hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e536aafb809ed6ff9811f384a52dcc866e9d4eb2 | 649 | cpp | C++ | Solutions/LASTDIG.cpp | sjnonweb/spoj | 72cf2afcf4466f1356a8646b5e4f925144cb9172 | [
"MIT"
] | 1 | 2016-10-05T20:07:03.000Z | 2016-10-05T20:07:03.000Z | Solutions/LASTDIG.cpp | sjnonweb/spoj | 72cf2afcf4466f1356a8646b5e4f925144cb9172 | [
"MIT"
] | null | null | null | Solutions/LASTDIG.cpp | sjnonweb/spoj | 72cf2afcf4466f1356a8646b5e4f925144cb9172 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
long int test,a,b,i,j,unit,rem,cycle[4];
cin>>test;
while(test--)
{
cin>>a>>b;
a=a%10;
if(a==0)
{
cout<<"0"<<endl;
continue;
}
cycle[0]=0; i=0; j=1;
do
{
unit=(((int)pow(a,j))%10);
if(cycle[0]==unit)
break;
cycle[i]=unit;
i++;
j++;
}while(1);
rem=b%i;
if(rem==0)
cout<<cycle[i-1]<<endl;
else
cout<<cycle[rem-1]<<endl;
}
return 0;
}
| 17.540541 | 44 | 0.371341 | sjnonweb |
e5379e9ffc988fe521e8faee0d6cbd3b2244856c | 2,730 | cpp | C++ | code/src/tutos/2-map/main.cpp | guillaume-haerinck/imac-soutien-tower-defense | bfa7843803421189f2d9fa47c55d27d2851da454 | [
"MIT"
] | null | null | null | code/src/tutos/2-map/main.cpp | guillaume-haerinck/imac-soutien-tower-defense | bfa7843803421189f2d9fa47c55d27d2851da454 | [
"MIT"
] | null | null | null | code/src/tutos/2-map/main.cpp | guillaume-haerinck/imac-soutien-tower-defense | bfa7843803421189f2d9fa47c55d27d2851da454 | [
"MIT"
] | null | null | null | #ifdef _WIN32
#include <windows.h>
#endif
#define _USE_MATH_DEFINES
#include <cmath>
#include <spdlog/spdlog.h>
#include <SDL2/SDL.h>
#include <glad/glad.h>
#include <stdlib.h>
#include <stdio.h>
#include "core/gl-log-handler.hpp"
#include "core/init.hpp"
#include "entity.hpp"
#include "map.hpp"
static const Uint32 FRAMERATE_MILLISECONDS = 1000 / 60;
int main(int argc, char **argv) {
SDL_Window* window = imac::init();
if (window == nullptr) {
spdlog::critical("[INIT] Init not achieved !");
debug_break();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0);
// Entities
std::vector<Entity*> entities;
/* Map */
Map level1;
bool loop = true;
while (loop) {
Uint32 startTime = SDL_GetTicks();
glClear(GL_COLOR_BUFFER_BIT);
level1.draw();
/* Update des entités */
for (Entity* entity : entities) {
entity->update();
}
SDL_GL_SwapWindow(window);
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
loop = false;
break;
}
switch (e.type) {
case SDL_MOUSEBUTTONUP:
{
printf("clic en (%d, %d)\n", e.button.x, e.button.y);
glm::vec2 gridPos = level1.windowToGrid((float) e.button.x, (float) e.button.y);
spdlog::info("Grid x: {} y: {}", gridPos.x, gridPos.y);
MapTile tile = level1.getTile(gridPos.x, gridPos.y);
if (tile == MapTile::constructible) {
spdlog::info("I can construct here");
glm::vec2 winPos = level1.gridToWindow(gridPos.x, gridPos.y);
Entity* myNewEntity = new Entity(winPos.x, winPos.y);
entities.push_back(myNewEntity);
} else {
spdlog::warn("can't construct here");
}
}
break;
case SDL_KEYDOWN:
printf("touche pressee (code = %d)\n", e.key.keysym.sym);
break;
default:
break;
}
}
Uint32 elapsedTime = SDL_GetTicks() - startTime;
if (elapsedTime < FRAMERATE_MILLISECONDS) {
SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime);
}
}
/* Cleanup */
SDL_DestroyWindow(window);
SDL_Quit();
for (Entity* entity : entities) {
delete entity;
}
return EXIT_SUCCESS;
}
| 28.14433 | 104 | 0.503663 | guillaume-haerinck |
e53a6173782ff0b52a492f8f00f1f3d1d8b9605b | 1,234 | cpp | C++ | Views/createrankview.cpp | MehmetHY/MilitaryOutpostManagement-Qt5 | fec112b5496d64e7b4826f05a84647848e49d78d | [
"MIT"
] | null | null | null | Views/createrankview.cpp | MehmetHY/MilitaryOutpostManagement-Qt5 | fec112b5496d64e7b4826f05a84647848e49d78d | [
"MIT"
] | null | null | null | Views/createrankview.cpp | MehmetHY/MilitaryOutpostManagement-Qt5 | fec112b5496d64e7b4826f05a84647848e49d78d | [
"MIT"
] | null | null | null | #include "createrankview.h"
#include "ui_createrankview.h"
#include "../mainwindow.h"
#include "manageranksview.h"
#include "QMessageBox"
#include "../Models/rank.h"
CreateRankView::CreateRankView(MainWindow *parent) :
QWidget(parent),
mainWindow(parent),
ui(new Ui::CreateRankView)
{
ui->setupUi(this);
connect(ui->backButton, &QPushButton::pressed, this, &CreateRankView::handleBackButtonPressed);
connect(ui->createButton, &QPushButton::pressed, this, &CreateRankView::handleCreateButtonPressed);
}
CreateRankView::~CreateRankView()
{
delete ui;
}
void CreateRankView::handleCreateButtonPressed() const
{
QString name = ui->lineEdit->text().trimmed();
if (name.isEmpty())
{
QMessageBox::warning(mainWindow, "Invalid Input", "Name cannot be empty!");
return;
}
if (Rank::isRankExist(name))
{
QMessageBox::warning(mainWindow, "Invalid Input", "Rank " + name + " already exist!");
return;
}
ui->lineEdit->clear();
Rank::createRank(name);
QMessageBox::information(mainWindow, "Success", "Rank created!");
}
void CreateRankView::handleBackButtonPressed() const
{
mainWindow->changeRootWidget(new ManageRanksView(mainWindow));
}
| 27.422222 | 103 | 0.691248 | MehmetHY |
e53a87307196e71bdaa29b0b31d6427838139570 | 16,901 | cpp | C++ | IMS_ModuleFunction_Comm.cpp | TheNewBob/IMS2 | 572dcfd4c3621458f01278713437c2aca526d2e6 | [
"MIT"
] | 2 | 2018-01-28T20:07:52.000Z | 2018-03-01T22:41:39.000Z | IMS_ModuleFunction_Comm.cpp | TheNewBob/IMS2 | 572dcfd4c3621458f01278713437c2aca526d2e6 | [
"MIT"
] | 6 | 2017-08-26T10:24:48.000Z | 2018-01-28T13:45:34.000Z | IMS_ModuleFunction_Comm.cpp | TheNewBob/IMS2 | 572dcfd4c3621458f01278713437c2aca526d2e6 | [
"MIT"
] | null | null | null | #include "GuiIncludes.h"
#include "Common.h"
#include "ModuleFunctionIncludes.h"
#include "StateMachineIncludes.h"
#include "IMS_ModuleFunctionData_Comm.h"
#include "GUI_ModuleFunction_Base.h"
#include "GUI_ModuleFunction_Comm.h"
#include "IMS_ModuleFunction_Comm.h"
IMS_ModuleFunction_Comm::IMS_ModuleFunction_Comm(IMS_ModuleFunctionData_Comm *_data, IMS_Module *_module, bool creategui)
: IMS_ModuleFunction_Base(_data, _module, MTYPE_COMM), data(_data)
{
//check which actions are actually supported by the config
bool hasdeployment = data->deployanimname != "";
bool hasscanning = data->searchanimname != "";
bool hastracking = data->trackinganimname != "";
if (creategui)
{
//add our GUI to the module's GUI page
menu = new GUI_ModuleFunction_Comm(this, module->GetGui(), hasdeployment, hasscanning, hastracking);
}
//set up the statemachine
//create the states the module function can be in
//deployed is the natural stagin state for everything else. basically,
//if a module function doesn't support deployment, what it actually doesn't
//support is retracting. The function will just be regarded as permanently deployed
state.AddState(COMMSTATE_DEPLOYED, "deployed");
if (hasdeployment)
{
state.AddState(COMMSTATE_RETRACTED, "retracted");
state.AddState(COMMSTATE_DEPLOYING, "deploying", false);
state.AddState(COMMSTATE_RETRACTING, "retracting", false);
}
if (hasscanning)
{
state.AddState(COMMSTATE_SEARCHING, "scanning");
state.AddState(COMMSTATE_STOP_SEARCHING, "resetting", false);
}
if (hastracking)
{
state.AddState(COMMSTATE_ALIGNING, "aligning", false);
state.AddState(COMMSTATE_TRACKING, "tracking");
state.AddState(COMMSTATE_STOP_TRACKING, "resetting", false);
}
//connect the states to create a statemap
if (hasdeployment)
{
state.ConnectStateTo(COMMSTATE_RETRACTED, COMMSTATE_DEPLOYING); //if antenna retracted, it can move to deploying state
state.ConnectStateTo(COMMSTATE_DEPLOYING, COMMSTATE_DEPLOYED); //if antenna deploying, it can move to deployed state
state.ConnectStateTo(COMMSTATE_DEPLOYED, COMMSTATE_RETRACTING); //if antenna deployed, it can move to retracting state
state.ConnectStateTo(COMMSTATE_RETRACTING, COMMSTATE_RETRACTED); //if antenna retracting, it can move to retracted state
state.ConnectStateTo(COMMSTATE_RETRACTING, COMMSTATE_DEPLOYING); //antenna can be retracted while it is deploying
state.ConnectStateTo(COMMSTATE_DEPLOYING, COMMSTATE_RETRACTING); //antenna can be deployed while it is retracting
}
if (hasscanning)
{
state.ConnectStateTo(COMMSTATE_DEPLOYED, COMMSTATE_SEARCHING); //etc
state.ConnectStateTo(COMMSTATE_SEARCHING, COMMSTATE_STOP_SEARCHING);
state.ConnectStateTo(COMMSTATE_STOP_SEARCHING, COMMSTATE_DEPLOYED);
}
if (hastracking)
{
state.ConnectStateTo(COMMSTATE_DEPLOYED, COMMSTATE_ALIGNING);
state.ConnectStateTo(COMMSTATE_ALIGNING, COMMSTATE_TRACKING);
state.ConnectStateTo(COMMSTATE_TRACKING, COMMSTATE_ALIGNING);
state.ConnectStateTo(COMMSTATE_TRACKING, COMMSTATE_STOP_TRACKING);
state.ConnectStateTo(COMMSTATE_ALIGNING, COMMSTATE_STOP_TRACKING); //the aligning state can skip the tracking state and move to the stop tracking state. This is one of the rare occasions where two intermediate states are connected directly
state.ConnectStateTo(COMMSTATE_STOP_TRACKING, COMMSTATE_DEPLOYED);
state.ConnectStateTo(COMMSTATE_STOP_TRACKING, COMMSTATE_ALIGNING);
}
}
IMS_ModuleFunction_Comm::~IMS_ModuleFunction_Comm()
{
}
void IMS_ModuleFunction_Comm::PostLoad()
{
if (!state.IsInitialised())
{
//setting the initial state of the statemachine, as it wasn't loaded from scenario
if (data->deployanimname != "")
{
state.SetInitialState(COMMSTATE_RETRACTED);
}
else
{
//if deployment is not supported, the antenna is
//actually considered permanently deployed
state.SetInitialState(COMMSTATE_DEPLOYED);
}
menu->SetStateDescription(state.GetStateDescription());
}
else
{
//states were loaded from scenario, initialise the control visuals
//initialise the control visuals
menu->SetStateDescription(state.GetStateDescription());
int curstate = state.GetState();
if (curstate != COMMSTATE_RETRACTED)
{
if (curstate == COMMSTATE_DEPLOYING || curstate == COMMSTATE_RETRACTING)
{
menu->SetDeployBoxState(BLINKING);
}
else
{
menu->SetDeployBoxState(ON);
if (curstate == COMMSTATE_SEARCHING)
{
menu->SetSearchBoxState(ON);
}
else if (curstate == COMMSTATE_TRACKING)
{
menu->SetTrackBoxState(ON);
}
else
{
if (curstate == COMMSTATE_STOP_SEARCHING)
{
menu->SetSearchBoxState(BLINKING);
}
else if (curstate == COMMSTATE_ALIGNING ||
curstate == COMMSTATE_STOP_TRACKING)
{
menu->SetTrackBoxState(BLINKING);
}
}
}
}
int tgtstate = state.GetTargetState();
if (tgtstate != curstate)
{
if (tgtstate == COMMSTATE_RETRACTED)
{
menu->SetDeployBoxState(BLINKING);
}
else if (tgtstate == COMMSTATE_SEARCHING)
{
menu->SetSearchBoxState(BLINKING);
}
else if (tgtstate == COMMSTATE_TRACKING)
{
menu->SetTrackBoxState(BLINKING);
}
}
}
}
GUI_ModuleFunction_Base *IMS_ModuleFunction_Comm::GetGui()
{
return menu;
}
void IMS_ModuleFunction_Comm::PreStep(double simdt, IMS2 *vessel)
{
//don't forget to call the prestep function of the base class!
IMS_ModuleFunction_Base::PreStep(simdt, vessel);
//check if the state has changed during the last frame,
//and whether we reached the target state
if (state.StateChanged())
{
//state has changed, update the state description on the gui
menu->SetStateDescription(state.GetStateDescription());
//first get the current event. This will immediately advance the state to the next
//state if it is secure, so don't call GetStateAndAdvance twice in a frame.
//then take appropriate action depending on what state we ended up in
//in the case of this module function, this simply takes the form of starting
//the necessary animations
switch (state.GetStateAndAdvance())
{
case COMMSTATE_DEPLOYING:
addEvent(new StartAnimationEvent(data->deployanimname, 1.0));
menu->SetDeployBoxState(BLINKING);
break;
case COMMSTATE_RETRACTING:
addEvent(new StartAnimationEvent(data->deployanimname, -1.0));
menu->SetDeployBoxState(BLINKING);
break;
case COMMSTATE_STOP_SEARCHING:
addEvent(new StopAnimationEvent(data->searchanimname));
menu->SetSearchBoxState(BLINKING);
break;
case COMMSTATE_STOP_TRACKING:
addEvent(new StopAnimationEvent(data->trackinganimname));
menu->SetTrackBoxState(BLINKING);
break;
case COMMSTATE_ALIGNING:
//check if we have a target selected
if (targetname != "")
{
menu->SetTrackBoxState(BLINKING);
addEvent(new StartTrackingAnimationEvent(data->trackinganimname, 1.0, oapiGetObjectByName((char*)targetname.data())));
}
else
{
menu->SetTargetDescription("set a valid target for tracking!", true);
menu->SetTrackBoxState(OFF);
state.SetTargetState(COMMSTATE_DEPLOYED);
}
break;
case COMMSTATE_SEARCHING:
addEvent(new StartAnimationEvent(data->searchanimname, 1.0));
menu->SetSearchBoxState(ON);
break;
case COMMSTATE_TRACKING:
menu->SetTrackBoxState(ON);
break;
case COMMSTATE_DEPLOYED:
menu->SetSearchBoxState(OFF);
menu->SetTrackBoxState(OFF);
menu->SetDeployBoxState(ON);
break;
case COMMSTATE_RETRACTED:
menu->SetSearchBoxState(OFF);
menu->SetTrackBoxState(OFF);
menu->SetDeployBoxState(OFF);
break;
}
}
}
void IMS_ModuleFunction_Comm::AddFunctionToVessel(IMS2 *vessel)
{
}
void IMS_ModuleFunction_Comm::CommandDeploy()
{
if (data->deployanimname == "") return;
if (state.GetState() != COMMSTATE_RETRACTED)
{
//if the state is not currently retracted, clicking the deployment box is interpreted as an order to retract
state.SetTargetState(COMMSTATE_RETRACTED);
menu->SetDeployBoxState(BLINKING);
}
else
{
//if it is retracted, we interpret it as an order to deploy
state.SetTargetState(COMMSTATE_DEPLOYED);
menu->SetDeployBoxState(BLINKING);
}
//if the current state is stable, advance it.
//if the current state is an Intermediate one, the state
//will be advanced by an event at the proper time
state.AdvanceStateSecure();
}
void IMS_ModuleFunction_Comm::CommandSearch()
{
if (data->searchanimname == "") return;
//if the comm is currently searching, stop searching
if (state.GetState() == COMMSTATE_SEARCHING)
{
state.SetTargetState(COMMSTATE_DEPLOYED);
menu->SetSearchBoxState(BLINKING);
}
else
{
//otherwise, we want to start searching
state.SetTargetState(COMMSTATE_SEARCHING);
menu->SetSearchBoxState(BLINKING);
}
state.AdvanceStateSecure();
}
void IMS_ModuleFunction_Comm::CommandTrack()
{
if (data->trackinganimname == "") return;
int curstate = state.GetState();
if (curstate == COMMSTATE_TRACKING ||
curstate == COMMSTATE_ALIGNING)
{
//if the comm is currently tracking or aligning, we want it to stop and get back to deployed state
state.SetTargetState(COMMSTATE_DEPLOYED);
menu->SetTrackBoxState(BLINKING);
}
else
{
state.SetTargetState(COMMSTATE_TRACKING);
menu->SetTrackBoxState(BLINKING);
}
state.AdvanceStateSecure();
}
void IMS_ModuleFunction_Comm::CommandSetTarget()
{
if (data->trackinganimname == "") return;
//open an input callback for the user to set the target
oapiOpenInputBox("enter target", SetTargetInputCallback, NULL, 15, this);
}
void IMS_ModuleFunction_Comm::SetTarget(string target)
{
if (data->trackinganimname == "") return;
OBJHANDLE checktarget = oapiGetObjectByName((char*)target.data());
int currentstate = state.GetState();
if (checktarget == NULL)
{
//if an invalid target was entered, display an error message
menu->SetTargetDescription("invalid target!", true);
//if the antenna is currently tracking or aligning with a previous target,
//stop it and bring it back to origin
if (currentstate == COMMSTATE_TRACKING ||
currentstate == COMMSTATE_ALIGNING)
{
state.SetTargetState(COMMSTATE_DEPLOYED);
}
targetname = "";
}
else
{
//a valid target was entered, update state, animation and gui
menu->SetTargetDescription(target);
targetname = target;
if (currentstate == COMMSTATE_TRACKING ||
currentstate == COMMSTATE_ALIGNING)
{
addEvent(new ModifyTrackingAnimationEvent(data->trackinganimname, 0.0, checktarget));
state.SetTargetState(COMMSTATE_TRACKING);
}
}
state.AdvanceStateSecure();
}
bool IMS_ModuleFunction_Comm::ProcessEvent(Event_Base *e)
{
if (*e == ANIMATIONFINISHEDEVENT)
{
//the animation that has finished is on of ours,
//that means that an intermediate state has reached its end
//we don't even have to know which one. That's what we have the statemachine for.
AnimationFinishedEvent *anim = (AnimationFinishedEvent*)e;
string id = anim->GetAnimationId();
if (id == data->deployanimname ||
id == data->searchanimname ||
id == data->trackinganimname)
{
state.AdvanceState();
}
}
else if (*e == ANIMATIONFAILEDEVENT)
{
//an animation has failed to start, probably due to an unfulfilled dependency.
//we need to take action!
AnimationFailedEvent *anim = (AnimationFailedEvent*)e;
string id = anim->GetAnimationId();
int curstate = state.GetState();
if (id == data->deployanimname)
{
//we'll have to know what direction the animation was supposed to move
if (anim->GetSpeed() < 0 && curstate == COMMSTATE_RETRACTING)
{
GUImanager::Alert(data->GetName() + ": unable to retract at the moment!", module->GetGui()->GetFirstVisibleChild(),
_R(0, 0, 0, 0), STYLE_ERROR, module->GetGui()->GetStyleSet());
state.SetTargetState(COMMSTATE_DEPLOYED);
}
else if (anim->GetSpeed() > 0 && curstate == COMMSTATE_DEPLOYING)
{
GUImanager::Alert(data->GetName() + ": unable to deploy at the moment!", module->GetGui()->GetFirstVisibleChild(),
_R(0, 0, 0, 0), STYLE_ERROR, module->GetGui()->GetStyleSet());
state.SetTargetState(COMMSTATE_RETRACTED);
}
}
else if (id == data->searchanimname && curstate == COMMSTATE_SEARCHING)
{
GUImanager::Alert(data->GetName() + ": unable to scan at the moment!", module->GetGui()->GetFirstVisibleChild(),
_R(0, 0, 0, 0), STYLE_ERROR, module->GetGui()->GetStyleSet());
state.SetTargetState(COMMSTATE_DEPLOYED);
}
else if (id == data->trackinganimname && curstate == COMMSTATE_ALIGNING)
{
GUImanager::Alert(data->GetName() + ": unable to start tracking at the moment!", module->GetGui()->GetFirstVisibleChild(),
_R(0, 0, 0, 0), STYLE_ERROR, module->GetGui()->GetStyleSet());
state.SetTargetState(COMMSTATE_DEPLOYED);
}
state.AdvanceStateSecure();
}
else if (*e == ANIMATIONSTARTEDEVENT)
{
//an animation has been started. Probably it was started by this module function, in which case we don't need to do anything.
//but if module functions have shared animations, the state of this module function must now change.
AnimationStartedEvent *ev = (AnimationStartedEvent*)e;
string animid = ev->GetAnimationId();
int curstate = state.GetState();
if (animid == data->deployanimname)
{
//check if the started animation concerns this function, and whether it needs to change state as a result
if (ev->GetSpeed() > 0 && curstate == COMMSTATE_RETRACTED)
{
state.SetTargetState(COMMSTATE_DEPLOYED);
state.AdvanceStateSecure();
}
else if (ev->GetSpeed() < 0 && curstate == COMMSTATE_DEPLOYED)
{
state.SetTargetState(COMMSTATE_RETRACTED);
state.AdvanceStateSecure();
}
}
else if (animid == data->searchanimname && curstate == COMMSTATE_DEPLOYED)
{
state.SetTargetState(COMMSTATE_SEARCHING);
state.AdvanceStateSecure();
}
else if (animid == data->trackinganimname && curstate == COMMSTATE_DEPLOYED)
{
state.SetTargetState(COMMSTATE_TRACKING);
state.AdvanceStateSecure();
}
}
else if (*e == TRACKINGANIMATIONSTATUSEVENT)
{
//while the array is tracking, we get a status update every frame.
//Currently, we're only interested if the array is aligning or aligned
TrackingAnimationStatusEvent *status = (TrackingAnimationStatusEvent*)e;
//check if the status update is actually for this modulefunction, and whether it has changed
if (status->GetAnimationId() == data->trackinganimname && status->GetStatus() != lasttrackingstatus)
{
//if the antenna was unable to track the target before,
//we have to update the state display to make the error message disapear
if (lasttrackingstatus == UNABLE)
{
menu->SetStateDescription(state.GetStateDescription());
}
if (status->GetStatus() == ALIGNED)
{
if (state.GetState() == COMMSTATE_ALIGNING)
{
//the array has just aligned itself with the target, update the statemachine
state.AdvanceState();
}
}
else if (status->GetStatus() == ALIGNING)
{
if (state.GetState() == COMMSTATE_TRACKING)
{
state.SetTargetState(COMMSTATE_TRACKING);
}
}
else if (status->GetStatus() == REVERTING)
{
if (state.GetState() == COMMSTATE_ALIGNING ||
state.GetState() == COMMSTATE_TRACKING)
{
//the array is on its way back to deployed position. Stop whatever it is it's doing right now
state.AdvanceState();
}
}
else if (status->GetStatus() == UNABLE)
{
//the array is unable to align with the specified target.
//print an error message to the gui.
menu->SetStateDescription("unable to align with " + targetname + "!", true);
}
lasttrackingstatus = status->GetStatus();
}
}
return false;
}
void IMS_ModuleFunction_Comm::SaveState(FILEHANDLE scn)
{
int curstate, tgtstate;
curstate = state.GetState();
tgtstate = state.GetTargetState();
oapiWriteScenario_int(scn, "STATE", curstate);
if (tgtstate != curstate)
{
oapiWriteScenario_int(scn, "TGTSTATE", state.GetTargetState());
}
if (targetname != "")
{
//there is a tracking target set, so save that too
oapiWriteScenario_string(scn, "TRACKINGTGT", (char*)targetname.data());
}
}
bool IMS_ModuleFunction_Comm::processScenarioLine(string line)
{
if (line.substr(0, 5) == "STATE")
{
int curstate = atoi(line.substr(6).data());
state.SetInitialState(curstate);
return true;
}
else if (line.substr(0, 8) == "TGTSTATE")
{
int tgtstate = atoi(line.substr(9).data());
if (tgtstate != state.GetState())
{
state.SetTargetState(tgtstate);
}
return true;
}
else if (line.substr(0, 11) == "TRACKINGTGT")
{
targetname = line.substr(12);
menu->SetTargetDescription(targetname);
return true;
}
return false;
}
bool SetTargetInputCallback(void *id, char *str, void *usrdata)
{
if (strlen(str) == 0)
{
return false;
}
IMS_ModuleFunction_Comm *comm = (IMS_ModuleFunction_Comm*)usrdata;
comm->SetTarget(string(str));
return true;
}
| 30.50722 | 242 | 0.725993 | TheNewBob |
e53c3c786211debde0fdca51c2ed14a8c86bd230 | 2,253 | cpp | C++ | Object3D.cpp | moelatt/A-Simple-Ray-Tracing | c4625f5d9d55add47d10824eebae4c6c12af81f1 | [
"MIT"
] | null | null | null | Object3D.cpp | moelatt/A-Simple-Ray-Tracing | c4625f5d9d55add47d10824eebae4c6c12af81f1 | [
"MIT"
] | null | null | null | Object3D.cpp | moelatt/A-Simple-Ray-Tracing | c4625f5d9d55add47d10824eebae4c6c12af81f1 | [
"MIT"
] | null | null | null | #include "main.h"
using namespace std;
void phongLight(scene& objectScene, vecRay pos, int number, float r){
for (int i = 0; i < number; i++) {
float t = 2 * M_PI / number * i;
light* lig = new light(pos + vecRay(r * cos(t), r * sin(t), 0), RGB(1, 1, 1) , 1.0 / number);
objectScene.LightAdd(lig);
}
}
void Sphere(scene& objectScene, vecRay pos, float r =0.5f, RGB col = RGB(0, 0, 1), bool ref =false) {
sphereGraph* s = new sphereGraph(r, pos);
s->natrualColor = col;
s->reflective = ref;
objectScene.ObjectAdd(s);
}
void plane(scene& objectScene, vecRay pos, vecRay dir, RGB col =RGB(0, 0.5, 0.5)){
objectPlane* p = new objectPlane(pos, vecRay(0, 0, 1)^dir);
p->natrualColor = col;
p->k_spec = 0;
objectScene.ObjectAdd(p);
}
void plane1(scene& objectScene, vecRay pos, RGB col = RGB(0, 1, 0),char inte = 'c'){
switch (inte){ objectPlane* obj;
case 'c':
obj = new objectPlane(pos, vecRay(0, 0, -1));
obj->natrualColor = col;
obj->k_spec = 0;
objectScene.ObjectAdd(obj); break;
case 'f':
obj = new objectPlane(pos, vecRay(0, 0, 1));
obj->natrualColor = col;
obj->k_spec = 0;
objectScene.ObjectAdd(obj); break;
default:break;
}
}
void DrawObject(scene& objectScene, float ir, float kr, float transparent) {
Sphere(objectScene, vecRay(1.5, 0.0, 1.2), 0.5, RGB(0.9, 0.5, 0), false);
Sphere(objectScene, vecRay(1.2, 0.0, 0.0), 0.5, RGB(0.5, 0.8, 1), false);
sphereGraph* sph1 = new sphereGraph(0.5, vecRay(1.5, 1.4, 1.2));
sph1->natrualColor = RGB(1, 0.1, 0.1);
sph1->reflective = true;
sph1->I_refl = ir;
sph1->k_spec = kr;
sph1->I_refr = 2;
sph1->transparency = transparent;
objectScene.ObjectAdd(sph1);
sphereGraph* sph2 = new sphereGraph(0.5, vecRay(1.5, -1.4, 1.2));
sph2->natrualColor = RGB(0.1, 1,0.1);
sph2->reflective = true;
sph2->I_refl = ir;
sph1->I_refr = 2;
sph2->k_spec = kr;
sph2->transparency = transparent;
objectScene.ObjectAdd(sph2);
RGB gray(0.2,0.2,0.2), red(1, 0, 0);
RGB green(0.3, 0.3, 0.3), blue(0.3, 0.0, 0.5);
plane(objectScene, vecRay(3, 0, -0.5), vecRay(0, 1, 0), gray * 0.4);
plane1(objectScene, vecRay(0, 0, +3.5), gray * 0.4, 'c');
plane1(objectScene, vecRay(0, 0, -0.5), gray * 0.4, 'f');
phongLight(objectScene, vecRay(-0.8, 0, 3), 1, 0.1);
} | 33.626866 | 101 | 0.634265 | moelatt |
e53ff1e5f9a3e954c7fbcef3156f38af3b6f12ce | 7,249 | cpp | C++ | src/demos/boxesDemo.cpp | VladimirV99/GLSandbox | 25987e630ace304ab756153cd31b5dcb2a7a67cf | [
"Unlicense"
] | null | null | null | src/demos/boxesDemo.cpp | VladimirV99/GLSandbox | 25987e630ace304ab756153cd31b5dcb2a7a67cf | [
"Unlicense"
] | null | null | null | src/demos/boxesDemo.cpp | VladimirV99/GLSandbox | 25987e630ace304ab756153cd31b5dcb2a7a67cf | [
"Unlicense"
] | null | null | null | #include "boxesDemo.hpp"
BoxesDemo::BoxesDemo() : shader("../assets/boxes.vert.glsl", "../assets/boxes.frag.glsl") { }
void BoxesDemo::Init(GLFWwindow* window)
{
// Load texture
texture = loadTexture("../assets/wall.jpg");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// color attribute
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
// texture coord attribute
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(9 * sizeof(float)));
glEnableVertexAttribArray(3);
shader.use();
shader.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
shader.setVec3("lightPos", lightPos);
shader.setVec3("viewPos", camera.getPosition());
}
void BoxesDemo::Draw(GLFWwindow* window)
{
// world space positions of our cubes
glm::vec3 cubePositions[] = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3( 2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3( 1.3f, -2.0f, -2.5f),
glm::vec3( 1.5f, 2.0f, -2.5f),
glm::vec3( 1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
shader.use();
shader.setVec3("viewPos", camera.getPosition());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
shader.use();
// pass projection matrix to shader (note that in this case it could change every frame)
glm::mat4 projection = glm::perspective(glm::radians(camera.getZoom()), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
shader.setMat4("projection", projection);
// camera/view transformation
glm::mat4 view = camera.GetViewMatrix();
shader.setMat4("view", view);
float angle = 3.1415f / 3;
glm::mat4 model = glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0.0f,0.0f,1.0f));
// GLuint location = glGetUniformLocation(programHandle, "model");
// if( location >= 0 ) {
// glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(model));
// }
shader.setMat4("model", model);
// render boxes
glBindVertexArray(VAO);
for (unsigned int i = 0; i < 10; i++)
{
// calculate the model matrix for each object and pass it to shader before drawing
glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
model = glm::translate(model, cubePositions[i]);
float angle = 20.0f * i;
model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
}
void BoxesDemo::Unload()
{
glDeleteTextures(1, &texture);
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
}
void BoxesDemo::ProcessKeyboard(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
void BoxesDemo::ProcessMouse(GLFWwindow* window, double xpos, double ypos, double xoffset, double yoffset)
{
camera.ProcessMouseMovement(xoffset, yoffset);
}
void BoxesDemo::ProcessScroll(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
bool BoxesDemo::DrawMenu()
{
ImGui::BulletText("Press WASD to move");
ImGui::BulletText("Use the mouse to look around");
return true;
} | 41.422857 | 128 | 0.554559 | VladimirV99 |
e542215953900b60bfb3b84aaf60daaa1586c807 | 8,209 | cpp | C++ | src/mongo/dbtests/query_stage_sort.cpp | fjonath1/mongodb-ros-osx | 31a58cab426b68ce85ef231200ff45d4bd691d32 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/query_stage_sort.cpp | fjonath1/mongodb-ros-osx | 31a58cab426b68ce85ef231200ff45d4bd691d32 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/query_stage_sort.cpp | fjonath1/mongodb-ros-osx | 31a58cab426b68ce85ef231200ff45d4bd691d32 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/client/dbclientcursor.h"
#include "mongo/db/exec/fetch.h"
#include "mongo/db/exec/mock_stage.h"
#include "mongo/db/exec/plan_stage.h"
#include "mongo/db/exec/sort.h"
#include "mongo/db/index/catalog_hack.h"
#include "mongo/db/instance.h"
#include "mongo/db/json.h"
#include "mongo/db/query/plan_executor.h"
#include "mongo/dbtests/dbtests.h"
/**
* This file tests db/exec/sort.cpp
*/
namespace QueryStageSortTests {
class QueryStageSortTestBase {
public:
QueryStageSortTestBase() { }
void fillData() {
for (int i = 0; i < numObj(); ++i) {
insert(BSON("foo" << i));
}
}
virtual ~QueryStageSortTestBase() {
_client.dropCollection(ns());
}
void insert(const BSONObj& obj) {
_client.insert(ns(), obj);
}
void getLocs(set<DiskLoc>* locs) {
for (boost::shared_ptr<Cursor> c = theDataFileMgr.findAll(ns());
c->ok(); c->advance()) {
locs->insert(c->currLoc());
}
}
/**
* We feed a mix of (key, unowned, owned) data to the sort stage.
*/
void insertVarietyOfObjects(MockStage* ms) {
set<DiskLoc> locs;
getLocs(&locs);
set<DiskLoc>::iterator it = locs.begin();
for (int i = 0; i < numObj(); ++i, ++it) {
// Insert some owned obj data.
WorkingSetMember member;
member.state = WorkingSetMember::OWNED_OBJ;
member.obj = it->obj().getOwned();
ASSERT(member.obj.isOwned());
ms->pushBack(member);
}
}
// Return a value in the set {-1, 0, 1} to represent the sign of parameter i. Used to
// normalize woCompare calls.
int sgn(int i) {
if (i == 0)
return 0;
return i > 0 ? 1 : -1;
}
/**
* A template used by many tests below.
* Fill out numObj objects, sort them in the order provided by 'direction'.
* If extAllowed is true, sorting will use use external sorting if available.
* If limit is not zero, we limit the output of the sort stage to 'limit' results.
*/
void sortAndCheck(int direction) {
WorkingSet* ws = new WorkingSet();
MockStage* ms = new MockStage(ws);
// Insert a mix of the various types of data.
insertVarietyOfObjects(ms);
SortStageParams params;
params.pattern = BSON("foo" << direction);
// Must fetch so we can look at the doc as a BSONObj.
PlanExecutor runner(ws, new FetchStage(ws, new SortStage(params, ws, ms), NULL));
// Look at pairs of objects to make sure that the sort order is pairwise (and therefore
// totally) correct.
BSONObj last;
ASSERT_EQUALS(Runner::RUNNER_ADVANCED, runner.getNext(&last, NULL));
// Count 'last'.
int count = 1;
BSONObj current;
while (Runner::RUNNER_ADVANCED == runner.getNext(¤t, NULL)) {
int cmp = sgn(current.woSortOrder(last, params.pattern));
// The next object should be equal to the previous or oriented according to the sort
// pattern.
ASSERT(cmp == 0 || cmp == 1);
++count;
last = current;
}
// No limit, should get all objects back.
ASSERT_EQUALS(numObj(), count);
}
virtual int numObj() = 0;
static const char* ns() { return "unittests.QueryStageSort"; }
private:
static DBDirectClient _client;
};
DBDirectClient QueryStageSortTestBase::_client;
// Sort some small # of results in increasing order.
class QueryStageSortInc: public QueryStageSortTestBase {
public:
virtual int numObj() { return 100; }
void run() {
Client::WriteContext ctx(ns());
fillData();
sortAndCheck(1);
}
};
// Sort some small # of results in decreasing order.
class QueryStageSortDec : public QueryStageSortTestBase {
public:
virtual int numObj() { return 100; }
void run() {
Client::WriteContext ctx(ns());
fillData();
sortAndCheck(-1);
}
};
// Sort a big bunch of objects.
class QueryStageSortExt : public QueryStageSortTestBase {
public:
virtual int numObj() { return 10000; }
void run() {
Client::WriteContext ctx(ns());
fillData();
sortAndCheck(-1);
}
};
// Invalidation of everything fed to sort.
class QueryStageSortInvalidation : public QueryStageSortTestBase {
public:
virtual int numObj() { return 2000; }
void run() {
Client::WriteContext ctx(ns());
fillData();
// The data we're going to later invalidate.
set<DiskLoc> locs;
getLocs(&locs);
// Build the mock stage which feeds the data.
WorkingSet ws;
auto_ptr<MockStage> ms(new MockStage(&ws));
insertVarietyOfObjects(ms.get());
SortStageParams params;
params.pattern = BSON("foo" << 1);
auto_ptr<SortStage> ss(new SortStage(params, &ws, ms.get()));
const int firstRead = 10;
// Have sort read in data from the mock stage.
for (int i = 0; i < firstRead; ++i) {
WorkingSetID id;
PlanStage::StageState status = ss->work(&id);
ASSERT_NOT_EQUALS(PlanStage::ADVANCED, status);
}
// We should have read in the first 'firstRead' locs. Invalidate the first.
ss->prepareToYield();
set<DiskLoc>::iterator it = locs.begin();
ss->invalidate(*it++);
ss->recoverFromYield();
// Read the rest of the data from the mock stage.
while (!ms->isEOF()) {
WorkingSetID id;
ss->work(&id);
}
// Release to prevent double-deletion.
ms.release();
// Let's just invalidate everything now.
ss->prepareToYield();
while (it != locs.end()) {
ss->invalidate(*it++);
}
ss->recoverFromYield();
// The sort should still work.
int count = 0;
while (!ss->isEOF()) {
WorkingSetID id;
PlanStage::StageState status = ss->work(&id);
if (PlanStage::ADVANCED != status) { continue; }
WorkingSetMember* member = ws.get(id);
ASSERT(member->hasObj());
ASSERT(!member->hasLoc());
++count;
}
// We've invalidated everything, but only 2/3 of our data had a DiskLoc to be
// invalidated. We get the rest as-is.
ASSERT_EQUALS(count, numObj());
}
};
class All : public Suite {
public:
All() : Suite( "query_stage_sort_test" ) { }
void setupTests() {
add<QueryStageSortInc>();
add<QueryStageSortDec>();
add<QueryStageSortExt>();
add<QueryStageSortInvalidation>();
}
} queryStageSortTest;
} // namespace
| 31.817829 | 100 | 0.543306 | fjonath1 |
e5448c5f8e635a35aa5e27820e321d3e5ce484e0 | 1,844 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Endian.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Endian.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Endian.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/Endian.cc,v 1.1 1992/06/20 17:40:19 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: Endian.cc,v $
* Revision 1.1 1992/06/20 17:40:19 lewis
* Initial revision
*
Revision 1.2 1992/04/29 23:45:43 lewis
*** empty log message ***
*
*
*/
#if qIncludeRCSIDs
static const char rcsid[] = "$Header: /fuji/lewis/RCS/Endian.cc,v 1.1 1992/06/20 17:40:19 lewis Exp $";
#endif
#include <iostream.h>
#include <stdlib.h>
static int BitOrder_LittleEndianP ();
static int ByteOrder_LittleEndianP ();
int main (int argc, char* argv[])
{
cout << "Testing to see if we are big or little endian\n";
cout << "Bit order is: " << (BitOrder_LittleEndianP ()? "Little": "Big") << " Endian\n";
cout << "Byte order is: " << (ByteOrder_LittleEndianP ()? "Little": "Big") << " Endian\n";
return (0);
}
static int BitOrder_LittleEndianP ()
{
// if we are little endian, then 1 becomes two when shifted left, and if we are
// big endian, then it should get shifted off into lala land, and become zero
unsigned w = 1;
unsigned x = w << 1;
if (x == 0) {
return (0); // false
}
else if (x == 2) {
return (1); // true
}
else {
cerr << "Well maybe I still dont understand this stuff\n";
exit (1);
}
}
static int ByteOrder_LittleEndianP ()
{
unsigned long value = 0x44332211; // hope long >= 4 bytes!!!
char* vp = (char*)&value;
if ((vp[0] == 0x11) && (vp[1] == 0x22) && (vp[2] == 0x33) && (vp[3] == 0x44)) {
return (0); // false
}
else if ((vp[3] == 0x11) && (vp[2] == 0x22) && (vp[1] == 0x33) && (vp[0] == 0x44)) {
return (1); // true
}
else {
cerr << "Well maybe I still dont understand this stuff\n";
exit (1);
}
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
| 21.44186 | 103 | 0.598156 | SophistSolutions |
e54a93658c8b55d6f45b9a668a312f5a2a56fa00 | 2,924 | cpp | C++ | 2019/Day03/Day03.cpp | luddet/AdventOfCode | ad6b3dacabfb29e044d8e37bc305e2a8c83e943e | [
"MIT"
] | null | null | null | 2019/Day03/Day03.cpp | luddet/AdventOfCode | ad6b3dacabfb29e044d8e37bc305e2a8c83e943e | [
"MIT"
] | null | null | null | 2019/Day03/Day03.cpp | luddet/AdventOfCode | ad6b3dacabfb29e044d8e37bc305e2a8c83e943e | [
"MIT"
] | null | null | null | // https://adventofcode.com/2019/day/3
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
struct Coord
{
int x;
int y;
};
struct Line
{
Coord start;
Coord end;
};
// Manhattan length
int length(const Coord& coord)
{
return std::abs(coord.x) + std::abs(coord.y);
}
int length(const Line& line)
{
return std::abs(line.end.x - line.start.x) + std::abs(line.end.y - line.start.y);
}
bool intersects(const Line& line1, const Line& line2, Coord& intersecionPoint)
{
int minX1 = std::min(line1.start.x, line1.end.x);
int minY1 = std::min(line1.start.y, line1.end.y);
int maxX1 = std::max(line1.start.x, line1.end.x);
int maxY1 = std::max(line1.start.y, line1.end.y);
int minX2 = std::min(line2.start.x, line2.end.x);
int minY2 = std::min(line2.start.y, line2.end.y);
int maxX2 = std::max(line2.start.x, line2.end.x);
int maxY2 = std::max(line2.start.y, line2.end.y);
if (maxX1 < minX2 || minX1 > maxX2 || maxY1 < minY2 || minY1 > maxY2)
return false;
intersecionPoint.x = minX1 == maxX1 ? minX1 : minX2;
intersecionPoint.y = minY1 == maxY1 ? minY1 : minY2;
return true;
}
std::vector<Line> parseLine(std::string& line)
{
std::stringstream lineStream(line);
std::vector<Line> result;
Coord p1{ 0,0 };
char direction;
int distance;
while (lineStream >> direction >> distance)
{
Coord p2{ p1.x, p1.y };
switch (direction)
{
case 'U':
p2.y += distance;
break;
case 'R':
p2.x += distance;
break;
case 'D':
p2.y -= distance;
break;
case 'L':
p2.x -= distance;
break;
}
result.push_back(Line{ p1, p2 });
p1 = p2;
// eat comma
char _; lineStream >> _;
}
return result;
}
int main()
{
std::ifstream fs("input.txt");
std::string line1, line2;
std::getline(fs, line1);
std::getline(fs, line2);
std::vector<Line> wire1, wire2;
wire1 = parseLine(line1);
wire2 = parseLine(line2);
int closestDistance = INT_MAX;
int leastSteps = INT_MAX;
int wire1TotalSteps = 0;
for (size_t i = 0; i < wire1.size(); ++i)
{
int wire2TotalSteps = 0;
for (size_t j = 0; j < wire2.size(); ++j)
{
Coord intersection;
// don't check origin segments for intersections
if ((i != 0 || j != 0) && intersects(wire1[i], wire2[j], intersection))
{
closestDistance = std::min(closestDistance, length(intersection));
// delta from each wire segments start point to the intersection
Coord w1delta{ intersection.x - wire1[i].start.x, intersection.y - wire1[i].start.y };
Coord w2delta{ intersection.x - wire2[j].start.x, intersection.y - wire2[j].start.y };
leastSteps = std::min(leastSteps, wire1TotalSteps + wire2TotalSteps + length(w1delta) + length(w2delta));
}
wire2TotalSteps += length(wire2[j]);
}
wire1TotalSteps += length(wire1[i]);
}
std::cout << "Part 1: " << closestDistance << std::endl;
std::cout << "Part 2: " << leastSteps << std::endl;
}
| 22.84375 | 109 | 0.647743 | luddet |
e54fc090eccf003218a089668bfc96725925c1a9 | 942 | hpp | C++ | include/modules/sway/bar.hpp | Psykar/Waybar | a1129c4c87dd14beef771295aca911f3f9e799bc | [
"MIT"
] | null | null | null | include/modules/sway/bar.hpp | Psykar/Waybar | a1129c4c87dd14beef771295aca911f3f9e799bc | [
"MIT"
] | null | null | null | include/modules/sway/bar.hpp | Psykar/Waybar | a1129c4c87dd14beef771295aca911f3f9e799bc | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include "modules/sway/ipc/client.hpp"
#include "util/SafeSignal.hpp"
#include "util/json.hpp"
namespace waybar {
class Bar;
namespace modules::sway {
/*
* Supported subset of i3/sway IPC barconfig object
*/
struct swaybar_config {
std::string id;
std::string mode;
std::string hidden_state;
};
/**
* swaybar IPC client
*/
class BarIpcClient {
public:
BarIpcClient(waybar::Bar& bar);
private:
void onInitialConfig(const struct Ipc::ipc_response& res);
void onIpcEvent(const struct Ipc::ipc_response&);
void onConfigUpdate(const swaybar_config& config);
void onVisibilityUpdate(bool visible_by_modifier);
void update();
Bar& bar_;
util::JsonParser parser_;
Ipc ipc_;
swaybar_config bar_config_;
bool visible_by_modifier_ = false;
SafeSignal<bool> signal_visible_;
SafeSignal<swaybar_config> signal_config_;
};
} // namespace modules::sway
} // namespace waybar
| 18.84 | 60 | 0.733546 | Psykar |
e5568754493f67bb68185336cecf41822a020365 | 2,116 | cpp | C++ | src/color_management.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 930 | 2018-02-19T16:38:29.000Z | 2022-03-30T22:16:01.000Z | src/color_management.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 142 | 2018-02-19T16:14:28.000Z | 2022-03-25T13:51:08.000Z | src/color_management.cpp | hydrocarborane/polyscope | bee34c22cd7ac1b1e01686b55b7b8ceeee20d2fe | [
"MIT"
] | 92 | 2018-05-13T01:41:04.000Z | 2022-03-28T03:26:44.000Z | // Copyright 2017-2019, Nicholas Sharp and the Polyscope contributors. http://polyscope.run.
#include "polyscope/color_management.h"
// Use for color conversion scripts
#include "imgui.h"
#include <algorithm>
#include <cmath>
#include <iostream>
using std::cout;
using std::endl;
namespace polyscope {
namespace {
// == Color management helpers
// Clamp to [0,1]
float unitClamp(float x) { return std::max(0.0f, std::min(1.0f, x)); }
glm::vec3 unitClamp(glm::vec3 x) { return {unitClamp(x[0]), unitClamp(x[1]), unitClamp(x[2])}; }
// Used to sample colors. Samples a series of most-distant values from a range [0,1]
// offset from a starting value 'start' and wrapped around. index=0 returns start
//
// Example: if start = 0, emits f(0, i) = {0, 1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, ...}
// if start = 0.3 emits (0.3 + f(0, i)) % 1
float getIndexedDistinctValue(float start, int index) {
if (index < 0) {
return 0.0;
}
// Bit shifty magic to evaluate f()
float val = 0;
float p = 0.5;
while (index > 0) {
if (index % 2 == 1) {
val += p;
}
index = index >> 1;
p /= 2.0;
}
// Apply modular offset
val = std::fmod(val + start, 1.0);
return unitClamp(val);
}
// Get an indexed offset color. Inputs and outputs in RGB
glm::vec3 indexOffsetHue(glm::vec3 baseColor, int index) {
glm::vec3 baseHSV = RGBtoHSV(baseColor);
float newHue = getIndexedDistinctValue(baseHSV[0], index);
glm::vec3 outHSV = {newHue, baseHSV[1], baseHSV[2]};
return HSVtoRGB(outHSV);
}
// Keep track of unique structure colors
const glm::vec3 uniqueColorBase{28. / 255., 99. / 255., 227. / 255.};
int iUniqueColor = 0;
} // namespace
glm::vec3 getNextUniqueColor() { return indexOffsetHue(uniqueColorBase, iUniqueColor++); }
glm::vec3 RGBtoHSV(glm::vec3 rgb) {
glm::vec3 hsv;
ImGui::ColorConvertRGBtoHSV(rgb[0], rgb[1], rgb[2], hsv[0], hsv[1], hsv[2]);
return unitClamp(hsv);
}
glm::vec3 HSVtoRGB(glm::vec3 hsv) {
glm::vec3 rgb;
ImGui::ColorConvertHSVtoRGB(hsv[0], hsv[1], hsv[2], rgb[0], rgb[1], rgb[2]);
return unitClamp(rgb);
}
} // namespace polyscope
| 25.804878 | 96 | 0.651229 | hydrocarborane |
e557a824faa6e221484d57c294b9c763b7490482 | 8,099 | cpp | C++ | src/loramodem.cpp | 2ni/lorawan_modem | a0722eb937b3d687c2a20c6123873ad93e18cb16 | [
"MIT"
] | 5 | 2020-10-27T21:28:03.000Z | 2020-12-15T15:56:19.000Z | src/loramodem.cpp | 2ni/lorawan_modem | a0722eb937b3d687c2a20c6123873ad93e18cb16 | [
"MIT"
] | 2 | 2020-10-28T17:47:17.000Z | 2020-11-03T01:20:16.000Z | src/loramodem.cpp | 2ni/lorawan_modem | a0722eb937b3d687c2a20c6123873ad93e18cb16 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "loramodem.h"
LoRaWANModem::LoRaWANModem(uint8_t pin_cts, uint8_t pin_rts) : uart(LORA_TX, LORA_RX, NC, NC) {
_pin_cts = pin_cts;
_pin_rts = pin_rts;
}
void LoRaWANModem::begin() {
pinMode(_pin_rts, OUTPUT);
digitalWrite(_pin_rts, HIGH);
pinMode(_pin_cts, INPUT);
uart.begin(115200); // data bits 8, stop bits 1, parity none
while (!uart);
}
/*
* only sends a join command
* does not wait for network
*/
Status LoRaWANModem::command_join(const uint8_t *appeui, const uint8_t *appkey) {
Status s;
// should not be called if module joined or is joining network
// or it'll return 0x05 error
s = command(CMD_SETJOINEUI, appeui, 8);
if (s != OK) {
Serial.printf(DBG_ERR("set app eui error: 0x%02x."), (uint8_t)s);
if (s == BUSY) {
Serial.print(" Can't set appeui when joined/joining to network");
}
Serial.println();
return s;
}
s = command(CMD_SETNWKKEY, appkey, 16);
if (s != OK) {
Serial.printf(DBG_ERR("set appkey error: 0x%02x."), (uint8_t)s);
if (s == BUSY) {
Serial.println("Can't set appeui when joined/joining to network");
}
return s;
}
s = command(CMD_JOIN);
if (s != OK) {
Serial.printf(DBG_ERR("join error: 0x%02x") "\n", (uint8_t)s);
return s;
}
delay(25);
return OK;
}
bool LoRaWANModem::is_joining(void (*join_done)(Event_code code)) {
uint8_t len;
uint8_t response[3] = {0};
Status s = command(CMD_GETEVENT, response, &len);
if (s != OK) {
Serial.printf(DBG_ERR("pulling join event error: 0x%02x") "\n", (uint8_t)s);
}
if (response[0] == EVT_JOINED || response[0] == EVT_JOINFAIL) {
// callback
if (join_done != NULL) {
join_done((Event_code)response[0]);
}
if (response[0] == EVT_JOINFAIL) {
Serial.printf(DBG_ERR("join event fail") "\n");
}
return false;
}
return true;
}
bool LoRaWANModem::is_joining() {
return is_joining(NULL);
}
/*
* send join command and wait for network
* TODO sleep instead of idling 500ms!
* TODO if join fails we get back to the modem stuck with "0x05 busy"
*/
Status LoRaWANModem::join(const uint8_t *appeui, const uint8_t *appkey) {
// check status, if joined -> do nothing
// avoid issues with multiple joins -> seems to create 0x05 busy errors
Status s;
uint8_t st[1] = {0};
uint8_t sl;
command(CMD_GETSTATUS, st, &sl);
Modem_status status = (Modem_status)st[0];
if (status == JOINED) {
Serial.println(DBG_OK("already joined. Send your data!"));
return OK;
}
// do not start an initial join call if already joining to avoid 0x05 busy errors
// by setting appeui / appkey
if (status != JOINING) {
s = command_join(appeui, appkey);
if (s != OK) {
Serial.printf(DBG_ERR("join request error: 0x%02x") "\n", s);
return FAIL;
}
}
Serial.print("waiting");
uint8_t len;
uint8_t response[1] = {0};
unsigned long current_time = millis();
while (true) {
if ((millis()-current_time) > 500) {
s = command(CMD_GETEVENT, response, &len);
if (s != OK) {
Serial.printf(DBG_ERR("pulling join event error: 0x%02x") "\n", (uint8_t)s);
}
if (response[0] == EVT_JOINED) {
Serial.println(DBG_OK("joined"));
return OK;
}
if (response[0] == EVT_JOINFAIL) {
Serial.println(DBG_ERR("failed"));
return FAIL;
}
current_time = millis();
Serial.print(".");
}
}
}
Status LoRaWANModem::send(const uint8_t *data, uint8_t len, uint8_t port, uint8_t confirm) {
uint8_t payload_len = len + 2;
uint8_t payload[255];
payload[0] = port;
payload[1] = confirm;
for (uint8_t i=0; i<len; i++) {
payload[2+i] = data[i];
}
Status sw = _write(CMD_REQUESTTX, payload, payload_len);
if (sw != OK) {
Serial.printf(DBG_ERR("tx cmd error: 0x%02x") "\n", (uint8_t)sw);
return sw;
}
/*
uint8_t event_len;
uint8_t event_resp[3] = {0};
Status se = command(CMD_GETEVENT, event_resp, &event_len);
if (se != OK) {
Serial.printf(DBG_ERR("tx event cmd error: %02x") "\n", (uint8_t)se);
}
if (event_resp[0] == EVT_TXDONE) {
tx_done((Event_code)event_resp[0]);
return false;
}
*/
return OK;
}
uint8_t LoRaWANModem::_calc_crc(uint8_t cmd, const uint8_t *payload, uint8_t len) {
uint8_t crc = cmd^len;
if (payload == NULL) return crc;
for (uint8_t i=0; i<len; i++) {
crc ^= payload[i];
}
return crc;
}
/*
* single command with arguments
* get response
*/
Status LoRaWANModem::command(Lora_cmd cmd, const uint8_t *payload, uint8_t len_payload, uint8_t *response, uint8_t *len_response) {
Status sw = _write(cmd, payload, len_payload);
if (sw != OK) return sw;
if (response == NULL) {
uint8_t r[255] = {0};
uint8_t l;
return _read(r, &l);
}
return _read(response, len_response);
}
/*
* single command no arguments
* get response
*/
Status LoRaWANModem::command(Lora_cmd cmd, uint8_t *response, uint8_t *len_response) {
return command(cmd, NULL, 0, response, len_response);
}
/*
* single command with arguments
* ignore response
*
* we always need to read the result or we'll mess up communication at some point
*/
Status LoRaWANModem::command(Lora_cmd cmd, const uint8_t *payload, uint8_t len_payload) {
return command(cmd, payload, len_payload, NULL, NULL);
}
/*
* single command no arguments
* ignore response
*/
Status LoRaWANModem::command(Lora_cmd cmd) {
return command(cmd, NULL, 0, NULL, NULL);
}
Status LoRaWANModem::_write(Lora_cmd cmd) {
return _write(cmd, NULL, 0);
}
Status LoRaWANModem::_write(Lora_cmd cmd, const uint8_t *payload, uint8_t len) {
digitalWrite(_pin_rts, LOW);
unsigned long now = millis();
// wait for uart to set busy line low with 10ms timeout
while (digitalRead(_pin_cts) == HIGH) {
if ((millis()-now) > 10) {
Serial.println(DBG_ERR("cts timeout"));
digitalWrite(_pin_rts, HIGH);
return TIMEOUT;
}
}
uart.write(cmd);
uart.write(len);
for (uint8_t i=0; i<len; i++) {
uart.write(payload[i]);
}
uart.write(_calc_crc(cmd, payload, len));
delay(25);
digitalWrite(_pin_rts, HIGH);
// wait for uart to set busy line high again
now = millis();
while (digitalRead(_pin_cts) == LOW) {
if ((millis()-now) > 200) {
Serial.println(DBG_ERR("cts release timeout"));
return TIMEOUT;
}
}
return OK;
}
Status LoRaWANModem::_read(uint8_t *payload, uint8_t *len) {
unsigned long now = millis();
// wait for data with 100ms timeout
while (!uart.available()) {
if ((millis()-now) > 100) {
Serial.println(DBG_ERR("receive timeout"));
return TIMEOUT;
}
}
while (!uart.available()) {}
Status rc = (Status)uart.read();
if (rc != OK) {
Serial.printf(DBG_ERR("receive error: 0x%02x") "\n", rc);
}
while (!uart.available()) {}
uint8_t l = uart.read();
if (l) {
uart.readBytes(payload, l);
}
while (!uart.available()) {}
uint8_t chk = uart.read();
if (chk != _calc_crc(rc, payload, l)) {
Serial.printf(DBG_ERR("invalid crc: 0x%02x") "\n", chk);
return BADCRC;
}
*len = l;
return rc;
}
void LoRaWANModem::info() {
cmd_and_result("version", CMD_GETVERSION);
cmd_and_result("status", CMD_GETSTATUS);
cmd_and_result("chip id", CMD_GETCHIPEUI);
cmd_and_result("dev eui", CMD_GETDEVEUI);
cmd_and_result("app eui", CMD_GETJOINEUI);
cmd_and_result("region", CMD_GETREGION);
}
void LoRaWANModem::cmd_and_result(const char *name, Lora_cmd cmd) {
cmd_and_result(name, cmd, NULL, 0);
}
void LoRaWANModem::cmd_and_result(const char *name, Lora_cmd cmd, const uint8_t *payload, uint8_t len_payload) {
uint8_t response[255] = {0};
uint8_t len = 0;
Serial.printf("%s: ", name);
if (command(cmd, payload, len_payload, response, &len) == OK) {
Serial.print(DBG_OK("ok"));
print_arr(response, len);
} else {
Serial.println(DBG_ERR("failed"));
}
}
void LoRaWANModem::print_arr(uint8_t *arr, uint8_t len) {
for (uint8_t i=0; i<len; i++) {
Serial.printf(" %02x", arr[i]);
}
Serial.println("");
}
| 24.248503 | 131 | 0.639462 | 2ni |
e557c19ba2a44a798c976cd41aada8e056a046c6 | 1,020 | cpp | C++ | libcxx/test/std/containers/sequences/array/array.tuple/get_rv.pass.cpp | nawrinsu/llvm | e9153f0e50d45fb4a760463ae711aa45ce2bd450 | [
"Apache-2.0"
] | null | null | null | libcxx/test/std/containers/sequences/array/array.tuple/get_rv.pass.cpp | nawrinsu/llvm | e9153f0e50d45fb4a760463ae711aa45ce2bd450 | [
"Apache-2.0"
] | null | null | null | libcxx/test/std/containers/sequences/array/array.tuple/get_rv.pass.cpp | nawrinsu/llvm | e9153f0e50d45fb4a760463ae711aa45ce2bd450 | [
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <array>
// template <size_t I, class T, size_t N> T&& get(array<T, N>&& a);
// UNSUPPORTED: c++98, c++03
#include <array>
#include <memory>
#include <utility>
#include <cassert>
// std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "test_macros.h"
#include "disable_missing_braces_warning.h"
int main(int, char**)
{
{
typedef std::unique_ptr<double> T;
typedef std::array<T, 1> C;
C c = {std::unique_ptr<double>(new double(3.5))};
T t = std::get<0>(std::move(c));
assert(*t == 3.5);
}
return 0;
}
| 26.842105 | 80 | 0.538235 | nawrinsu |
e55ea52956dab30f6882d126a1960c9d4f07d3e2 | 23,289 | cpp | C++ | taco-oopsla2017/src/lower/lower.cpp | peterahrens/FillEstimationIPDPS2017 | 857b6ee8866a2950aa5721d575d2d7d0797c4302 | [
"BSD-3-Clause"
] | null | null | null | taco-oopsla2017/src/lower/lower.cpp | peterahrens/FillEstimationIPDPS2017 | 857b6ee8866a2950aa5721d575d2d7d0797c4302 | [
"BSD-3-Clause"
] | null | null | null | taco-oopsla2017/src/lower/lower.cpp | peterahrens/FillEstimationIPDPS2017 | 857b6ee8866a2950aa5721d575d2d7d0797c4302 | [
"BSD-3-Clause"
] | null | null | null | #include "taco/lower/lower.h"
#include <vector>
#include <stack>
#include <set>
#include "taco/tensor.h"
#include "taco/expr.h"
#include "taco/ir/ir.h"
#include "taco/ir/ir_visitor.h"
#include "ir/ir_codegen.h"
#include "lower_codegen.h"
#include "iterators.h"
#include "tensor_path.h"
#include "merge_lattice.h"
#include "iteration_schedule.h"
#include "expr_tools.h"
#include "taco/expr_nodes/expr_nodes.h"
#include "taco/expr_nodes/expr_rewriter.h"
#include "storage/iterator.h"
#include "taco/util/name_generator.h"
#include "taco/util/collections.h"
#include "taco/util/strings.h"
using namespace std;
namespace taco {
namespace lower {
using namespace taco::ir;
using namespace taco::expr_nodes;
using taco::storage::Iterator;
struct Context {
/// Determines what kind of code to emit (e.g. compute and/or assembly)
set<Property> properties;
/// The iteration schedule to use for lowering the index expression
IterationSchedule schedule;
/// The iterators of the tensor tree levels
Iterators iterators;
/// The size of initial memory allocations
Expr allocSize;
/// Maps tensor (scalar) temporaries to IR variables.
/// (Not clear if this approach to temporaries is too hacky.)
map<TensorBase,Expr> temporaries;
};
struct Target {
Expr tensor;
Expr pos;
};
enum ComputeCase {
// Emit the last free variable. We first recurse to compute remaining
// reduction variables into a temporary, before we compute and store the
// main expression
LAST_FREE,
// Emit a variable above the last free variable. First emit code to compute
// available expressions and store them in temporaries, before
// we recurse on the next index variable.
ABOVE_LAST_FREE,
// Emit a variable below the last free variable. First recurse to emit
// remaining (summation) variables, before we add in the available expressions
// for the current summation variable.
BELOW_LAST_FREE
};
static ComputeCase getComputeCase(const IndexVar& indexVar,
const IterationSchedule& schedule) {
if (schedule.isLastFreeVariable(indexVar)) {
return LAST_FREE;
}
else if (schedule.hasFreeVariableDescendant(indexVar)) {
return ABOVE_LAST_FREE;
}
else {
return BELOW_LAST_FREE;
}
}
/// Returns true iff the lattice must be merged, false otherwise. A lattice
/// must be merged iff it has more than one lattice point, or two or more of
/// its iterators are not random access.
static bool needsMerge(MergeLattice lattice) {
if (lattice.getSize() > 1) {
return true;
}
int notRandomAccess = 0;
for (auto& iterator : lattice.getIterators()) {
if ((!iterator.isRandomAccess()) && (++notRandomAccess > 1)) {
return true;
}
}
return false;
}
static bool needsZero(const Context& ctx) {
const auto& schedule = ctx.schedule;
const auto& resultIdxVars = schedule.getResultTensorPath().getVariables();
if (schedule.hasReductionVariableAncestor(resultIdxVars.back())) {
return true;
}
for (const auto& idxVar : resultIdxVars) {
for (const auto& tensorPath : schedule.getTensorPaths()) {
if (util::contains(tensorPath.getVariables(), idxVar) &&
!ctx.iterators[tensorPath.getStep(idxVar)].isDense()) {
return true;
}
}
}
return false;
}
static IndexExpr emitAvailableExprs(const IndexVar& indexVar,
const IndexExpr& indexExpr, Context* ctx,
vector<Stmt>* stmts) {
vector<IndexVar> visited = ctx->schedule.getAncestors(indexVar);
vector<IndexExpr> availExprs = getAvailableExpressions(indexExpr, visited);
map<IndexExpr,IndexExpr> substitutions;
for (const IndexExpr& availExpr : availExprs) {
TensorBase t("t" + indexVar.getName(), Float(64));
substitutions.insert({availExpr, taco::Access(t)});
Expr tensorVar = Var::make(t.getName(), Float(64));
ctx->temporaries.insert({t, tensorVar});
Expr expr = lowerToScalarExpression(availExpr, ctx->iterators,
ctx->schedule, ctx->temporaries);
stmts->push_back(VarAssign::make(tensorVar, expr, true));
}
return replace(indexExpr, substitutions);
}
static void emitComputeExpr(const Target& target, const IndexVar& indexVar,
const IndexExpr& indexExpr, const Context& ctx,
vector<Stmt>* stmts) {
Expr expr = lowerToScalarExpression(indexExpr, ctx.iterators,
ctx.schedule, ctx.temporaries);
if (target.pos.defined()) {
Stmt store = ctx.schedule.hasReductionVariableAncestor(indexVar)
? compoundStore(target.tensor, target.pos, expr)
: Store::make(target.tensor, target.pos, expr);
stmts->push_back(store);
}
else {
Stmt assign = ctx.schedule.hasReductionVariableAncestor(indexVar)
? compoundAssign(target.tensor, expr)
: VarAssign::make(target.tensor, expr);
stmts->push_back(assign);
}
}
static LoopKind doParallelize(const IndexVar& indexVar, const Expr& tensor,
const Context& ctx) {
if (ctx.schedule.getAncestors(indexVar).size() != 1 ||
ctx.schedule.isReduction(indexVar)) {
return LoopKind::Serial;
}
const TensorPath& resultPath = ctx.schedule.getResultTensorPath();
for (size_t i = 0; i < resultPath.getSize(); i++){
if (!ctx.iterators[resultPath.getStep(i)].isDense()) {
return LoopKind::Serial;
}
}
const TensorPath parallelizedAccess = [&]() {
const auto tensorName = tensor.as<Var>()->name;
for (const auto& tensorPath : ctx.schedule.getTensorPaths()) {
if (tensorPath.getTensor().getName() == tensorName) {
return tensorPath;
}
}
taco_iassert(false);
return TensorPath();
}();
if (parallelizedAccess.getSize() <= 2) {
return LoopKind::Static;
}
for (size_t i = 1; i < parallelizedAccess.getSize(); ++i) {
if (ctx.iterators[parallelizedAccess.getStep(i)].isDense()) {
return LoopKind::Static;
}
}
return LoopKind::Dynamic;
}
/// Expression evaluates to true iff none of the iteratators are exhausted
static Expr noneExhausted(const vector<Iterator>& iterators) {
vector<Expr> stepIterLqEnd;
for (auto& iter : iterators) {
stepIterLqEnd.push_back(Lt::make(iter.getIteratorVar(), iter.end()));
}
return conjunction(stepIterLqEnd);
}
/// Expression evaluates to true iff all the iterator idx vars are equal to idx
/// or if there are no iterators.
static Expr allEqualTo(const vector<Iterator>& iterators, Expr idx) {
if (iterators.size() == 0) {
return Literal::make(true);
}
vector<Expr> iterIdxEqualToIdx;
for (auto& iter : iterators) {
iterIdxEqualToIdx.push_back(Eq::make(iter.getIdxVar(), idx));
}
return conjunction(iterIdxEqualToIdx);
}
/// Returns the iterator for the `idx` variable from `iterators`, or Iterator()
/// none of the iterator iterate over `idx`.
static Iterator getIterator(const Expr& idx,
const vector<Iterator>& iterators) {
for (auto& iterator : iterators) {
if (iterator.getIdxVar() == idx) {
return iterator;
}
}
return Iterator();
}
static vector<Iterator> removeIterator(const Expr& idx,
const vector<Iterator>& iterators) {
vector<Iterator> result;
for (auto& iterator : iterators) {
if (iterator.getIdxVar() != idx) {
result.push_back(iterator);
}
}
return result;
}
static Stmt createIfStatements(vector<pair<Expr,Stmt>> cases,
const MergeLattice& lattice) {
if (!needsMerge(lattice)) {
return cases[0].second;
}
vector<pair<Expr,Stmt>> ifCases;
pair<Expr,Stmt> elseCase;
for (auto& cas : cases) {
auto lit = cas.first.as<Literal>();
if (lit != nullptr && lit->type == Bool() && lit->value == 1){
taco_iassert(!elseCase.first.defined()) <<
"there should only be one true case";
elseCase = cas;
}
else {
ifCases.push_back(cas);
}
}
if (elseCase.first.defined()) {
ifCases.push_back(elseCase);
return Case::make(ifCases, true);
}
else {
return Case::make(ifCases, lattice.isFull());
}
}
static vector<Stmt> lower(const Target& target,
const IndexExpr& indexExpr,
const IndexVar& indexVar,
Context& ctx) {
vector<Stmt> code;
MergeLattice lattice = MergeLattice::make(indexExpr, indexVar, ctx.schedule,
ctx.iterators);
TensorPath resultPath = ctx.schedule.getResultTensorPath();
TensorPathStep resultStep = resultPath.getStep(indexVar);
Iterator resultIterator = (resultStep.getPath().defined())
? ctx.iterators[resultStep]
: Iterator();
bool emitCompute = util::contains(ctx.properties, Compute);
bool emitAssemble = util::contains(ctx.properties, Assemble);
bool emitMerge = needsMerge(lattice);
// Emit code to initialize pos variables:
// B2_pos = B2_pos_arr[B1_pos];
if (emitMerge) {
for (auto& iterator : lattice.getIterators()) {
Expr iteratorVar = iterator.getIteratorVar();
Stmt iteratorInit = VarAssign::make(iteratorVar, iterator.begin(), true);
code.push_back(iteratorInit);
}
}
// Emit one loop per lattice point lp
vector<Stmt> loops;
for (MergeLatticePoint lp : lattice) {
MergeLattice lpLattice = lattice.getSubLattice(lp);
auto lpIterators = lp.getIterators();
vector<Stmt> loopBody;
// Emit code to initialize sequential access idx variables:
// int kB = B1_idx_arr[B1_pos];
// int kc = c0_idx_arr[c0_pos];
vector<Expr> mergeIdxVariables;
auto sequentialAccessIterators = getSequentialAccessIterators(lpIterators);
for (Iterator& iterator : sequentialAccessIterators) {
Stmt initIdx = iterator.initDerivedVar();
loopBody.push_back(initIdx);
mergeIdxVariables.push_back(iterator.getIdxVar());
}
// Emit code to initialize the index variable:
// k = min(kB, kc);
Expr idx = (lp.getMergeIterators().size() > 1)
? min(indexVar.getName(), lp.getMergeIterators(), &loopBody)
: lp.getMergeIterators()[0].getIdxVar();
// Emit code to initialize random access pos variables:
// D1_pos = (D0_pos * 3) + k;
auto randomAccessIterators =
getRandomAccessIterators(util::combine(lpIterators, {resultIterator}));
for (Iterator& iterator : randomAccessIterators) {
Expr val = ir::Add::make(ir::Mul::make(iterator.getParent().getPtrVar(),
iterator.end()), idx);
Stmt initPos = VarAssign::make(iterator.getPtrVar(), val, true);
loopBody.push_back(initPos);
}
// Emit one case per lattice point in the sub-lattice rooted at lp
vector<pair<Expr,Stmt>> cases;
for (MergeLatticePoint& lq : lpLattice) {
IndexExpr lqExpr = lq.getExpr();
vector<Stmt> caseBody;
// Emit compute code for three cases: above, at or below the last free var
ComputeCase indexVarCase = getComputeCase(indexVar, ctx.schedule);
// Emit available sub-expressions at this loop level
if (emitCompute && ABOVE_LAST_FREE == indexVarCase) {
lqExpr = emitAvailableExprs(indexVar, lqExpr, &ctx, &caseBody);
}
// Recursive call to emit iteration schedule children
for (auto& child : ctx.schedule.getChildren(indexVar)) {
IndexExpr childExpr = lqExpr;
Target childTarget = target;
if (indexVarCase == LAST_FREE || indexVarCase == BELOW_LAST_FREE) {
// Extract the expression to compute at the next level. If there's no
// computation on the next level for this lattice case then skip it
childExpr = getSubExpr(lqExpr, ctx.schedule.getDescendants(child));
if (!childExpr.defined()) continue;
// Reduce child expression into temporary
TensorBase t("t" + child.getName(), Float(64));
Expr tensorVar = Var::make(t.getName(), Type(Type::Float,64));
ctx.temporaries.insert({t, tensorVar});
childTarget.tensor = tensorVar;
childTarget.pos = Expr();
if (emitCompute) {
caseBody.push_back(VarAssign::make(tensorVar, 0.0, true));
}
// Rewrite lqExpr to substitute the expression computed at the next
// level with the temporary
lqExpr = replace(lqExpr, {{childExpr,taco::Access(t)}});
}
auto childCode = lower::lower(childTarget, childExpr, child, ctx);
util::append(caseBody, childCode);
}
// Emit code to compute and store/assign result
if (emitCompute &&
(indexVarCase == LAST_FREE || indexVarCase == BELOW_LAST_FREE)) {
emitComputeExpr(target, indexVar, lqExpr, ctx, &caseBody);
}
// Emit a store of the index variable value to the result idx index array
// A2_idx_arr[A2_pos] = j;
if (emitAssemble && resultIterator.defined()){
Stmt idxStore = resultIterator.storeIdx(idx);
if (idxStore.defined()) {
caseBody.push_back(idxStore);
}
}
// Emit code to increment the result `pos` variable and to allocate
// additional storage for result `idx` and `pos` arrays
if (resultIterator.defined() && resultIterator.isSequentialAccess()) {
Expr rpos = resultIterator.getPtrVar();
Stmt posInc = VarAssign::make(rpos, Add::make(rpos, 1));
// Conditionally resize result `idx` and `pos` arrays
if (emitAssemble) {
Expr resize =
And::make(Eq::make(0, BitAnd::make(Add::make(rpos, 1), rpos)),
Lte::make(ctx.allocSize, Add::make(rpos, 1)));
Expr newSize = ir::Mul::make(2, ir::Add::make(rpos, 1));
// Resize result `idx` array
Stmt resizeIndices = resultIterator.resizeIdxStorage(newSize);
// Resize result `pos` array
if (indexVarCase == ABOVE_LAST_FREE) {
auto nextStep = resultPath.getStep(resultStep.getStep() + 1);
Stmt resizePos = ctx.iterators[nextStep].resizePtrStorage(newSize);
resizeIndices = Block::make({resizeIndices, resizePos});
} else if (resultStep == resultPath.getLastStep() && emitCompute) {
Expr vals = GetProperty::make(resultIterator.getTensor(),
TensorProperty::Values);
Stmt resizeVals = Allocate::make(vals, newSize, true);
resizeIndices = Block::make({resizeIndices, resizeVals});
}
posInc = Block::make({posInc,IfThenElse::make(resize,resizeIndices)});
}
// Only increment `pos` if values were produced at the next level
if (indexVarCase == ABOVE_LAST_FREE) {
int step = resultStep.getStep() + 1;
string resultTensorName = resultIterator.getTensor().as<Var>()->name;
string posArrName = resultTensorName + to_string(step + 1) + "_pos";
Expr posArr = GetProperty::make(resultIterator.getTensor(),
TensorProperty::Indices,
step, 0, posArrName);
Expr producedVals = Gt::make(Load::make(posArr, Add::make(rpos,1)),
Load::make(posArr, rpos));
posInc = IfThenElse::make(producedVals, posInc);
}
util::append(caseBody, {posInc});
}
auto caseIterators = removeIterator(idx, lq.getRangeIterators());
cases.push_back({allEqualTo(caseIterators,idx), Block::make(caseBody)});
}
loopBody.push_back(createIfStatements(cases, lpLattice));
// Emit code to increment sequential access `pos` variables. Variables that
// may not be consumed in an iteration (i.e. their iteration space is
// different from the loop iteration space) are guarded by a conditional:
if (emitMerge) {
// if (k == kB) B1_pos++;
// if (k == kc) c0_pos++;
for (auto& iterator : removeIterator(idx, lp.getRangeIterators())) {
Expr ivar = iterator.getIteratorVar();
Stmt inc = VarAssign::make(ivar, Add::make(ivar, 1));
Expr tensorIdx = iterator.getIdxVar();
loopBody.push_back(IfThenElse::make(Eq::make(tensorIdx, idx), inc));
}
/// k++
auto idxIterator = getIterator(idx, lpIterators);
if (idxIterator.defined()) {
Expr ivar = idxIterator.getIteratorVar();
loopBody.push_back(VarAssign::make(ivar, Add::make(ivar, 1)));
}
}
// Emit loop (while loop for merges and for loop for non-merges)
Stmt loop;
if (emitMerge) {
loop = While::make(noneExhausted(lp.getRangeIterators()),
Block::make(loopBody));
}
else {
Iterator iter = lp.getRangeIterators()[0];
loop = For::make(iter.getIteratorVar(), iter.begin(), iter.end(), 1,
Block::make(loopBody),
doParallelize(indexVar, iter.getTensor(), ctx));
}
loops.push_back(loop);
}
util::append(code, loops);
// Emit a store of the segment size to the result pos index
// A2_pos_arr[A1_pos + 1] = A2_pos;
if (emitAssemble && resultIterator.defined()) {
Stmt posStore = resultIterator.storePtr();
if (posStore.defined()) {
util::append(code, {posStore});
}
}
return code;
}
Stmt lower(TensorBase tensor, string funcName, set<Property> properties) {
Context ctx;
ctx.allocSize = Var::make("init_alloc_size", Type(Type::Int));
ctx.properties = properties;
const bool emitAssemble = util::contains(ctx.properties, Assemble);
const bool emitCompute = util::contains(ctx.properties, Compute);
auto name = tensor.getName();
auto indexExpr = tensor.getExpr();
// Pack the tensor and it's expression operands into the parameter list
vector<Expr> parameters;
vector<Expr> results;
map<TensorBase,Expr> tensorVars;
tie(parameters,results,tensorVars) = getTensorVars(tensor);
// Create the schedule and the iterators of the lowered code
ctx.schedule = IterationSchedule::make(tensor);
ctx.iterators = Iterators(ctx.schedule, tensorVars);
vector<Stmt> init, body;
TensorPath resultPath = ctx.schedule.getResultTensorPath();
if (emitAssemble) {
for (auto& indexVar : resultPath.getVariables()) {
Iterator iter = ctx.iterators[resultPath.getStep(indexVar)];
Stmt allocStmts = iter.initStorage(ctx.allocSize);
if (allocStmts.defined()) {
if (init.empty()) {
const auto comment = to<Var>(ctx.allocSize)->name +
" should be initialized to a power of two";
Stmt setAllocSize = Block::make({
Comment::make(comment),
VarAssign::make(ctx.allocSize, (int)tensor.getAllocSize(), true)
});
init.push_back(setAllocSize);
}
init.push_back(allocStmts);
}
}
}
// Initialize the result pos variables
if (emitCompute || emitAssemble) {
Stmt prevIteratorInit;
for (auto& indexVar : resultPath.getVariables()) {
Iterator iter = ctx.iterators[resultPath.getStep(indexVar)];
Stmt iteratorInit = VarAssign::make(iter.getPtrVar(), iter.begin(), true);
if (iter.isSequentialAccess()) {
// Emit code to initialize the result pos variable
if (prevIteratorInit.defined()) {
body.push_back(prevIteratorInit);
prevIteratorInit = Stmt();
}
body.push_back(iteratorInit);
} else {
prevIteratorInit = iteratorInit;
}
}
}
taco_iassert(results.size() == 1) << "An expression can only have one result";
// Lower the iteration schedule
auto& roots = ctx.schedule.getRoots();
// Lower tensor expressions
if (roots.size() > 0) {
Iterator resultIterator = (resultPath.getSize() > 0)
? ctx.iterators[resultPath.getLastStep()]
: ctx.iterators.getRoot(resultPath); // e.g. `a = b(i) * c(i)`
Target target;
target.tensor = GetProperty::make(resultIterator.getTensor(),
TensorProperty::Values);
target.pos = resultIterator.getPtrVar();
if (emitCompute) {
Expr size = 1;
for (auto& indexVar : resultPath.getVariables()) {
const Iterator iter = ctx.iterators[resultPath.getStep(indexVar)];
if (!iter.isFixedRange()) {
size = ctx.allocSize;
break;
}
size = Mul::make(size, iter.end());
}
if (emitAssemble) {
Stmt allocVals = Allocate::make(target.tensor, size);
init.push_back(allocVals);
}
// If the output is dense and if either an output dimension is merged with
// a sparse input dimension or if the emitted code is a scatter code, then
// we also need to zero the output.
if (!isa<Var>(size)) {
if (isa<Literal>(size)) {
taco_iassert(to<Literal>(size)->value == 1);
body.push_back(Store::make(target.tensor, 0, 0.0));
} else if (needsZero(ctx)) {
Expr idxVar = Var::make("p" + name, Type(Type::Int));
Stmt zeroStmt = Store::make(target.tensor, idxVar, 0.0);
body.push_back(For::make(idxVar, 0, size, 1, zeroStmt));
}
}
}
const bool emitLoops = emitCompute || (emitAssemble && [&]() {
for (auto& indexVar : resultPath.getVariables()) {
Iterator iter = ctx.iterators[resultPath.getStep(indexVar)];
if (!iter.isDense()) {
return true;
}
}
return false;
}());
if (emitLoops) {
for (auto& root : roots) {
auto loopNest = lower::lower(target, indexExpr, root, ctx);
util::append(body, loopNest);
}
}
if (emitAssemble && !emitCompute) {
Expr size = 1;
for (auto& indexVar : resultPath.getVariables()) {
Iterator iter = ctx.iterators[resultPath.getStep(indexVar)];
size = iter.isFixedRange() ? Mul::make(size, iter.end()) :
iter.getPtrVar();
}
Stmt allocVals = Allocate::make(target.tensor, size);
if (!body.empty()) {
body.push_back(BlankLine::make());
}
body.push_back(allocVals);
}
}
// Lower scalar expressions
else {
TensorPath resultPath = ctx.schedule.getResultTensorPath();
Expr resultTensorVar = ctx.iterators.getRoot(resultPath).getTensor();
Expr vals = GetProperty::make(resultTensorVar, TensorProperty::Values);
if (emitAssemble) {
Stmt allocVals = Allocate::make(vals, 1);
init.push_back(allocVals);
}
if (emitCompute) {
Expr expr = lowerToScalarExpression(indexExpr, ctx.iterators, ctx.schedule,
map<TensorBase,Expr>());
Stmt compute = Store::make(vals, 0, expr);
body.push_back(compute);
}
}
if (!init.empty()) {
init.push_back(BlankLine::make());
}
body = util::combine(init, body);
return Function::make(funcName, parameters, results, Block::make(body));
}
}}
| 35.339909 | 81 | 0.630083 | peterahrens |
e562585a55cfabb469ca1ed2c84c423dae48f8de | 99 | cpp | C++ | Src/Vessel/Quadcopter/QuadcopterSubsys.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Src/Vessel/Quadcopter/QuadcopterSubsys.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Src/Vessel/Quadcopter/QuadcopterSubsys.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | // Copyright (c) Martin Schweiger
// Licensed under the MIT License
#include "QuadcopterSubsys.h"
| 19.8 | 33 | 0.757576 | Ybalrid |
e5648cea6421a775246cc1d2cc71e8dbedd13695 | 575 | cpp | C++ | Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/Interpreter.cpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/Interpreter.cpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/Interpreter.cpp | tedi21/SisypheReview | f7c05bad1ccc036f45870535149d9685e1120c2c | [
"Unlicense"
] | null | null | null | #include <windows.h>
#include "ProgramInterpreter.hpp"
#include "DebugEngineInterpreter.hpp"
#include "IDebugClientPtrInterpreter.hpp"
#include "IDebugControlPtrInterpreter.hpp"
#include "DEBUG_VALUEInterpreter.hpp"
using namespace enc;
using namespace fctr;
using namespace interp;
//////////////////////////////////////////
// Exportation des classes
//////////////////////////////////////////
FACTORY_EXPORT_FILE(DebugEngineInterpreter<ucs>, )
FACTORY_EXPORT_FILE(IDebugClientPtrInterpreter<ucs>, )
FACTORY_EXPORT_FILE(IDebugControlPtrInterpreter<ucs>, ) | 33.823529 | 55 | 0.690435 | tedi21 |
e5681f877ad7f83f4618f2fc44e500c843976446 | 1,984 | hh | C++ | src/opbox/core/OpTimer.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-01-25T21:21:07.000Z | 2021-04-29T17:24:00.000Z | src/opbox/core/OpTimer.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 8 | 2018-10-09T14:35:30.000Z | 2020-09-30T20:09:42.000Z | src/opbox/core/OpTimer.hh | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-04-23T19:01:36.000Z | 2021-05-11T07:44:55.000Z | // Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#ifndef OPBOX_OPBOX_OPTIMER_HH
#define OPBOX_OPBOX_OPTIMER_HH
#include <vector>
#include "opbox/ops/Op.hh"
namespace opbox {
namespace internal {
class OpTimerEvent {
public:
enum Value: int {
Incoming=0,
Update,
Launch,
Trigger,
Dispatched,
ActionComplete
};
OpTimerEvent()=default;
std::string str();
constexpr OpTimerEvent(Value e) :value(e) {}
private:
Value value;
};
/**
* @brief Timing code to help estimate how long it takes to execute ops
*
* This timer creates a trace of all the different events that are passed
* to each op. An instrumented OpBoxCore should include one of these
* structures and use Mark commands to add new events to the trace. The
* op's mailbox id is extracted from the op to provide a tag for grouping
* ops. The Dump command sorts by mailbox and shows the amount of time
* since the previous marker in this op.
*/
class OpTimer {
public:
OpTimer();
~OpTimer();
void Mark(Op *op, OpTimerEvent event);
void MarkDispatched(mailbox_t);
void Dump();
private:
struct op_timestamp_t {
mailbox_t mbox;
unsigned int opid;
OpTimerEvent event;
std::chrono::high_resolution_clock::time_point time;
op_timestamp_t(Op *op, OpTimerEvent event)
: mbox(op->GetAssignedMailbox()), opid(op->getOpID()), event(event) {
time = std::chrono::high_resolution_clock::now();
}
op_timestamp_t(mailbox_t m)
: mbox(m), opid(0), event(OpTimerEvent::Dispatched) {
time = std::chrono::high_resolution_clock::now();
}
uint64_t getGapTimeUS(const op_timestamp_t &prv);
};
private:
faodel::MutexWrapper *mutex;
std::vector <op_timestamp_t> timestamps;
};
} //namespace internal
} //namespace opbox
#endif //OPBOX_OPBOX_OPTIMER_HH
| 24.8 | 81 | 0.705645 | faodel |
e571e48132178154c38b7965efe5a0948d4a8c28 | 3,083 | cpp | C++ | LibFoundation/Intersection/Wm4IntrRay3Capsule3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | LibFoundation/Intersection/Wm4IntrRay3Capsule3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | LibFoundation/Intersection/Wm4IntrRay3Capsule3.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4FoundationPCH.h"
#include "Wm4IntrRay3Capsule3.h"
#include "Wm4DistRay3Segment3.h"
#include "Wm4IntrLine3Capsule3.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
IntrRay3Capsule3<Real>::IntrRay3Capsule3 (const Ray3<Real>& rkRay,
const Capsule3<Real>& rkCapsule)
:
m_rkRay(rkRay),
m_rkCapsule(rkCapsule)
{
}
//----------------------------------------------------------------------------
template <class Real>
const Ray3<Real>& IntrRay3Capsule3<Real>::GetRay () const
{
return m_rkRay;
}
//----------------------------------------------------------------------------
template <class Real>
const Capsule3<Real>& IntrRay3Capsule3<Real>::GetCapsule () const
{
return m_rkCapsule;
}
//----------------------------------------------------------------------------
template <class Real>
bool IntrRay3Capsule3<Real>::Test ()
{
Real fDist = DistRay3Segment3<Real>(m_rkRay,m_rkCapsule.Segment).Get();
return fDist <= m_rkCapsule.Radius;
}
//----------------------------------------------------------------------------
template <class Real>
bool IntrRay3Capsule3<Real>::Find ()
{
Real afT[2];
int iQuantity = IntrLine3Capsule3<Real>::Find(m_rkRay.Origin,
m_rkRay.Direction,m_rkCapsule,afT);
m_iQuantity = 0;
for (int i = 0; i < iQuantity; i++)
{
if (afT[i] >= (Real)0.0)
{
m_akPoint[m_iQuantity++] = m_rkRay.Origin +
afT[i]*m_rkRay.Direction;
}
}
if (m_iQuantity == 2)
{
m_iIntersectionType = IT_SEGMENT;
}
else if (m_iQuantity == 1)
{
m_iIntersectionType = IT_POINT;
}
else
{
m_iIntersectionType = IT_EMPTY;
}
return m_iIntersectionType != IT_EMPTY;
}
//----------------------------------------------------------------------------
template <class Real>
int IntrRay3Capsule3<Real>::GetQuantity () const
{
return m_iQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector3<Real>& IntrRay3Capsule3<Real>::GetPoint (int i) const
{
assert(0 <= i && i < m_iQuantity);
return m_akPoint[i];
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_FOUNDATION_ITEM
class IntrRay3Capsule3<float>;
template WM4_FOUNDATION_ITEM
class IntrRay3Capsule3<double>;
//----------------------------------------------------------------------------
}
| 29.644231 | 78 | 0.492702 | wjezxujian |
e5737e84d7801be09dc45c044267c7bb91c9edbf | 410 | cpp | C++ | src/CPP/7zip/Compress/CopyRegister.cpp | playback-sports/PLzmaSDK | f1f4807e2f797a14cfdb6ad81833385a06c8338d | [
"MIT"
] | 33 | 2020-09-01T20:11:50.000Z | 2022-03-29T01:20:43.000Z | src/CPP/7zip/Compress/CopyRegister.cpp | playback-sports/PLzmaSDK | f1f4807e2f797a14cfdb6ad81833385a06c8338d | [
"MIT"
] | 13 | 2021-01-20T14:00:18.000Z | 2022-03-24T08:31:47.000Z | src/CPP/7zip/Compress/CopyRegister.cpp | playback-sports/PLzmaSDK | f1f4807e2f797a14cfdb6ad81833385a06c8338d | [
"MIT"
] | 9 | 2021-01-29T14:51:41.000Z | 2022-02-21T13:38:31.000Z | // CopyRegister.cpp
#include "StdAfx.h"
#include "../Common/RegisterCodec.h"
#include "CopyCoder.h"
namespace NCompress {
REGISTER_CODEC_CREATE(CreateCodec, CCopyCoder())
REGISTER_CODEC_2(Copy, CreateCodec, CreateCodec, 0, "Copy")
}
#if defined(LIBPLZMA_USING_REGISTRATORS)
uint64_t plzma_registrator_9(void) {
return static_cast<uint64_t>(NCompress::g_CodecInfo.Id);
}
#endif
| 18.636364 | 61 | 0.729268 | playback-sports |
e57578e36cfc567cfe4c3b042ab10c0d043ec0f1 | 15,553 | cpp | C++ | test/reduce/merge_blocks_test.cpp | danginsburg/SPIRV-Tools | 37861ac106027220fa327bd088d1635c352fb5f0 | [
"Apache-2.0"
] | 9 | 2016-05-25T12:25:50.000Z | 2020-11-30T13:40:13.000Z | test/reduce/merge_blocks_test.cpp | danginsburg/SPIRV-Tools | 37861ac106027220fa327bd088d1635c352fb5f0 | [
"Apache-2.0"
] | null | null | null | test/reduce/merge_blocks_test.cpp | danginsburg/SPIRV-Tools | 37861ac106027220fa327bd088d1635c352fb5f0 | [
"Apache-2.0"
] | 3 | 2018-02-25T06:10:31.000Z | 2019-09-28T15:55:36.000Z | // Copyright (c) 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "reduce_test_util.h"
#include "source/opt/build_module.h"
#include "source/reduce/merge_blocks_reduction_opportunity_finder.h"
#include "source/reduce/reduction_opportunity.h"
namespace spvtools {
namespace reduce {
namespace {
TEST(MergeBlocksReductionPassTest, BasicCheck) {
std::string shader = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpBranch %13
%13 = OpLabel
OpStore %8 %9
OpBranch %14
%14 = OpLabel
OpStore %8 %10
OpBranch %15
%15 = OpLabel
OpStore %8 %11
OpBranch %16
%16 = OpLabel
OpStore %8 %12
OpBranch %17
%17 = OpLabel
OpReturn
OpFunctionEnd
)";
const auto env = SPV_ENV_UNIVERSAL_1_3;
const auto consumer = nullptr;
const auto context =
BuildModule(env, consumer, shader, kReduceAssembleOption);
const auto ops =
MergeBlocksReductionOpportunityFinder().GetAvailableOpportunities(
context.get());
ASSERT_EQ(5, ops.size());
// Try order 3, 0, 2, 4, 1
ASSERT_TRUE(ops[3]->PreconditionHolds());
ops[3]->TryToApply();
std::string after_op_3 = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpBranch %13
%13 = OpLabel
OpStore %8 %9
OpBranch %14
%14 = OpLabel
OpStore %8 %10
OpBranch %15
%15 = OpLabel
OpStore %8 %11
OpStore %8 %12
OpBranch %17
%17 = OpLabel
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after_op_3, context.get());
ASSERT_TRUE(ops[0]->PreconditionHolds());
ops[0]->TryToApply();
std::string after_op_0 = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpStore %8 %9
OpBranch %14
%14 = OpLabel
OpStore %8 %10
OpBranch %15
%15 = OpLabel
OpStore %8 %11
OpStore %8 %12
OpBranch %17
%17 = OpLabel
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after_op_0, context.get());
ASSERT_TRUE(ops[2]->PreconditionHolds());
ops[2]->TryToApply();
std::string after_op_2 = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpStore %8 %9
OpBranch %14
%14 = OpLabel
OpStore %8 %10
OpStore %8 %11
OpStore %8 %12
OpBranch %17
%17 = OpLabel
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after_op_2, context.get());
ASSERT_TRUE(ops[4]->PreconditionHolds());
ops[4]->TryToApply();
std::string after_op_4 = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpStore %8 %9
OpBranch %14
%14 = OpLabel
OpStore %8 %10
OpStore %8 %11
OpStore %8 %12
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after_op_4, context.get());
ASSERT_TRUE(ops[1]->PreconditionHolds());
ops[1]->TryToApply();
std::string after_op_1 = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%10 = OpConstant %6 2
%11 = OpConstant %6 3
%12 = OpConstant %6 4
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpStore %8 %9
OpStore %8 %10
OpStore %8 %11
OpStore %8 %12
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after_op_1, context.get());
}
TEST(MergeBlocksReductionPassTest, Loops) {
std::string shader = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
OpName %10 "i"
OpName %29 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%11 = OpConstant %6 0
%18 = OpConstant %6 10
%19 = OpTypeBool
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
%29 = OpVariable %7 Function
OpStore %8 %9
OpBranch %45
%45 = OpLabel
OpStore %10 %11
OpBranch %12
%12 = OpLabel
OpLoopMerge %14 %15 None
OpBranch %16
%16 = OpLabel
%17 = OpLoad %6 %10
OpBranch %46
%46 = OpLabel
%20 = OpSLessThan %19 %17 %18
OpBranchConditional %20 %13 %14
%13 = OpLabel
%21 = OpLoad %6 %10
OpBranch %47
%47 = OpLabel
%22 = OpLoad %6 %8
%23 = OpIAdd %6 %22 %21
OpStore %8 %23
%24 = OpLoad %6 %10
%25 = OpLoad %6 %8
%26 = OpIAdd %6 %25 %24
OpStore %8 %26
OpBranch %48
%48 = OpLabel
OpBranch %15
%15 = OpLabel
%27 = OpLoad %6 %10
%28 = OpIAdd %6 %27 %9
OpStore %10 %28
OpBranch %12
%14 = OpLabel
OpStore %29 %11
OpBranch %49
%49 = OpLabel
OpBranch %30
%30 = OpLabel
OpLoopMerge %32 %33 None
OpBranch %34
%34 = OpLabel
%35 = OpLoad %6 %29
%36 = OpSLessThan %19 %35 %18
OpBranch %50
%50 = OpLabel
OpBranchConditional %36 %31 %32
%31 = OpLabel
%37 = OpLoad %6 %29
%38 = OpLoad %6 %8
%39 = OpIAdd %6 %38 %37
OpStore %8 %39
%40 = OpLoad %6 %29
%41 = OpLoad %6 %8
%42 = OpIAdd %6 %41 %40
OpStore %8 %42
OpBranch %33
%33 = OpLabel
%43 = OpLoad %6 %29
%44 = OpIAdd %6 %43 %9
OpBranch %51
%51 = OpLabel
OpStore %29 %44
OpBranch %30
%32 = OpLabel
OpReturn
OpFunctionEnd
)";
const auto env = SPV_ENV_UNIVERSAL_1_3;
const auto consumer = nullptr;
const auto context =
BuildModule(env, consumer, shader, kReduceAssembleOption);
const auto ops =
MergeBlocksReductionOpportunityFinder().GetAvailableOpportunities(
context.get());
ASSERT_EQ(11, ops.size());
for (auto& ri : ops) {
ASSERT_TRUE(ri->PreconditionHolds());
ri->TryToApply();
}
std::string after = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
OpName %10 "i"
OpName %29 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%11 = OpConstant %6 0
%18 = OpConstant %6 10
%19 = OpTypeBool
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
%29 = OpVariable %7 Function
OpStore %8 %9
OpStore %10 %11
OpBranch %12
%12 = OpLabel
%17 = OpLoad %6 %10
%20 = OpSLessThan %19 %17 %18
OpLoopMerge %14 %13 None
OpBranchConditional %20 %13 %14
%13 = OpLabel
%21 = OpLoad %6 %10
%22 = OpLoad %6 %8
%23 = OpIAdd %6 %22 %21
OpStore %8 %23
%24 = OpLoad %6 %10
%25 = OpLoad %6 %8
%26 = OpIAdd %6 %25 %24
OpStore %8 %26
%27 = OpLoad %6 %10
%28 = OpIAdd %6 %27 %9
OpStore %10 %28
OpBranch %12
%14 = OpLabel
OpStore %29 %11
OpBranch %30
%30 = OpLabel
%35 = OpLoad %6 %29
%36 = OpSLessThan %19 %35 %18
OpLoopMerge %32 %31 None
OpBranchConditional %36 %31 %32
%31 = OpLabel
%37 = OpLoad %6 %29
%38 = OpLoad %6 %8
%39 = OpIAdd %6 %38 %37
OpStore %8 %39
%40 = OpLoad %6 %29
%41 = OpLoad %6 %8
%42 = OpIAdd %6 %41 %40
OpStore %8 %42
%43 = OpLoad %6 %29
%44 = OpIAdd %6 %43 %9
OpStore %29 %44
OpBranch %30
%32 = OpLabel
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after, context.get());
}
TEST(MergeBlocksReductionPassTest, MergeWithOpPhi) {
std::string shader = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
OpName %10 "y"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
OpStore %8 %9
%11 = OpLoad %6 %8
OpBranch %12
%12 = OpLabel
%13 = OpPhi %6 %11 %5
OpStore %10 %13
OpReturn
OpFunctionEnd
)";
const auto env = SPV_ENV_UNIVERSAL_1_3;
const auto consumer = nullptr;
const auto context =
BuildModule(env, consumer, shader, kReduceAssembleOption);
const auto ops =
MergeBlocksReductionOpportunityFinder().GetAvailableOpportunities(
context.get());
ASSERT_EQ(1, ops.size());
ASSERT_TRUE(ops[0]->PreconditionHolds());
ops[0]->TryToApply();
std::string after = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 310
OpName %4 "main"
OpName %8 "x"
OpName %10 "y"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
OpStore %8 %9
%11 = OpLoad %6 %8
OpStore %10 %11
OpReturn
OpFunctionEnd
)";
CheckEqual(env, after, context.get());
}
} // namespace
} // namespace reduce
} // namespace spvtools
| 30.258755 | 75 | 0.48923 | danginsburg |
e575b5ffc966abe5bdd67d94c90113033a1f860b | 1,710 | cpp | C++ | Code/Engine/Animation/AnimationFrameTime.cpp | JuanluMorales/KRG | f3a11de469586a4ef0db835af4bc4589e6b70779 | [
"MIT"
] | 419 | 2022-01-27T19:37:43.000Z | 2022-03-31T06:14:22.000Z | Code/Engine/Animation/AnimationFrameTime.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-01-28T20:35:33.000Z | 2022-03-13T17:42:52.000Z | Code/Engine/Animation/AnimationFrameTime.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 20 | 2022-01-27T20:41:02.000Z | 2022-03-26T16:16:57.000Z | #include "AnimationFrameTime.h"
//-------------------------------------------------------------------------
namespace KRG::Animation
{
FrameTime FrameTime::operator+( Percentage const& RHS ) const
{
FrameTime newTime = *this;
int32 loopCount;
Percentage newPercent = m_percentageThrough + RHS;
newPercent.GetLoopCountAndNormalizedTime( loopCount, newTime.m_percentageThrough );
newTime.m_frameIndex += loopCount;
return newTime;
}
FrameTime& FrameTime::operator+=( Percentage const& RHS )
{
int32 loopCount;
Percentage newPercent = m_percentageThrough + RHS;
newPercent.GetLoopCountAndNormalizedTime( loopCount, m_percentageThrough );
m_frameIndex += loopCount;
return *this;
}
FrameTime FrameTime::operator-( Percentage const& RHS ) const
{
FrameTime newTime = *this;
int32 loopCount;
Percentage newPercent = m_percentageThrough - RHS;
newPercent.GetLoopCountAndNormalizedTime( loopCount, newTime.m_percentageThrough );
if ( loopCount < 0 )
{
newTime.m_frameIndex -= loopCount;
newTime.m_percentageThrough.Invert();
}
return newTime;
}
FrameTime& FrameTime::operator-=( Percentage const& RHS )
{
int32 loopCount;
Percentage newPercent = m_percentageThrough - RHS;
newPercent.GetLoopCountAndNormalizedTime( loopCount, m_percentageThrough );
if ( loopCount < 0 )
{
m_frameIndex -= loopCount;
m_percentageThrough.Invert();
}
return *this;
}
} | 30 | 92 | 0.587135 | JuanluMorales |
ec7ac649a2c32d3c679a5de985cccde3fdd44fab | 3,730 | hpp | C++ | include/ReverseAssignment.hpp | AristiPap/kNN-and-Clustering-on-Time-Series-and-Curves | 4f510e69c65c4c2e6a994eb267c08289acd80727 | [
"MIT"
] | 16 | 2022-02-06T15:29:36.000Z | 2022-02-18T09:11:35.000Z | include/ReverseAssignment.hpp | AristiPap/kNN-and-Clustering-on-Time-Series-and-Curves | 4f510e69c65c4c2e6a994eb267c08289acd80727 | [
"MIT"
] | null | null | null | include/ReverseAssignment.hpp | AristiPap/kNN-and-Clustering-on-Time-Series-and-Curves | 4f510e69c65c4c2e6a994eb267c08289acd80727 | [
"MIT"
] | 1 | 2022-02-06T15:28:49.000Z | 2022-02-06T15:28:49.000Z | #pragma once
#include <set>
#include <list>
#include "GenericClusterSolver.hpp"
// init radius is min(dist between centroids)/2
template<class CentroidT>
double init_R(vector<CentroidT> ¢roids) {
double min_dist = numeric_limits<double>::max();
for (uint32_t i = 0; i < centroids.size(); i++)
for (uint32_t j = i + 1; j < centroids.size(); j++)
min_dist = min(min_dist, centroids[i].first.dist(centroids[j].first));
return min_dist/2.0;
}
template<class T, class CentroidT>
void insert_into_cluster(T *p, double dist, int centroid_id, vector<CentroidT> ¢roids, uint32_t &points_changed, set<T *>& unassigned_points) {
assert(centroid_id < centroids.size());
// get p's previous and under-check cluster-centroid
CentroidT *old_c = p->getCluster() >= 0 ? &(centroids[p->getCluster()]) : nullptr;
CentroidT *new_c = &(centroids[centroid_id]);
// check if the point is marked
// if P is marked,
// then we need to decide in which cluster to assign it.
// Assign it to the new cluster only if the distance of new centroid is smaller than the assigned one
// otherwise we will let the point at its assigned cluster
if (p->getMarked() && old_c != nullptr && dist - old_c->second[p] >= 0) {
new_c = old_c;
}
// do something only in case the previous and the newly assigned clusters are different
if (new_c != old_c) {
points_changed++;
// in case its the first point assignment for this loop then assign it
if (p->getMarked() == false) unassigned_points.erase(p);
if (old_c != nullptr) old_c->second.erase(p);
new_c->second[p] = dist;
p->setMarked(true);
p->setCluster(centroid_id);
}
}
// Actual implementation of reverse assignment utilizing a Nearest Neighbour Solver class (either LSH or Hypercube will do).
template<class T, class CentroidT, class SolverT>
uint32_t __reverse_assignment__(vector<CentroidT> ¢roids, list<T *> &dataset, SolverT &solver, double R_max, set<T *>& unassigned_points) {
static bool start = true;
// insert all items in an unassigned table
if (start) {
unassigned_points.insert(dataset.begin(), dataset.end());
start = false;
}
// initialize R for range search
static double R = init_R(centroids);
// number of points that changed cluster
uint32_t points_changes = 0;
// perform range search with q-point each one of the centroids
for (auto i = 0; i < centroids.size(); i++) {
// perform the range query, with center the current centroid
list<pair<T *, double>> *in_range = solver.nearestNeighbours_w_rangeSearch(centroids[i].first, R);
// insert all the neighbours in the centroid
for (auto neighbour_pair : *in_range) {
T *p = neighbour_pair.first;
double dist = neighbour_pair.second;
// insert the point into c. If p was in a different centroid before change the changes counter accordingly
insert_into_cluster(p, dist, i, centroids, points_changes, unassigned_points);
}
delete in_range; // free the list, but jsut the list not the inner pointers
}
// at the end of the loop double the search radius
R *= 2.0;
if (R - R_max > 0) {
for (auto p = unassigned_points.begin(); p != unassigned_points.end(); p++) {
insert_in_closest_center(*p, centroids);
}
unassigned_points.clear();
}
#ifdef VERBOSE
cout << "points_changes: " << points_changes << ", unassigned points: " << unassigned_points.size() << ", R = " << R << endl;
#endif
return points_changes + unassigned_points.size();
}
| 39.680851 | 147 | 0.652547 | AristiPap |
ec7d3b0ba9ee3d08fe0df60cba1017060940634f | 7,028 | cpp | C++ | plugins/archvis/src/ScaleModel.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | plugins/archvis/src/ScaleModel.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | null | null | null | plugins/archvis/src/ScaleModel.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* ScaleModel.cpp
*
* Copyright (C) 2018 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include "ScaleModel.h"
using namespace megamol::archvis;
ScaleModel::ScaleModel(
std::vector<Vec3> node_positions,
std::vector<std::tuple<int, int, int, int, int>> elements,
std::vector<int> input_elements)
: m_node_positions(node_positions),
m_node_displacements(node_positions.size(), Vec3(0.0f,0.0f,0.0f)),
m_input_elements(input_elements)
{
for (auto& element : elements)
{
int type = std::get<0>(element);
switch (type)
{
case 0:
m_elements.push_back(
Element(
ElementType::STRUT,
std::tuple<int, int>(std::get<1>(element), std::get<2>(element)),
0.0f)
);
break;
case 1:
m_elements.push_back(
Element(
ElementType::DIAGONAL,
std::tuple<int, int>(std::get<1>(element), std::get<2>(element)),
0.0f)
);
break;
case 2:
m_elements.push_back(
Element(
ElementType::FLOOR,
std::tuple<int, int, int, int>(std::get<1>(element), std::get<2>(element), std::get<3>(element), std::get<4>(element)),
0.0f)
);
break;
default:
break;
}
}
}
void ScaleModel::setModelTransform(Mat4x4 transform)
{
m_model_transform = transform;
}
void ScaleModel::updateNodeDisplacements(std::vector<Vec3> const& displacements)
{
m_node_displacements = displacements;
}
void ScaleModel::updateElementForces(std::vector<float> const& forces)
{
//TODO check forces count matches input element count
for (int i=0; i<forces.size(); ++i)
{
m_elements[m_input_elements[i]].setForce(forces[i]);
}
}
int ScaleModel::getNodeCount()
{
return m_node_positions.size();
}
int ScaleModel::getElementCount()
{
return m_elements.size();
}
int ScaleModel::getInputElementCount()
{
return m_input_elements.size();
}
ScaleModel::ElementType ScaleModel::getElementType(int element_idx)
{
return m_elements[element_idx].getType();
}
float ScaleModel::getElementForce(int element_idx)
{
return m_elements[element_idx].getForce();
}
ScaleModel::Mat4x4 ScaleModel::getElementTransform(int element_idx)
{
return m_model_transform * m_elements[element_idx].computeTransform(m_node_positions, m_node_displacements);
}
ScaleModel::Vec3 ScaleModel::getElementCenter(int element_idx)
{
Vec4 center = Vec4(m_elements[element_idx].computeCenter(m_node_positions, m_node_displacements));
center.SetW(1.0f);
return Vec3(m_model_transform * center);
}
std::vector<ScaleModel::Vec3> const& megamol::archvis::ScaleModel::accessNodePositions() { return m_node_positions; }
std::vector<ScaleModel::Vec3> const& megamol::archvis::ScaleModel::accessNodeDisplacements() {
return m_node_displacements;
}
ScaleModel::Mat4x4 ScaleModel::computeElementTransform(std::tuple<int, int> node_indices,
std::vector<Vec3> const& node_positions,
std::vector<Vec3> const& node_displacements)
{
Vec3 src_position = node_positions[std::get<0>(node_indices)];
Vec3 tgt_position = node_positions[std::get<1>(node_indices)];
Vec3 src_displaced = src_position + node_displacements[std::get<0>(node_indices)];
Vec3 tgt_displaced = tgt_position + node_displacements[std::get<1>(node_indices)];
// compute element rotation
Mat4x4 object_rotation;
Vec3 diag_vector = tgt_displaced - src_displaced;
diag_vector.Normalise();
Vec3 up_vector(0.0f, 1.0f, 0.0f);
Vec3 rot_vector = up_vector.Cross(diag_vector);
rot_vector.Normalise();
Quat rotation(std::acos(up_vector.Dot(diag_vector)), rot_vector);
object_rotation = rotation;
// compute element scale
Mat4x4 object_scale;
float base_distance = (tgt_position - src_position).Length();
float displaced_distance = (tgt_displaced - src_displaced).Length();
object_scale.SetAt(1, 1, displaced_distance / base_distance);
// compute element offset
Mat4x4 object_translation;
object_translation.SetAt(0, 3, src_displaced.X() );
object_translation.SetAt(1, 3, src_displaced.Y() );
object_translation.SetAt(2, 3, src_displaced.Z() );
return (object_translation * object_rotation * object_scale);
}
ScaleModel::Mat4x4 ScaleModel::computeElementTransform(std::tuple<int, int, int, int> node_indices,
std::vector<Vec3> const& node_positions,
std::vector<Vec3> const& node_displacements)
{
Vec3 origin_displaced = node_positions[std::get<0>(node_indices)] + node_displacements[std::get<0>(node_indices)];
Vec3 corner_x_displaced = node_positions[std::get<1>(node_indices)] + node_displacements[std::get<1>(node_indices)];
Vec3 corner_z_displaced = node_positions[std::get<3>(node_indices)] + node_displacements[std::get<3>(node_indices)];
Vec3 corner_xz_displaced = node_positions[std::get<2>(node_indices)] + node_displacements[std::get<2>(node_indices)];
// compute coordinate frame of planar surface given by four points
Vec3 x_axis = corner_x_displaced - origin_displaced;
x_axis.Normalise();
Vec3 z_axis = corner_z_displaced - origin_displaced;
z_axis.Normalise();
Vec3 y_axis = -x_axis.Cross(z_axis);
y_axis.Normalise();
Mat4x4 rotational_transform;
rotational_transform.SetAt(0, 0, x_axis.X());
rotational_transform.SetAt(1, 0, x_axis.Y());
rotational_transform.SetAt(2, 0, x_axis.Z());
rotational_transform.SetAt(0, 1, y_axis.X());
rotational_transform.SetAt(1, 1, y_axis.Y());
rotational_transform.SetAt(2, 1, y_axis.Z());
rotational_transform.SetAt(0, 2, z_axis.X());
rotational_transform.SetAt(1, 2, z_axis.Y());
rotational_transform.SetAt(2, 2, z_axis.Z());
rotational_transform.SetAt(3, 3, 1.0f);
// compute element offset
Mat4x4 object_translation;
object_translation.SetAt(0, 3, origin_displaced.X());
object_translation.SetAt(1, 3, origin_displaced.Y());
object_translation.SetAt(2, 3, origin_displaced.Z());
return (object_translation * rotational_transform);
}
ScaleModel::Vec3 ScaleModel::computeElementCenter(std::tuple<int, int> node_indices,
std::vector<Vec3> const& node_positions,
std::vector<Vec3> const& node_displacements)
{
Vec3 src_position = node_positions[std::get<0>(node_indices)];
Vec3 tgt_position = node_positions[std::get<1>(node_indices)];
Vec3 src_displaced = src_position + node_displacements[std::get<0>(node_indices)];
Vec3 tgt_displaced = tgt_position + node_displacements[std::get<1>(node_indices)];
return (src_displaced + tgt_displaced)*0.5f;
}
ScaleModel::Vec3 ScaleModel::computeElementCenter(std::tuple<int, int, int, int> node_indices,
std::vector<Vec3> const& node_positions,
std::vector<Vec3> const& node_displacements)
{
Vec3 origin_displaced = node_positions[std::get<0>(node_indices)] + node_displacements[std::get<0>(node_indices)];
Vec3 corner_x_displaced = node_positions[std::get<1>(node_indices)] + node_displacements[std::get<1>(node_indices)];
Vec3 corner_z_displaced = node_positions[std::get<3>(node_indices)] + node_displacements[std::get<3>(node_indices)];
Vec3 corner_xz_displaced = node_positions[std::get<2>(node_indices)] + node_displacements[std::get<2>(node_indices)];
return (origin_displaced + corner_x_displaced + corner_z_displaced + corner_xz_displaced)*0.25f;
} | 31.657658 | 124 | 0.749858 | azuki-monster |
ec8dbf21301fd11a54a4ec8946a7ecf45c18a269 | 2,507 | hpp | C++ | src/ast.hpp | camila314/Broma | ceb3aeb853271bf0c1766d17c32c592f8c7c8c21 | [
"MIT"
] | 1 | 2022-01-11T18:53:23.000Z | 2022-01-11T18:53:23.000Z | src/ast.hpp | camila314/Broma | ceb3aeb853271bf0c1766d17c32c592f8c7c8c21 | [
"MIT"
] | 1 | 2022-01-11T20:50:13.000Z | 2022-01-11T20:50:13.000Z | src/ast.hpp | CacaoSDK/Broma | ceb3aeb853271bf0c1766d17c32c592f8c7c8c21 | [
"MIT"
] | 2 | 2022-01-11T20:32:21.000Z | 2022-01-14T17:42:25.000Z | #pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
using std::vector, std::unordered_map, std::string, std::is_same_v, std::cout, std::cin, std::endl;
struct ClassDefinition;
enum FieldType {
kFunction=0,
kMember=1,
kInline=2
};
struct ClassField {
FieldType field_type;
ClassDefinition* parent_class;
};
enum FunctionType {
kVirtualFunction=0,
kStaticFunction=1,
kRegularFunction=2,
//kStructorCutoff=10, // used for comparisons
kConstructor=11,
kDestructor=12
};
struct Function : ClassField {
Function() : is_const(), return_type(), name(), args(), binds(), android_mangle(), index() {}
bool is_const;
FunctionType function_type;
string return_type;
string name;
vector<string> args;
string binds[3]; // mac, windows, ios (android has all symbols included). No binding = no string. Stored as a string because no math is done on it
string android_mangle; // only sometimes matters. empty if irrelevant
size_t index;
};
struct Member : ClassField {
Member() : type(), name(), hardcode(), hardcodes(), count() {}
string type;
string name;
bool hardcode;
string hardcodes[3]; // mac/ios, windows, android
size_t count; // for arrays
};
struct Inline : ClassField {
Inline() : inlined() {}
string inlined;
};
struct Root;
struct ClassDefinition {
string name;
vector<string> superclasses;
vector<Function> functions;
vector<Member> members;
vector<Inline> inlines;
vector<ClassField*> in_order;
void addSuperclass(string sclass) {
if (std::find(superclasses.begin(), superclasses.end(), sclass) == superclasses.end()) {
superclasses.push_back(sclass);
}
// intentional
// else cacerr("Duplicate superclass %s for class %s\n", sclass.c_str(), name.c_str());
}
template<typename T>
void addField(T& field) {
field.parent_class = this;
if constexpr (is_same_v<Function, T>) {
field.index = functions.size();
field.field_type = FieldType::kFunction;
functions.push_back(field);
}
if constexpr (is_same_v<Member, T>) {
field.field_type = FieldType::kMember;
members.push_back(field);
}
if constexpr (is_same_v<Inline, T>) {
field.field_type = FieldType::kInline;
inlines.push_back(field);
}
}
};
struct Root {
unordered_map<string, ClassDefinition> classes;
ClassDefinition& addClass(string name) {
if (classes.find(name) == classes.end()) {
classes[name] = ClassDefinition();
classes[name].name = name;
}
return classes[name];
}
};
| 23.212963 | 147 | 0.708018 | camila314 |
ec8fddd0f498c738de2bfc064e886c2cb5235326 | 2,304 | cc | C++ | src/Error.cc | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | 1 | 2020-01-06T09:43:56.000Z | 2020-01-06T09:43:56.000Z | src/Error.cc | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | src/Error.cc | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | #include <utility>
#include "Error.hh"
#include "ast/Type.hh"
void error::syntax_error(const std::string_view err) { report_error(err); }
void error::syntax(TokenType expected, Token got) {
std::ostringstream oss {};
oss << "Invalid syntax, expected " << token_names[expected];
oss << " got " << token_names[got.type];
report_error(oss.str());
}
void error::syntax(const std::string &s, TokenBuffer &tokens) {
std::ostringstream oss {};
oss << s << " " << tokens.dump() << std::endl;
report_error(oss.str());
}
void error::report_error(const std::string_view err, bool quit) {
std::cout << Color::Modifier(Color::FG_RED) << err
<< Color::Modifier(Color::FG_DEFAULT) << std::endl;
if (quit) exit(EXIT_FAILURE);
}
std::string line_text(SourceRef source_ref) {
std::ostringstream oss {};
oss << "Line " << (source_ref.begin->row + 1) << " column "
<< (source_ref.begin->col + 1);
return oss.str();
}
void error::mismatched_type(const Type &a, const Type &b,
SourceRef source_ref) {
std::ostringstream oss {};
auto tokens = TokenBuffer::source_tokens(source_ref);
oss << line_text(source_ref) << ": ";
oss << "Mismatched types, got " << a.to_user_string() << " and " << b.to_user_string()
<< std::endl;
oss << "\t" << tokens.as_source();
add_semantic_error(oss.str());
}
void error::add_semantic_error(const std::string error) {
semantic_errors.push_back(error);
}
void error::add_semantic_error(const std::string error_prefix,
const Token &token) {
std::ostringstream oss {};
oss << error_prefix << ": " << token.to_string();
add_semantic_error(oss.str());
}
void error::add_semantic_error(const std::string error_prefix,
SourceRef source_ref) {
auto tokens = TokenBuffer::source_tokens(source_ref);
std::ostringstream oss {};
oss << line_text(source_ref) << ": ";
oss << error_prefix << std::endl;
oss << "\t" << tokens.as_source();
add_semantic_error(oss.str());
}
void error::report_semantic_errors() {
if (semantic_errors.empty()) return;
for (auto &error : semantic_errors) {
report_error(error, false);
}
exit(EXIT_FAILURE);
}
| 28.8 | 90 | 0.61849 | walecome |
ec9e2db9686565bd9f58b3a43512b0a2c281a845 | 1,559 | cc | C++ | source/common/formatter/substitution_format_string.cc | tgalkovskyi/envoy | 9d702c125acde33933fc5d63818b1defe36b5cf3 | [
"Apache-2.0"
] | 3 | 2020-06-04T03:26:32.000Z | 2020-06-04T03:26:45.000Z | source/common/formatter/substitution_format_string.cc | tgalkovskyi/envoy | 9d702c125acde33933fc5d63818b1defe36b5cf3 | [
"Apache-2.0"
] | 8 | 2020-08-07T00:52:28.000Z | 2020-09-24T22:11:43.000Z | source/common/formatter/substitution_format_string.cc | tgalkovskyi/envoy | 9d702c125acde33933fc5d63818b1defe36b5cf3 | [
"Apache-2.0"
] | 3 | 2020-03-29T08:27:26.000Z | 2022-02-17T14:12:22.000Z | #include "common/formatter/substitution_format_string.h"
#include "common/formatter/substitution_formatter.h"
namespace Envoy {
namespace Formatter {
namespace {
absl::flat_hash_map<std::string, std::string>
convertJsonFormatToMap(const ProtobufWkt::Struct& json_format) {
absl::flat_hash_map<std::string, std::string> output;
for (const auto& pair : json_format.fields()) {
if (pair.second.kind_case() != ProtobufWkt::Value::kStringValue) {
throw EnvoyException("Only string values are supported in the JSON access log format.");
}
output.emplace(pair.first, pair.second.string_value());
}
return output;
}
} // namespace
FormatterPtr
SubstitutionFormatStringUtils::createJsonFormatter(const ProtobufWkt::Struct& struct_format,
bool preserve_types) {
auto json_format_map = convertJsonFormatToMap(struct_format);
return std::make_unique<JsonFormatterImpl>(json_format_map, preserve_types);
}
FormatterPtr SubstitutionFormatStringUtils::fromProtoConfig(
const envoy::config::core::v3::SubstitutionFormatString& config) {
switch (config.format_case()) {
case envoy::config::core::v3::SubstitutionFormatString::FormatCase::kTextFormat:
return std::make_unique<FormatterImpl>(config.text_format());
case envoy::config::core::v3::SubstitutionFormatString::FormatCase::kJsonFormat: {
return createJsonFormatter(config.json_format(), true);
}
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
return nullptr;
}
} // namespace Formatter
} // namespace Envoy
| 33.891304 | 94 | 0.74086 | tgalkovskyi |
ec9f2d36b59bbdfe5dd574b82b6aad36c372d195 | 38,633 | cpp | C++ | src/connection.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 4 | 2020-02-21T00:15:30.000Z | 2022-01-20T22:56:42.000Z | src/connection.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 5 | 2020-10-22T16:53:03.000Z | 2021-05-19T17:29:33.000Z | src/connection.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 5 | 2019-11-12T07:40:24.000Z | 2021-01-15T11:29:41.000Z | /*
Copyright (c) DataStax, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "connection.hpp"
#include "auth.hpp"
#include "auth_requests.hpp"
#include "auth_responses.hpp"
#include "cassandra.h"
#include "cassconfig.hpp"
#include "constants.hpp"
#include "connector.hpp"
#include "timer.hpp"
#include "config.hpp"
#include "result_response.hpp"
#include "supported_response.hpp"
#include "startup_request.hpp"
#include "query_request.hpp"
#include "options_request.hpp"
#include "register_request.hpp"
#include "error_response.hpp"
#include "event_response.hpp"
#include "logger.hpp"
#ifdef HAVE_NOSIGPIPE
#include <sys/socket.h>
#include <sys/types.h>
#endif
#include <iomanip>
#include <sstream>
#define SSL_READ_SIZE 8192
#define SSL_WRITE_SIZE 8192
#define SSL_ENCRYPTED_BUFS_COUNT 16
#define MAX_BUFFER_REUSE_NO 8
#define BUFFER_REUSE_SIZE 64 * 1024
#if UV_VERSION_MAJOR == 0
#define UV_ERRSTR(status, loop) uv_strerror(uv_last_error(loop))
#else
#define UV_ERRSTR(status, loop) uv_strerror(status)
#endif
namespace cass {
static void cleanup_pending_callbacks(List<RequestCallback>* pending) {
while (!pending->is_empty()) {
RequestCallback::Ptr callback(pending->front());
pending->remove(callback.get());
switch (callback->state()) {
case RequestCallback::REQUEST_STATE_NEW:
case RequestCallback::REQUEST_STATE_FINISHED:
case RequestCallback::REQUEST_STATE_CANCELLED:
assert(false && "Request state is invalid in cleanup");
break;
case RequestCallback::REQUEST_STATE_READ_BEFORE_WRITE:
callback->set_state(RequestCallback::REQUEST_STATE_FINISHED);
// Use the response saved in the read callback
callback->on_set(callback->read_before_write_response());
break;
case RequestCallback::REQUEST_STATE_WRITING:
case RequestCallback::REQUEST_STATE_READING:
callback->set_state(RequestCallback::REQUEST_STATE_FINISHED);
if (callback->request()->is_idempotent()) {
callback->on_retry_next_host();
} else {
callback->on_error(CASS_ERROR_LIB_REQUEST_TIMED_OUT,
"Request timed out");
}
break;
case RequestCallback::REQUEST_STATE_CANCELLED_WRITING:
case RequestCallback::REQUEST_STATE_CANCELLED_READING:
case RequestCallback::REQUEST_STATE_CANCELLED_READ_BEFORE_WRITE:
callback->set_state(RequestCallback::REQUEST_STATE_CANCELLED);
callback->on_cancel();
break;
}
callback->dec_ref();
}
}
Connection::StartupCallback::StartupCallback(const Request::ConstPtr& request)
: SimpleRequestCallback(request) { }
void Connection::StartupCallback::on_internal_set(ResponseMessage* response) {
switch (response->opcode()) {
case CQL_OPCODE_SUPPORTED:
connection()->on_supported(response);
break;
case CQL_OPCODE_ERROR: {
ErrorResponse* error
= static_cast<ErrorResponse*>(response->response_body().get());
ConnectionError error_code = CONNECTION_ERROR_GENERIC;
if (error->code() == CQL_ERROR_PROTOCOL_ERROR &&
error->message().find("Invalid or unsupported protocol version") != StringRef::npos) {
error_code = CONNECTION_ERROR_INVALID_PROTOCOL;
} else if (error->code() == CQL_ERROR_BAD_CREDENTIALS) {
error_code = CONNECTION_ERROR_AUTH;
} else if (error->code() == CQL_ERROR_INVALID_QUERY &&
error->message().find("Keyspace") == 0 &&
error->message().find("does not exist") != StringRef::npos) {
error_code = CONNECTION_ERROR_KEYSPACE;
}
connection()->notify_error("Received error response " + error->error_message(), error_code);
break;
}
case CQL_OPCODE_AUTHENTICATE: {
AuthenticateResponse* auth
= static_cast<AuthenticateResponse*>(response->response_body().get());
connection()->on_authenticate(auth->class_name());
break;
}
case CQL_OPCODE_AUTH_CHALLENGE:
connection()->on_auth_challenge(
static_cast<const AuthResponseRequest*>(request()),
static_cast<AuthChallengeResponse*>(response->response_body().get())->token());
break;
case CQL_OPCODE_AUTH_SUCCESS:
connection()->on_auth_success(
static_cast<const AuthResponseRequest*>(request()),
static_cast<AuthSuccessResponse*>(response->response_body().get())->token());
break;
case CQL_OPCODE_READY:
connection()->on_ready();
break;
case CQL_OPCODE_RESULT:
on_result_response(response);
break;
default:
connection()->notify_error("Invalid opcode");
break;
}
}
void Connection::StartupCallback::on_internal_error(CassError code,
const std::string& message) {
std::ostringstream ss;
ss << "Error: '" << message
<< "' (0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << code << ")";
connection()->notify_error(ss.str());
}
void Connection::StartupCallback::on_internal_timeout() {
if (!connection()->is_closing()) {
connection()->notify_error("Timed out", CONNECTION_ERROR_TIMEOUT);
}
}
void Connection::StartupCallback::on_result_response(ResponseMessage* response) {
ResultResponse* result =
static_cast<ResultResponse*>(response->response_body().get());
switch (result->kind()) {
case CASS_RESULT_KIND_SET_KEYSPACE:
connection()->on_set_keyspace();
break;
default:
connection()->notify_error("Invalid result response. Expected set keyspace.");
break;
}
}
Connection::HeartbeatCallback::HeartbeatCallback()
: SimpleRequestCallback(Request::ConstPtr(new OptionsRequest())) { }
void Connection::HeartbeatCallback::on_internal_set(ResponseMessage* response) {
LOG_TRACE("Heartbeat completed on host %s",
connection()->address_string().c_str());
connection()->heartbeat_outstanding_ = false;
}
void Connection::HeartbeatCallback::on_internal_error(CassError code, const std::string& message) {
LOG_WARN("An error occurred on host %s during a heartbeat request: %s",
connection()->address_string().c_str(),
message.c_str());
connection()->heartbeat_outstanding_ = false;
}
void Connection::HeartbeatCallback::on_internal_timeout() {
LOG_WARN("Heartbeat request timed out on host %s",
connection()->address_string().c_str());
connection()->heartbeat_outstanding_ = false;
}
Connection::Connection(uv_loop_t* loop,
const Config& config,
Metrics* metrics,
const Host::ConstPtr& host,
const std::string& keyspace,
int protocol_version,
Listener* listener)
: state_(CONNECTION_STATE_NEW)
, error_code_(CONNECTION_OK)
, ssl_error_code_(CASS_OK)
, loop_(loop)
, config_(config)
, metrics_(metrics)
, host_(host)
, keyspace_(keyspace)
, protocol_version_(protocol_version)
, listener_(listener)
, response_(new ResponseMessage())
, stream_manager_(protocol_version)
, ssl_session_(NULL)
, heartbeat_outstanding_(false) {
socket_.data = this;
uv_tcp_init(loop_, &socket_);
if (uv_tcp_nodelay(&socket_,
config.tcp_nodelay_enable() ? 1 : 0) != 0) {
LOG_WARN("Unable to set tcp nodelay");
}
if (uv_tcp_keepalive(&socket_,
config.tcp_keepalive_enable() ? 1 : 0,
config.tcp_keepalive_delay_secs()) != 0) {
LOG_WARN("Unable to set tcp keepalive");
}
SslContext* ssl_context = config_.ssl_context();
if (ssl_context != NULL) {
ssl_session_.reset(ssl_context->create_session(host));
}
}
Connection::~Connection()
{
while (!buffer_reuse_list_.empty()) {
uv_buf_t buf = buffer_reuse_list_.top();
delete[] buf.base;
buffer_reuse_list_.pop();
}
}
void Connection::connect() {
if (state_ == CONNECTION_STATE_NEW) {
set_state(CONNECTION_STATE_CONNECTING);
connect_timer_.start(loop_, config_.connect_timeout_ms(), this,
on_connect_timeout);
Connector::connect(&socket_, host_->address(), this, on_connect);
}
}
bool Connection::write(const RequestCallback::Ptr& callback, bool flush_immediately) {
int32_t result = internal_write(callback, flush_immediately);
if (result > 0) {
restart_heartbeat_timer();
}
return result != Request::REQUEST_ERROR_NO_AVAILABLE_STREAM_IDS;
}
int32_t Connection::internal_write(const RequestCallback::Ptr& callback, bool flush_immediately) {
if (callback->state() == RequestCallback::REQUEST_STATE_CANCELLED) {
return Request::REQUEST_ERROR_CANCELLED;
}
int stream = stream_manager_.acquire(callback.get());
if (stream < 0) {
return Request::REQUEST_ERROR_NO_AVAILABLE_STREAM_IDS;
}
callback->inc_ref(); // Connection reference
callback->start(this, stream);
if (pending_writes_.is_empty() || pending_writes_.back()->is_flushed()) {
if (ssl_session_) {
pending_writes_.add_to_back(new PendingWriteSsl(this));
} else {
pending_writes_.add_to_back(new PendingWrite(this));
}
}
PendingWriteBase *pending_write = pending_writes_.back();
int32_t request_size = pending_write->write(callback.get());
if (request_size < 0) {
stream_manager_.release(stream);
switch (request_size) {
case Request::REQUEST_ERROR_BATCH_WITH_NAMED_VALUES:
case Request::REQUEST_ERROR_PARAMETER_UNSET:
// Already handled
break;
default:
callback->on_error(CASS_ERROR_LIB_MESSAGE_ENCODE,
"Operation unsupported by this protocol version");
break;
}
callback->dec_ref();
return request_size;
}
LOG_TRACE("Sending message type %s with stream %d on host %s",
opcode_to_string(callback->request()->opcode()).c_str(),
stream,
address_string().c_str());
callback->set_state(RequestCallback::REQUEST_STATE_WRITING);
if (flush_immediately) {
pending_write->flush();
}
return request_size;
}
void Connection::flush() {
if (pending_writes_.is_empty()) return;
pending_writes_.back()->flush();
}
void Connection::schedule_schema_agreement(const SchemaChangeCallback::Ptr& callback, uint64_t wait) {
PendingSchemaAgreement* pending_schema_agreement = new PendingSchemaAgreement(callback);
pending_schema_agreements_.add_to_back(pending_schema_agreement);
pending_schema_agreement->timer.start(loop_,
wait,
pending_schema_agreement,
Connection::on_pending_schema_agreement);
}
void Connection::close() {
internal_close(CONNECTION_STATE_CLOSE);
}
void Connection::defunct() {
internal_close(CONNECTION_STATE_CLOSE_DEFUNCT);
}
void Connection::internal_close(ConnectionState close_state) {
assert(close_state == CONNECTION_STATE_CLOSE ||
close_state == CONNECTION_STATE_CLOSE_DEFUNCT);
if (state_ != CONNECTION_STATE_CLOSE &&
state_ != CONNECTION_STATE_CLOSE_DEFUNCT) {
uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&socket_);
if (!uv_is_closing(handle)) {
heartbeat_timer_.stop();
terminate_timer_.stop();
connect_timer_.stop();
set_state(close_state);
uv_close(handle, on_close);
}
}
}
void Connection::set_state(ConnectionState new_state) {
// Only update if the state changed
if (new_state == state_) return;
switch (state_) {
case CONNECTION_STATE_NEW:
assert(new_state == CONNECTION_STATE_CONNECTING &&
"Invalid connection state after new");
state_ = new_state;
break;
case CONNECTION_STATE_CONNECTING:
assert((new_state == CONNECTION_STATE_CONNECTED ||
new_state == CONNECTION_STATE_CLOSE ||
new_state == CONNECTION_STATE_CLOSE_DEFUNCT) &&
"Invalid connection state after connecting");
state_ = new_state;
break;
case CONNECTION_STATE_CONNECTED:
assert((new_state == CONNECTION_STATE_REGISTERING_EVENTS ||
new_state == CONNECTION_STATE_READY ||
new_state == CONNECTION_STATE_CLOSE ||
new_state == CONNECTION_STATE_CLOSE_DEFUNCT) &&
"Invalid connection state after connected");
state_ = new_state;
break;
case CONNECTION_STATE_REGISTERING_EVENTS:
assert((new_state == CONNECTION_STATE_READY ||
new_state == CONNECTION_STATE_CLOSE ||
new_state == CONNECTION_STATE_CLOSE_DEFUNCT) &&
"Invalid connection state after registering for events");
state_ = new_state;
break;
case CONNECTION_STATE_READY:
assert((new_state == CONNECTION_STATE_CLOSE ||
new_state == CONNECTION_STATE_CLOSE_DEFUNCT) &&
"Invalid connection state after ready");
state_ = new_state;
break;
case CONNECTION_STATE_CLOSE:
assert(false && "No state change after close");
break;
case CONNECTION_STATE_CLOSE_DEFUNCT:
assert(false && "No state change after close defunct");
break;
}
}
void Connection::consume(char* input, size_t size) {
char* buffer = input;
size_t remaining = size;
// A successful read means the connection is still responsive
restart_terminate_timer();
while (remaining != 0 && !is_closing()) {
ssize_t consumed = response_->decode(buffer, remaining);
if (consumed <= 0) {
notify_error("Error consuming message");
continue;
}
if (response_->is_body_ready()) {
ScopedPtr<ResponseMessage> response(response_.release());
response_.reset(new ResponseMessage());
LOG_TRACE("Consumed message type %s with stream %d, input %u, remaining %u on host %s",
opcode_to_string(response->opcode()).c_str(),
static_cast<int>(response->stream()),
static_cast<unsigned int>(size),
static_cast<unsigned int>(remaining),
host_->address_string().c_str());
if (response->stream() < 0) {
if (response->opcode() == CQL_OPCODE_EVENT) {
listener_->on_event(static_cast<EventResponse*>(response->response_body().get()));
} else {
notify_error("Invalid response opcode for event stream: " +
opcode_to_string(response->opcode()));
continue;
}
} else {
RequestCallback* temp = NULL;
if (stream_manager_.get_pending_and_release(response->stream(), temp)) {
RequestCallback::Ptr callback(temp);
switch (callback->state()) {
case RequestCallback::REQUEST_STATE_READING:
pending_reads_.remove(callback.get());
callback->set_state(RequestCallback::REQUEST_STATE_FINISHED);
maybe_set_keyspace(response.get());
callback->on_set(response.get());
callback->dec_ref();
break;
case RequestCallback::REQUEST_STATE_WRITING:
// There are cases when the read callback will happen
// before the write callback. If this happens we have
// to allow the write callback to finish the request.
callback->set_state(RequestCallback::REQUEST_STATE_READ_BEFORE_WRITE);
// Save the response for the write callback
callback->set_read_before_write_response(response.release()); // Transfer ownership
break;
case RequestCallback::REQUEST_STATE_CANCELLED_READING:
pending_reads_.remove(callback.get());
callback->set_state(RequestCallback::REQUEST_STATE_CANCELLED);
callback->on_cancel();
callback->dec_ref();
break;
case RequestCallback::REQUEST_STATE_CANCELLED_WRITING:
// There are cases when the read callback will happen
// before the write callback. If this happens we have
// to allow the write callback to finish the request.
callback->set_state(RequestCallback::REQUEST_STATE_CANCELLED_READ_BEFORE_WRITE);
break;
default:
assert(false && "Invalid request state after receiving response");
break;
}
} else {
notify_error("Invalid stream ID");
continue;
}
}
}
remaining -= consumed;
buffer += consumed;
}
}
void Connection::maybe_set_keyspace(ResponseMessage* response) {
if (response->opcode() == CQL_OPCODE_RESULT) {
ResultResponse* result =
static_cast<ResultResponse*>(response->response_body().get());
if (result->kind() == CASS_RESULT_KIND_SET_KEYSPACE) {
keyspace_ = result->keyspace().to_string();
}
}
}
void Connection::on_connect(Connector* connector) {
Connection* connection = static_cast<Connection*>(connector->data());
if (!connection->connect_timer_.is_running()) {
return; // Timed out
}
if (connector->status() == 0) {
LOG_DEBUG("Connected to host %s on connection(%p)",
connection->host_->address_string().c_str(),
static_cast<void*>(connection));
#if defined(HAVE_NOSIGPIPE) && UV_VERSION_MAJOR >= 1
// This must be done after connection for the socket file descriptor to be
// valid.
uv_os_fd_t fd = 0;
int enabled = 1;
if (uv_fileno(reinterpret_cast<uv_handle_t*>(&connection->socket_), &fd) != 0 ||
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&enabled, sizeof(int)) != 0) {
LOG_WARN("Unable to set socket option SO_NOSIGPIPE for host %s",
connection->host_->address_string().c_str());
}
#endif
if (connection->ssl_session_) {
uv_read_start(reinterpret_cast<uv_stream_t*>(&connection->socket_),
Connection::alloc_buffer_ssl, Connection::on_read_ssl);
} else {
uv_read_start(reinterpret_cast<uv_stream_t*>(&connection->socket_),
Connection::alloc_buffer, Connection::on_read);
}
connection->set_state(CONNECTION_STATE_CONNECTED);
if (connection->ssl_session_) {
connection->ssl_handshake();
} else {
connection->on_connected();
}
} else {
connection->notify_error("Connect error '" +
std::string(UV_ERRSTR(connector->status(), connection->loop_)) +
"'");
}
}
void Connection::on_connect_timeout(Timer* timer) {
Connection* connection = static_cast<Connection*>(timer->data());
connection->notify_error("Connection timeout", CONNECTION_ERROR_TIMEOUT);
connection->metrics_->connection_timeouts.inc();
}
void Connection::on_close(uv_handle_t* handle) {
Connection* connection = static_cast<Connection*>(handle->data);
LOG_DEBUG("Connection(%p) to host %s closed",
static_cast<void*>(connection),
connection->host_->address_string().c_str());
cleanup_pending_callbacks(&connection->pending_reads_);
while (!connection->pending_writes_.is_empty()) {
PendingWriteBase* pending_write
= connection->pending_writes_.front();
connection->pending_writes_.remove(pending_write);
delete pending_write;
}
while (!connection->pending_schema_agreements_.is_empty()) {
PendingSchemaAgreement* pending_schema_aggreement
= connection->pending_schema_agreements_.front();
connection->pending_schema_agreements_.remove(pending_schema_aggreement);
pending_schema_aggreement->stop_timer();
pending_schema_aggreement->callback->on_closing();
delete pending_schema_aggreement;
}
connection->listener_->on_close(connection);
delete connection;
}
uv_buf_t Connection::internal_alloc_buffer(size_t suggested_size) {
if (suggested_size <= BUFFER_REUSE_SIZE) {
if (!buffer_reuse_list_.empty()) {
uv_buf_t ret = buffer_reuse_list_.top();
buffer_reuse_list_.pop();
return ret;
}
return uv_buf_init(new char[BUFFER_REUSE_SIZE], BUFFER_REUSE_SIZE);
}
return uv_buf_init(new char[suggested_size], suggested_size);
}
void Connection::internal_reuse_buffer(uv_buf_t buf) {
if (buf.len == BUFFER_REUSE_SIZE && buffer_reuse_list_.size() < MAX_BUFFER_REUSE_NO) {
buffer_reuse_list_.push(buf);
return;
}
delete[] buf.base;
}
#if UV_VERSION_MAJOR == 0
uv_buf_t Connection::alloc_buffer(uv_handle_t* handle, size_t suggested_size) {
Connection* connection = static_cast<Connection*>(handle->data);
return connection->internal_alloc_buffer(suggested_size);
}
#else
void Connection::alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
Connection* connection = static_cast<Connection*>(handle->data);
*buf = connection->internal_alloc_buffer(suggested_size);
}
#endif
#if UV_VERSION_MAJOR == 0
void Connection::on_read(uv_stream_t* client, ssize_t nread, uv_buf_t buf) {
#else
void Connection::on_read(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf) {
#endif
Connection* connection = static_cast<Connection*>(client->data);
if (nread < 0) {
#if UV_VERSION_MAJOR == 0
if (uv_last_error(connection->loop_).code != UV_EOF) {
#else
if (nread != UV_EOF) {
#endif
connection->notify_error("Read error '" +
std::string(UV_ERRSTR(nread, connection->loop_)) +
"'");
} else {
connection->defunct();
}
#if UV_VERSION_MAJOR == 0
connection->internal_reuse_buffer(buf);
#else
connection->internal_reuse_buffer(*buf);
#endif
return;
}
#if UV_VERSION_MAJOR == 0
connection->consume(buf.base, nread);
connection->internal_reuse_buffer(buf);
#else
connection->consume(buf->base, nread);
connection->internal_reuse_buffer(*buf);
#endif
}
#if UV_VERSION_MAJOR == 0
uv_buf_t Connection::alloc_buffer_ssl(uv_handle_t* handle, size_t suggested_size) {
Connection* connection = static_cast<Connection*>(handle->data);
char* base = connection->ssl_session_->incoming().peek_writable(&suggested_size);
return uv_buf_init(base, suggested_size);
}
#else
void Connection::alloc_buffer_ssl(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
Connection* connection = static_cast<Connection*>(handle->data);
buf->base = connection->ssl_session_->incoming().peek_writable(&suggested_size);
buf->len = suggested_size;
}
#endif
#if UV_VERSION_MAJOR == 0
void Connection::on_read_ssl(uv_stream_t* client, ssize_t nread, uv_buf_t buf) {
#else
void Connection::on_read_ssl(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf) {
#endif
Connection* connection = static_cast<Connection*>(client->data);
SslSession* ssl_session = connection->ssl_session_.get();
assert(ssl_session != NULL);
if (nread < 0) {
#if UV_VERSION_MAJOR == 0
if (uv_last_error(connection->loop_).code != UV_EOF) {
#else
if (nread != UV_EOF) {
#endif
connection->notify_error("Read error '" +
std::string(UV_ERRSTR(nread, connection->loop_)) +
"'");
} else {
connection->defunct();
}
return;
}
ssl_session->incoming().commit(nread);
if (ssl_session->is_handshake_done()) {
char buf[SSL_READ_SIZE];
int rc = 0;
while ((rc = ssl_session->decrypt(buf, sizeof(buf))) > 0) {
connection->consume(buf, rc);
}
if (rc <= 0 && ssl_session->has_error()) {
connection->notify_error("Unable to decrypt data: " + ssl_session->error_message(),
CONNECTION_ERROR_SSL_DECRYPT);
}
} else {
connection->ssl_handshake();
}
}
void Connection::on_connected() {
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new OptionsRequest()))));
}
void Connection::on_authenticate(const std::string& class_name) {
if (protocol_version_ == 1) {
send_credentials(class_name);
} else {
send_initial_auth_response(class_name);
}
}
void Connection::on_auth_challenge(const AuthResponseRequest* request,
const std::string& token) {
std::string response;
if (!request->auth()->evaluate_challenge(token, &response)) {
notify_error("Failed evaluating challenge token: " + request->auth()->error(), CONNECTION_ERROR_AUTH);
return;
}
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new AuthResponseRequest(response, request->auth())))));
}
void Connection::on_auth_success(const AuthResponseRequest* request,
const std::string& token) {
if (!request->auth()->success(token)) {
notify_error("Failed evaluating success token: " + request->auth()->error(), CONNECTION_ERROR_AUTH);
return;
}
on_ready();
}
void Connection::on_ready() {
if (state_ == CONNECTION_STATE_CONNECTED && listener_->event_types() != 0) {
set_state(CONNECTION_STATE_REGISTERING_EVENTS);
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new RegisterRequest(listener_->event_types())))));
return;
}
if (keyspace_.empty()) {
notify_ready();
} else {
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new QueryRequest("USE \"" + keyspace_ + "\"")))));
}
}
void Connection::on_set_keyspace() {
notify_ready();
}
void Connection::on_supported(ResponseMessage* response) {
SupportedResponse* supported =
static_cast<SupportedResponse*>(response->response_body().get());
// TODO(mstump) do something with the supported info
(void)supported;
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new StartupRequest(config().no_compact())))));
}
void Connection::on_pending_schema_agreement(Timer* timer) {
PendingSchemaAgreement* pending_schema_agreement
= static_cast<PendingSchemaAgreement*>(timer->data());
Connection* connection = pending_schema_agreement->callback->connection();
connection->pending_schema_agreements_.remove(pending_schema_agreement);
pending_schema_agreement->callback->execute();
delete pending_schema_agreement;
}
void Connection::notify_ready() {
connect_timer_.stop();
restart_heartbeat_timer();
restart_terminate_timer();
set_state(CONNECTION_STATE_READY);
listener_->on_ready(this);
}
void Connection::notify_error(const std::string& message, ConnectionError code) {
assert(code != CONNECTION_OK && "Notified error without an error");
LOG_DEBUG("Lost connection(%p) to host %s with the following error: %s",
static_cast<void*>(this),
host_->address_string().c_str(),
message.c_str());
error_message_ = message;
error_code_ = code;
if (is_ssl_error()) {
ssl_error_code_ = ssl_session_->error_code();
}
defunct();
}
void Connection::ssl_handshake() {
if (!ssl_session_->is_handshake_done()) {
ssl_session_->do_handshake();
if (ssl_session_->has_error()) {
notify_error("Error during SSL handshake: " + ssl_session_->error_message(),
CONNECTION_ERROR_SSL_HANDSHAKE);
return;
}
}
char buf[SslHandshakeWriter::MAX_BUFFER_SIZE];
size_t size = ssl_session_->outgoing().read(buf, sizeof(buf));
if (size > 0) {
if (!SslHandshakeWriter::write(this, buf, size)) {
notify_error("Error writing data during SSL handshake");
return;
}
}
if (ssl_session_->is_handshake_done()) {
ssl_session_->verify();
if (ssl_session_->has_error()) {
notify_error("Error verifying peer certificate: " + ssl_session_->error_message(),
CONNECTION_ERROR_SSL_VERIFY);
return;
}
on_connected();
}
}
void Connection::send_credentials(const std::string& class_name) {
ScopedPtr<V1Authenticator> v1_auth(config_.auth_provider()->new_authenticator_v1(host_, class_name));
if (v1_auth) {
V1Authenticator::Credentials credentials;
v1_auth->get_credentials(&credentials);
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new CredentialsRequest(credentials)))));
} else {
send_initial_auth_response(class_name);
}
}
void Connection::send_initial_auth_response(const std::string& class_name) {
Authenticator::Ptr auth(config_.auth_provider()->new_authenticator(host_, class_name));
if (!auth) {
notify_error("Authentication required but no auth provider set", CONNECTION_ERROR_AUTH);
} else {
std::string response;
if (!auth->initial_response(&response)) {
notify_error("Failed creating initial response token: " + auth->error(), CONNECTION_ERROR_AUTH);
return;
}
internal_write(RequestCallback::Ptr(
new StartupCallback(Request::ConstPtr(
new AuthResponseRequest(response, auth)))));
}
}
void Connection::restart_heartbeat_timer() {
if (config_.connection_heartbeat_interval_secs() > 0) {
heartbeat_timer_.start(loop_,
1000 * config_.connection_heartbeat_interval_secs(),
this, on_heartbeat);
}
}
void Connection::on_heartbeat(Timer* timer) {
Connection* connection = static_cast<Connection*>(timer->data());
if (!connection->heartbeat_outstanding_) {
if (!connection->internal_write(RequestCallback::Ptr(new HeartbeatCallback()))) {
// Recycling only this connection with a timeout error. This is unlikely and
// it means the connection ran out of stream IDs as a result of requests
// that never returned and as a result timed out.
connection->notify_error("No streams IDs available for heartbeat request. "
"Terminating connection...",
CONNECTION_ERROR_TIMEOUT);
return;
}
connection->heartbeat_outstanding_ = true;
}
connection->restart_heartbeat_timer();
}
void Connection::restart_terminate_timer() {
// The terminate timer shouldn't be started without having heartbeats enabled,
// otherwise connections would be terminated in periods of request inactivity.
if (config_.connection_heartbeat_interval_secs() > 0 &&
config_.connection_idle_timeout_secs() > 0) {
terminate_timer_.start(loop_,
1000 * config_.connection_idle_timeout_secs(),
this, on_terminate);
}
}
void Connection::on_terminate(Timer* timer) {
Connection* connection = static_cast<Connection*>(timer->data());
connection->notify_error("Failed to send a heartbeat within connection idle interval. "
"Terminating connection...",
CONNECTION_ERROR_TIMEOUT);
}
void Connection::PendingSchemaAgreement::stop_timer() {
timer.stop();
}
Connection::PendingWriteBase::~PendingWriteBase() {
cleanup_pending_callbacks(&callbacks_);
}
int32_t Connection::PendingWriteBase::write(RequestCallback* callback) {
size_t last_buffer_size = buffers_.size();
int32_t request_size = callback->encode(connection_->protocol_version_, 0x00, &buffers_);
if (request_size < 0) {
buffers_.resize(last_buffer_size); // rollback
return request_size;
}
size_ += request_size;
callbacks_.add_to_back(callback);
return request_size;
}
void Connection::PendingWriteBase::on_write(uv_write_t* req, int status) {
PendingWrite* pending_write = static_cast<PendingWrite*>(req->data);
Connection* connection = static_cast<Connection*>(pending_write->connection_);
while (!pending_write->callbacks_.is_empty()) {
RequestCallback::Ptr callback(pending_write->callbacks_.front());
pending_write->callbacks_.remove(callback.get());
switch (callback->state()) {
case RequestCallback::REQUEST_STATE_WRITING:
if (status == 0) {
callback->set_state(RequestCallback::REQUEST_STATE_READING);
connection->pending_reads_.add_to_back(callback.get());
} else {
if (!connection->is_closing()) {
connection->notify_error("Write error '" +
std::string(UV_ERRSTR(status, connection->loop_)) +
"'");
connection->defunct();
}
connection->stream_manager_.release(callback->stream());
callback->set_state(RequestCallback::REQUEST_STATE_FINISHED);
callback->on_error(CASS_ERROR_LIB_WRITE_ERROR,
"Unable to write to socket");
callback->dec_ref();
}
break;
case RequestCallback::REQUEST_STATE_READ_BEFORE_WRITE:
// The read callback happened before the write callback
// returned. This is now responsible for finishing the request.
callback->set_state(RequestCallback::REQUEST_STATE_FINISHED);
// Use the response saved in the read callback
connection->maybe_set_keyspace(callback->read_before_write_response());
callback->on_set(callback->read_before_write_response());
callback->dec_ref();
break;
case RequestCallback::REQUEST_STATE_CANCELLED_WRITING:
callback->set_state(RequestCallback::REQUEST_STATE_CANCELLED_READING);
connection->pending_reads_.add_to_back(callback.get());
break;
case RequestCallback::REQUEST_STATE_CANCELLED_READ_BEFORE_WRITE:
// The read callback happened before the write callback
// returned. This is now responsible for cleanup.
callback->set_state(RequestCallback::REQUEST_STATE_CANCELLED);
callback->on_cancel();
callback->dec_ref();
break;
default:
assert(false && "Invalid request state after write finished");
break;
}
}
connection->pending_writes_.remove(pending_write);
delete pending_write;
connection->flush();
}
void Connection::PendingWrite::flush() {
if (!is_flushed_ && !buffers_.empty()) {
UvBufVec bufs;
bufs.reserve(buffers_.size());
for (BufferVec::const_iterator it = buffers_.begin(),
end = buffers_.end(); it != end; ++it) {
bufs.push_back(uv_buf_init(const_cast<char*>(it->data()), it->size()));
}
is_flushed_ = true;
uv_stream_t* sock_stream = reinterpret_cast<uv_stream_t*>(&connection_->socket_);
uv_write(&req_, sock_stream, bufs.data(), bufs.size(), PendingWrite::on_write);
}
}
void Connection::PendingWriteSsl::encrypt() {
char buf[SSL_WRITE_SIZE];
size_t copied = 0;
size_t offset = 0;
size_t total = 0;
SslSession* ssl_session = connection_->ssl_session_.get();
BufferVec::const_iterator it = buffers_.begin(),
end = buffers_.end();
LOG_TRACE("Copying %u bufs", static_cast<unsigned int>(buffers_.size()));
bool is_done = (it == end);
while (!is_done) {
assert(it->size() > 0);
size_t size = it->size();
size_t to_copy = size - offset;
size_t available = SSL_WRITE_SIZE - copied;
if (available < to_copy) {
to_copy = available;
}
memcpy(buf + copied, it->data() + offset, to_copy);
copied += to_copy;
offset += to_copy;
total += to_copy;
if (offset == size) {
++it;
offset = 0;
}
is_done = (it == end);
if (is_done || copied == SSL_WRITE_SIZE) {
int rc = ssl_session->encrypt(buf, copied);
if (rc <= 0 && ssl_session->has_error()) {
connection_->notify_error("Unable to encrypt data: " + ssl_session->error_message(),
CONNECTION_ERROR_SSL_ENCRYPT);
return;
}
copied = 0;
}
}
LOG_TRACE("Copied %u bytes for encryption", static_cast<unsigned int>(total));
}
void Connection::PendingWriteSsl::flush() {
if (!is_flushed_ && !buffers_.empty()) {
SslSession* ssl_session = connection_->ssl_session_.get();
rb::RingBuffer::Position prev_pos = ssl_session->outgoing().write_position();
encrypt();
SmallVector<uv_buf_t, SSL_ENCRYPTED_BUFS_COUNT> bufs;
encrypted_size_ = ssl_session->outgoing().peek_multiple(prev_pos, &bufs);
LOG_TRACE("Sending %u encrypted bytes", static_cast<unsigned int>(encrypted_size_));
uv_stream_t* sock_stream = reinterpret_cast<uv_stream_t*>(&connection_->socket_);
uv_write(&req_, sock_stream, bufs.data(), bufs.size(), PendingWriteSsl::on_write);
is_flushed_ = true;
}
}
void Connection::PendingWriteSsl::on_write(uv_write_t* req, int status) {
if (status == 0) {
PendingWriteSsl* pending_write = static_cast<PendingWriteSsl*>(req->data);
pending_write->connection_->ssl_session_->outgoing().read(NULL, pending_write->encrypted_size_);
}
PendingWriteBase::on_write(req, status);
}
bool Connection::SslHandshakeWriter::write(Connection* connection, char* buf, size_t buf_size) {
SslHandshakeWriter* writer = new SslHandshakeWriter(connection, buf, buf_size);
uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(&connection->socket_);
int rc = uv_write(&writer->req_, stream, &writer->uv_buf_, 1, SslHandshakeWriter::on_write);
if (rc != 0) {
delete writer;
return false;
}
return true;
}
Connection::SslHandshakeWriter::SslHandshakeWriter(Connection* connection, char* buf, size_t buf_size)
: connection_(connection)
, uv_buf_(uv_buf_init(buf, buf_size)) {
memcpy(buf_, buf, buf_size);
req_.data = this;
}
void Connection::SslHandshakeWriter::on_write(uv_write_t* req, int status) {
SslHandshakeWriter* writer = static_cast<SslHandshakeWriter*>(req->data);
if (status != 0) {
writer->connection_->notify_error("Write error '" +
std::string(UV_ERRSTR(status, writer->connection_->loop_)) +
"'");
}
delete writer;
}
} // namespace cass
| 33.53559 | 106 | 0.666529 | spolitov |
eca05a55acf935e9d42224eff0b73ef73fe19066 | 41,398 | cpp | C++ | dev/TreeView/ViewModel.cpp | riverar/microsoft-ui-xaml | ef3a0fcd85d200c98514e765eea94323b943cf1e | [
"MIT"
] | 3,788 | 2019-05-07T02:41:36.000Z | 2022-03-30T12:34:15.000Z | dev/TreeView/ViewModel.cpp | riverar/microsoft-ui-xaml | ef3a0fcd85d200c98514e765eea94323b943cf1e | [
"MIT"
] | 6,170 | 2019-05-06T21:32:43.000Z | 2022-03-31T23:46:55.000Z | dev/TreeView/ViewModel.cpp | riverar/microsoft-ui-xaml | ef3a0fcd85d200c98514e765eea94323b943cf1e | [
"MIT"
] | 532 | 2019-05-07T12:15:58.000Z | 2022-03-31T11:36:26.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include "ViewModel.h"
#include "TreeView.h"
#include "TreeViewItem.h"
#include "VectorChangedEventArgs.h"
#include "TreeViewList.h"
#include <HashMap.h>
// Need to update node selection states on UI before vector changes.
// Listen on vector change events don't solve the problem because the event already happened when the event handler gets called.
// i.e. the node is already gone when we get to ItemRemoved callback.
#pragma region SelectedTreeNodeVector
typedef typename VectorOptionsFromFlag<winrt::TreeViewNode, MakeVectorParam<VectorFlag::Observable, VectorFlag::DependencyObjectBase>()> SelectedTreeNodeVectorOptions;
class SelectedTreeNodeVector :
public ReferenceTracker<
SelectedTreeNodeVector,
reference_tracker_implements_t<typename SelectedTreeNodeVectorOptions::VectorType>::type,
typename TreeViewNodeVectorOptions::IterableType,
typename TreeViewNodeVectorOptions::ObservableVectorType>,
public TreeViewNodeVectorOptions::IVectorOwner
{
Implement_Vector_Read(SelectedTreeNodeVectorOptions)
private:
winrt::weak_ref<ViewModel> m_viewModel{ nullptr };
void UpdateSelection(winrt::TreeViewNode const& node, TreeNodeSelectionState state)
{
if (winrt::get_self<TreeViewNode>(node)->SelectionState() != state)
{
if (auto viewModel = m_viewModel.get())
{
viewModel->UpdateSelection(node, state);
viewModel->NotifyContainerOfSelectionChange(node, state);
}
}
}
public:
void SetViewModel(ViewModel& viewModel)
{
m_viewModel = viewModel.get_weak();
}
void Append(winrt::TreeViewNode const& node)
{
InsertAt(Size(), node);
}
void InsertAt(unsigned int index, winrt::TreeViewNode const& node)
{
if (!Contains(node))
{
// UpdateSelection will call InsertAtCore
UpdateSelection(node, TreeNodeSelectionState::Selected);
}
}
void SetAt(unsigned int index, winrt::TreeViewNode const& node)
{
RemoveAt(index);
InsertAt(index, node);
}
void RemoveAt(unsigned int index)
{
auto inner = GetVectorInnerImpl();
auto oldNode = winrt::get_self<TreeViewNode>(inner->GetAt(index));
// UpdateSelection will call RemoveAtCore
UpdateSelection(*oldNode, TreeNodeSelectionState::UnSelected);
}
void RemoveAtEnd()
{
RemoveAt(Size() - 1);
}
void ReplaceAll(winrt::array_view<winrt::TreeViewNode const> nodes)
{
Clear();
for (auto const& node : nodes)
{
Append(node);
}
}
void Clear()
{
while (Size() > 0)
{
RemoveAtEnd();
}
}
bool Contains(winrt::TreeViewNode const& node)
{
uint32_t index;
return GetVectorInnerImpl()->IndexOf(node, index);
}
// Default write methods will trigger TreeView visual updates.
// If you want to update vector content without notifying TreeViewNodes, use "core" version of the methods.
void InsertAtCore(unsigned int index, winrt::TreeViewNode const& node)
{
GetVectorInnerImpl()->InsertAt(index, node);
// Keep SelectedItems and SelectedNodes in sync
if (auto viewModel = m_viewModel.get())
{
auto selectedItems = viewModel->GetSelectedItems();
if (selectedItems.Size() != Size())
{
if (auto listControl = viewModel->ListControl())
{
if (auto item = winrt::get_self<TreeViewList>(listControl)->ItemFromNode(node))
{
selectedItems.InsertAt(index, item);
viewModel->TrackItemSelected(item);
}
}
}
}
}
void RemoveAtCore(unsigned int index)
{
GetVectorInnerImpl()->RemoveAt(index);
// Keep SelectedItems and SelectedNodes in sync
if (auto viewModel = m_viewModel.get())
{
auto selectedItems = viewModel->GetSelectedItems();
if (selectedItems.Size() != Size())
{
const auto item = selectedItems.GetAt(index);
selectedItems.RemoveAt(index);
viewModel->TrackItemUnselected(item);
}
}
}
};
#pragma endregion
// Similar to SelectedNodesVector above, we need to make decisions before the item is inserted or removed.
// we can't use vector change events because the event already happened when event hander gets called.
#pragma region SelectedItemsVector
typedef typename VectorOptionsFromFlag<winrt::IInspectable, MakeVectorParam<VectorFlag::Observable, VectorFlag::DependencyObjectBase>()> SelectedItemsVectorOptions;
class SelectedItemsVector :
public ReferenceTracker<
SelectedItemsVector,
reference_tracker_implements_t<typename SelectedItemsVectorOptions::VectorType>::type,
typename SelectedItemsVectorOptions::IterableType,
typename SelectedItemsVectorOptions::ObservableVectorType>,
public SelectedItemsVectorOptions::IVectorOwner
{
Implement_Vector_Read(SelectedItemsVectorOptions)
private:
winrt::weak_ref<ViewModel> m_viewModel{ nullptr };
public:
void SetViewModel(ViewModel& viewModel)
{
m_viewModel = viewModel.get_weak();
}
void Append(winrt::IInspectable const& item)
{
InsertAt(Size(), item);
}
void InsertAt(unsigned int index, winrt::IInspectable const& item)
{
if (!Contains(item))
{
GetVectorInnerImpl()->InsertAt(index, item);
// Keep SelectedNodes and SelectedItems in sync
if (auto viewModel = m_viewModel.get())
{
auto selectedNodes = viewModel->GetSelectedNodes();
if (selectedNodes.Size() != Size())
{
if (auto listControl = viewModel->ListControl())
{
if (auto node = winrt::get_self<TreeViewList>(listControl)->NodeFromItem(item))
{
selectedNodes.InsertAt(index, node);
}
}
}
}
}
}
void SetAt(unsigned int index, winrt::IInspectable const& item)
{
RemoveAt(index);
InsertAt(index, item);
}
void RemoveAt(unsigned int index)
{
GetVectorInnerImpl()->RemoveAt(index);
// Keep SelectedNodes and SelectedItems in sync
if (auto viewModel = m_viewModel.get())
{
auto selectedNodes = viewModel->GetSelectedNodes();
if (Size() != selectedNodes.Size())
{
selectedNodes.RemoveAt(index);
}
}
}
void RemoveAtEnd()
{
RemoveAt(Size() - 1);
}
void ReplaceAll(winrt::array_view<winrt::IInspectable const> items)
{
Clear();
for (auto const& node : items)
{
Append(node);
}
}
void Clear()
{
while (Size() > 0)
{
RemoveAtEnd();
}
}
bool Contains(winrt::IInspectable const& item)
{
uint32_t index;
return GetVectorInnerImpl()->IndexOf(item, index);
}
};
#pragma endregion
ViewModel::ViewModel()
{
auto selectedNodes = winrt::make_self<SelectedTreeNodeVector>();
selectedNodes->SetViewModel(*this);
m_selectedNodes.set(*selectedNodes);
auto selectedItems = winrt::make_self<SelectedItemsVector>();
selectedItems->SetViewModel(*this);
m_selectedItems.set(*selectedItems);
m_itemToNodeMap.set(winrt::make<HashMap<winrt::IInspectable, winrt::TreeViewNode>>());
}
ViewModel::~ViewModel()
{
if (m_rootNodeChildrenChangedEventToken.value != 0)
{
if (auto origin = m_originNode.safe_get())
{
winrt::get_self<TreeViewNode>(origin)->ChildrenChanged(m_rootNodeChildrenChangedEventToken);
}
ClearEventTokenVectors();
}
}
void ViewModel::ExpandNode(const winrt::TreeViewNode& value)
{
value.IsExpanded(true);
}
void ViewModel::CollapseNode(const winrt::TreeViewNode& value)
{
value.IsExpanded(false);
}
winrt::event_token ViewModel::NodeExpanding(const winrt::TypedEventHandler<winrt::TreeViewNode, winrt::IInspectable>& handler)
{
return m_nodeExpandingEventSource.add(handler);
}
void ViewModel::NodeExpanding(const winrt::event_token token)
{
m_nodeExpandingEventSource.remove(token);
}
winrt::event_token ViewModel::NodeCollapsed(const winrt::TypedEventHandler<winrt::TreeViewNode, winrt::IInspectable>& handler)
{
return m_nodeCollapsedEventSource.add(handler);
}
void ViewModel::NodeCollapsed(const winrt::event_token token)
{
m_nodeCollapsedEventSource.remove(token);
}
void ViewModel::SelectAll()
{
auto trackSelection = gsl::finally([this]() { EndSelectionChanges(); });
BeginSelectionChanges();
UpdateSelection(m_originNode.get(), TreeNodeSelectionState::Selected);
}
void ViewModel::SelectSingleItem(winrt::IInspectable const& item)
{
auto trackSelection = gsl::finally([this]() { EndSelectionChanges(); });
BeginSelectionChanges();
auto selectedItems = GetSelectedItems();
if (selectedItems.Size() > 0)
{
selectedItems.Clear();
}
if (item)
{
selectedItems.Append(item);
}
}
void ViewModel::SelectNode(const winrt::TreeViewNode& node, bool isSelected)
{
auto trackSelection = gsl::finally([this]() { EndSelectionChanges(); });
BeginSelectionChanges();
auto selectedNodes = GetSelectedNodes();
if (isSelected)
{
if (IsInSingleSelectionMode() && selectedNodes.Size() > 0)
{
selectedNodes.Clear();
}
selectedNodes.Append(node);
}
else
{
unsigned int index;
if (selectedNodes.IndexOf(node, index))
{
selectedNodes.RemoveAt(index);
}
}
}
void ViewModel::SelectByIndex(int index, TreeNodeSelectionState const& state)
{
auto trackSelection = gsl::finally([this]() { EndSelectionChanges(); });
BeginSelectionChanges();
auto targetNode = GetNodeAt(index);
UpdateSelection(targetNode, state);
}
void ViewModel::BeginSelectionChanges()
{
if (!IsInSingleSelectionMode())
{
m_selectionTrackingCounter++;
if (m_selectionTrackingCounter == 1) {
m_addedSelectedItems.clear();
m_removedSelectedItems.clear();
}
}
}
void ViewModel::EndSelectionChanges()
{
if (!IsInSingleSelectionMode())
{
m_selectionTrackingCounter--;
if (m_selectionTrackingCounter == 0 && (m_addedSelectedItems.size() > 0 || m_removedSelectedItems.size() > 0)) {
auto treeView = winrt::get_self<TreeView>(m_TreeView.get());
auto added = winrt::make<Vector<winrt::IInspectable>>();
for (unsigned int i = 0; i < m_addedSelectedItems.size(); i++)
{
added.Append(m_addedSelectedItems.at(i).get());
}
auto removed = winrt::make<Vector<winrt::IInspectable>>();
for (unsigned int i = 0; i < m_removedSelectedItems.size(); i++)
{
removed.Append(m_removedSelectedItems.at(i));
}
treeView->RaiseSelectionChanged(added, removed);
}
}
}
uint32_t ViewModel::Size()
{
auto inner = GetVectorInnerImpl();
return inner->Size();
}
winrt::IInspectable ViewModel::GetAt(uint32_t index)
{
winrt::TreeViewNode node = GetNodeAt(index);
return IsContentMode() ? node.Content() : node;
}
bool ViewModel::IndexOf(winrt::IInspectable const& value, uint32_t& index)
{
if (auto indexOfFunction = GetCustomIndexOfFunction())
{
return indexOfFunction(value, index);
}
else
{
auto inner = GetVectorInnerImpl();
return inner->IndexOf(value, index);
}
}
uint32_t ViewModel::GetMany(uint32_t const startIndex, winrt::array_view<winrt::IInspectable> values)
{
auto inner = GetVectorInnerImpl();
if (IsContentMode())
{
auto vector = winrt::make<Vector<winrt::IInspectable>>();
const int size = Size();
for (int i = 0; i < size; i++)
{
vector.Append(GetNodeAt(i).Content());
}
return vector.GetMany(startIndex, values);
}
return inner->GetMany(startIndex, values);
}
winrt::IVectorView<winrt::IInspectable> ViewModel::GetView()
{
throw winrt::hresult_not_implemented();
}
winrt::TreeViewNode ViewModel::GetNodeAt(uint32_t index)
{
auto inner = GetVectorInnerImpl();
return inner->GetAt(index).as<winrt::TreeViewNode>();
}
void ViewModel::SetAt(uint32_t index, winrt::IInspectable const& value)
{
auto inner = GetVectorInnerImpl();
auto current = inner->GetAt(index).as<winrt::TreeViewNode>();
inner->SetAt(index, value);
winrt::TreeViewNode newNode = value.as<winrt::TreeViewNode>();
auto tvnCurrent = winrt::get_self<TreeViewNode>(current);
tvnCurrent->ChildrenChanged(m_collectionChangedEventTokenVector[index]);
tvnCurrent->RemoveExpandedChanged(m_IsExpandedChangedEventTokenVector[index]);
// Hook up events and replace tokens
auto tvnNewNode = winrt::get_self<TreeViewNode>(newNode);
m_collectionChangedEventTokenVector[index] = tvnNewNode->ChildrenChanged({ this, &ViewModel::TreeViewNodeVectorChanged });
m_IsExpandedChangedEventTokenVector[index] = tvnNewNode->AddExpandedChanged({ this, &ViewModel::TreeViewNodePropertyChanged });
}
void ViewModel::InsertAt(uint32_t index, winrt::IInspectable const& value)
{
GetVectorInnerImpl()->InsertAt(index, value);
winrt::TreeViewNode newNode = value.as<winrt::TreeViewNode>();
// Hook up events and save tokens
auto tvnNewNode = winrt::get_self<TreeViewNode>(newNode);
m_collectionChangedEventTokenVector.insert(m_collectionChangedEventTokenVector.begin() + index, tvnNewNode->ChildrenChanged({ this, &ViewModel::TreeViewNodeVectorChanged }));
m_IsExpandedChangedEventTokenVector.insert(m_IsExpandedChangedEventTokenVector.begin() + index, tvnNewNode->AddExpandedChanged({ this, &ViewModel::TreeViewNodePropertyChanged }));
}
void ViewModel::RemoveAt(uint32_t index)
{
auto inner = GetVectorInnerImpl();
auto current = inner->GetAt(index).as<winrt::TreeViewNode>();
inner->RemoveAt(index);
// Unhook event handlers
auto tvnCurrent = winrt::get_self<TreeViewNode>(current);
tvnCurrent->ChildrenChanged(m_collectionChangedEventTokenVector[index]);
tvnCurrent->RemoveExpandedChanged(m_IsExpandedChangedEventTokenVector[index]);
// Remove tokens from vectors
m_collectionChangedEventTokenVector.erase(m_collectionChangedEventTokenVector.begin() + index);
m_IsExpandedChangedEventTokenVector.erase(m_IsExpandedChangedEventTokenVector.begin() + index);
}
void ViewModel::Append(winrt::IInspectable const& value)
{
GetVectorInnerImpl()->Append(value);
winrt::TreeViewNode newNode = value.as<winrt::TreeViewNode>();
// Hook up events and save tokens
auto tvnNewNode = winrt::get_self<TreeViewNode>(newNode);
m_collectionChangedEventTokenVector.push_back(tvnNewNode->ChildrenChanged({ this, &ViewModel::TreeViewNodeVectorChanged }));
m_IsExpandedChangedEventTokenVector.push_back(tvnNewNode->AddExpandedChanged({ this, &ViewModel::TreeViewNodePropertyChanged }));
}
void ViewModel::RemoveAtEnd()
{
auto inner = GetVectorInnerImpl();
auto current = inner->GetAt(Size() - 1).as<winrt::TreeViewNode>();
inner->RemoveAtEnd();
// Unhook events
auto tvnCurrent = winrt::get_self<TreeViewNode>(current);
tvnCurrent->ChildrenChanged(m_collectionChangedEventTokenVector.back());
tvnCurrent->RemoveExpandedChanged(m_IsExpandedChangedEventTokenVector.back());
// Remove tokens
m_collectionChangedEventTokenVector.pop_back();
m_IsExpandedChangedEventTokenVector.pop_back();
}
void ViewModel::Clear()
{
// Don't call GetVectorInnerImpl()->Clear() directly because we need to remove hooked events
unsigned int count = Size();
while (count != 0)
{
RemoveAtEnd();
count--;
}
}
void ViewModel::ReplaceAll(winrt::array_view<winrt::IInspectable const> items)
{
auto inner = GetVectorInnerImpl();
return inner->ReplaceAll(items);
}
// Helper function
void ViewModel::PrepareView(const winrt::TreeViewNode& originNode)
{
// Remove any existing RootNode events/children
if (auto existingOriginNode = m_originNode.get())
{
for (int i = (existingOriginNode.Children().Size() - 1); i >= 0; i--)
{
auto removeNode = existingOriginNode.Children().GetAt(i).as<winrt::TreeViewNode>();
RemoveNodeAndDescendantsFromView(removeNode);
}
if (m_rootNodeChildrenChangedEventToken.value != 0)
{
existingOriginNode.Children().as<winrt::IObservableVector<winrt::TreeViewNode>>().VectorChanged(m_rootNodeChildrenChangedEventToken);
}
}
// Add new RootNode & children
m_originNode.set(originNode);
m_rootNodeChildrenChangedEventToken = winrt::get_self<TreeViewNode>(originNode)->ChildrenChanged({ this, &ViewModel::TreeViewNodeVectorChanged });
originNode.IsExpanded(true);
int allOpenedDescendantsCount = 0;
for (unsigned int i = 0; i < originNode.Children().Size(); i++)
{
auto addNode = originNode.Children().GetAt(i).as<winrt::TreeViewNode>();
AddNodeToView(addNode, i + allOpenedDescendantsCount);
allOpenedDescendantsCount = AddNodeDescendantsToView(addNode, i, allOpenedDescendantsCount);
}
}
void ViewModel::SetOwners(winrt::TreeViewList const& owningList, winrt::TreeView const& owningTreeView)
{
m_TreeViewList = winrt::make_weak(owningList);
m_TreeView = winrt::make_weak(owningTreeView);
}
winrt::TreeViewList ViewModel::ListControl()
{
return m_TreeViewList.get();
}
bool ViewModel::IsInSingleSelectionMode()
{
return m_TreeViewList.get().SelectionMode() == winrt::ListViewSelectionMode::Single;
}
// Private helpers
void ViewModel::AddNodeToView(const winrt::TreeViewNode& value, unsigned int index)
{
InsertAt(index, value);
}
int ViewModel::AddNodeDescendantsToView(const winrt::TreeViewNode& value, unsigned int index, int offset)
{
if (value.IsExpanded())
{
unsigned int size = value.Children().Size();
for (unsigned int i = 0; i < size; i++)
{
auto childNode = value.Children().GetAt(i).as<winrt::TreeViewNode>();
offset++;
AddNodeToView(childNode, offset + index);
offset = AddNodeDescendantsToView(childNode, index, offset);
}
return offset;
}
return offset;
}
void ViewModel::RemoveNodeAndDescendantsFromView(const winrt::TreeViewNode& value)
{
UINT32 valueIndex;
if (value.IsExpanded())
{
unsigned int size = value.Children().Size();
for (unsigned int i = 0; i < size; i++)
{
auto childNode = value.Children().GetAt(i).as<winrt::TreeViewNode>();
RemoveNodeAndDescendantsFromView(childNode);
}
}
const bool containsValue = IndexOfNode(value, valueIndex);
if (containsValue)
{
RemoveAt(valueIndex);
}
}
void ViewModel::RemoveNodesAndDescendentsWithFlatIndexRange(unsigned int lowIndex, unsigned int highIndex)
{
MUX_ASSERT(lowIndex <= highIndex);
for (int i = static_cast<int>(highIndex); i >= static_cast<int>(lowIndex); i--)
{
RemoveNodeAndDescendantsFromView(GetNodeAt(i));
}
}
int ViewModel::GetNextIndexInFlatTree(const winrt::TreeViewNode& node)
{
unsigned int index = 0;
const bool isNodeInFlatList = IndexOfNode(node, index);
if (isNodeInFlatList)
{
index++;
}
else
{
// node is Root node, so next index in flat tree is 0
index = 0;
}
return index;
}
// When ViewModel receives a event, it only includes the sender(parent TreeViewNode) and index.
// We can't use sender[index] directly because it is already updated/removed
// To find the removed TreeViewNode:
// calculate allOpenedDescendantsCount in sender[0..index-1] first
// then add offset and finally return TreeViewNode by looking up the flat tree.
winrt::TreeViewNode ViewModel::GetRemovedChildTreeViewNodeByIndex(winrt::TreeViewNode const& node, unsigned int childIndex)
{
unsigned int allOpenedDescendantsCount = 0;
for (unsigned int i = 0; i < childIndex; i++)
{
winrt::TreeViewNode calcNode = node.Children().GetAt(i).as<winrt::TreeViewNode>();
if (calcNode.IsExpanded())
{
allOpenedDescendantsCount += GetExpandedDescendantCount(calcNode);
}
}
const unsigned int childIndexInFlatTree = GetNextIndexInFlatTree(node) + childIndex + allOpenedDescendantsCount;
return GetNodeAt(childIndexInFlatTree);
}
int ViewModel::CountDescendants(const winrt::TreeViewNode& value)
{
int descendantCount = 0;
unsigned int size = value.Children().Size();
for (unsigned int i = 0; i < size; i++)
{
auto childNode = value.Children().GetAt(i).as<winrt::TreeViewNode>();
descendantCount++;
if (childNode.IsExpanded())
{
descendantCount = descendantCount + CountDescendants(childNode);
}
}
return descendantCount;
}
unsigned int ViewModel::IndexOfNextSibling(winrt::TreeViewNode const& childNode)
{
auto child = childNode;
auto parentNode = child.Parent();
unsigned int stopIndex;
bool isLastRelativeChild = true;
while (parentNode && isLastRelativeChild)
{
unsigned int relativeIndex;
parentNode.Children().IndexOf(child, relativeIndex);
if (parentNode.Children().Size() - 1 != relativeIndex)
{
isLastRelativeChild = false;
}
else
{
child = parentNode;
parentNode = parentNode.Parent();
}
}
if (parentNode)
{
unsigned int siblingIndex;
parentNode.Children().IndexOf(child, siblingIndex);
auto siblingNode = parentNode.Children().GetAt(siblingIndex + 1);
IndexOfNode(siblingNode, stopIndex);
}
else
{
stopIndex = Size();
}
return stopIndex;
}
unsigned int ViewModel::GetExpandedDescendantCount(winrt::TreeViewNode const& parentNode)
{
unsigned int allOpenedDescendantsCount = 0;
for (unsigned int i = 0; i < parentNode.Children().Size(); i++)
{
auto childNode = parentNode.Children().GetAt(i).as<winrt::TreeViewNode>();
allOpenedDescendantsCount++;
if (childNode.IsExpanded())
{
allOpenedDescendantsCount += CountDescendants(childNode);
}
}
return allOpenedDescendantsCount;
}
bool ViewModel::IsNodeSelected(winrt::TreeViewNode const& targetNode)
{
unsigned int index;
return m_selectedNodes.get().IndexOf(targetNode, index);
}
TreeNodeSelectionState ViewModel::NodeSelectionState(winrt::TreeViewNode const& targetNode)
{
return winrt::get_self<TreeViewNode>(targetNode)->SelectionState();
}
void ViewModel::UpdateNodeSelection(winrt::TreeViewNode const& selectNode, TreeNodeSelectionState const& selectionState)
{
auto node = winrt::get_self<TreeViewNode>(selectNode);
if (selectionState != node->SelectionState())
{
node->SelectionState(selectionState);
auto selectedNodes = winrt::get_self<SelectedTreeNodeVector>(m_selectedNodes.get());
switch (selectionState)
{
case TreeNodeSelectionState::Selected:
selectedNodes->InsertAtCore(selectedNodes->Size(), selectNode);
m_selectedNodeChildrenChangedEventTokenVector.push_back(winrt::get_self<TreeViewNode>(selectNode)->ChildrenChanged({ this, &ViewModel::SelectedNodeChildrenChanged }));
break;
case TreeNodeSelectionState::PartialSelected:
case TreeNodeSelectionState::UnSelected:
unsigned int index;
if (selectedNodes->IndexOf(selectNode, index))
{
selectedNodes->RemoveAtCore(index);
winrt::get_self<TreeViewNode>(selectNode)->ChildrenChanged(m_selectedNodeChildrenChangedEventTokenVector[index]);
m_selectedNodeChildrenChangedEventTokenVector.erase(m_selectedNodeChildrenChangedEventTokenVector.begin() + index);
}
break;
}
}
}
void ViewModel::UpdateSelection(winrt::TreeViewNode const& selectNode, TreeNodeSelectionState const& selectionState)
{
if(NodeSelectionState(selectNode) != selectionState)
{
UpdateNodeSelection(selectNode, selectionState);
if (!IsInSingleSelectionMode())
{
UpdateSelectionStateOfDescendants(selectNode, selectionState);
UpdateSelectionStateOfAncestors(selectNode);
}
}
}
void ViewModel::UpdateSelectionStateOfDescendants(winrt::TreeViewNode const& targetNode, TreeNodeSelectionState const& selectionState)
{
if (selectionState == TreeNodeSelectionState::PartialSelected) return;
for (auto const& childNode : targetNode.Children())
{
UpdateNodeSelection(childNode, selectionState);
UpdateSelectionStateOfDescendants(childNode, selectionState);
NotifyContainerOfSelectionChange(childNode, selectionState);
}
}
void ViewModel::UpdateSelectionStateOfAncestors(winrt::TreeViewNode const& targetNode)
{
if (auto parentNode = targetNode.Parent())
{
// no need to update m_originalNode since it's the logical root for TreeView and not accessible to users
if (parentNode != m_originNode.safe_get())
{
const auto previousState = NodeSelectionState(parentNode);
const auto selectionState = SelectionStateBasedOnChildren(parentNode);
if (previousState != selectionState)
{
UpdateNodeSelection(parentNode, selectionState);
NotifyContainerOfSelectionChange(parentNode, selectionState);
UpdateSelectionStateOfAncestors(parentNode);
}
}
}
}
TreeNodeSelectionState ViewModel::SelectionStateBasedOnChildren(winrt::TreeViewNode const& node)
{
bool hasSelectedChildren{ false };
bool hasUnSelectedChildren{ false };
for (auto const& childNode : node.Children())
{
const auto state = NodeSelectionState(childNode);
if (state == TreeNodeSelectionState::Selected)
{
hasSelectedChildren = true;
}
else if (state == TreeNodeSelectionState::UnSelected)
{
hasUnSelectedChildren = true;
}
if ((hasSelectedChildren && hasUnSelectedChildren) ||
state == TreeNodeSelectionState::PartialSelected)
{
return TreeNodeSelectionState::PartialSelected;
}
}
return hasSelectedChildren ? TreeNodeSelectionState::Selected : TreeNodeSelectionState::UnSelected;
}
void ViewModel::NotifyContainerOfSelectionChange(winrt::TreeViewNode const& targetNode, TreeNodeSelectionState const& selectionState)
{
if (m_TreeViewList)
{
auto container = winrt::get_self<TreeViewList>(m_TreeViewList.get())->ContainerFromNode(targetNode);
if (container)
{
winrt::TreeViewItem targetItem = container.as<winrt::TreeViewItem>();
winrt::get_self<TreeViewItem>(targetItem)->UpdateSelectionVisual(selectionState);
}
}
}
winrt::IVector<winrt::TreeViewNode> ViewModel::GetSelectedNodes()
{
return m_selectedNodes.get();
}
winrt::IVector<winrt::IInspectable> ViewModel::GetSelectedItems()
{
return m_selectedItems.get();
}
void ViewModel::TrackItemSelected(winrt::IInspectable item)
{
if (m_selectionTrackingCounter > 0 && item != m_originNode.safe_get())
{
m_addedSelectedItems.push_back(winrt::make_weak(item));
}
}
void ViewModel::TrackItemUnselected(winrt::IInspectable item)
{
if (m_selectionTrackingCounter > 0 && item != m_originNode.safe_get())
{
m_removedSelectedItems.push_back(item);
}
}
winrt::TreeViewNode ViewModel::GetAssociatedNode(winrt::IInspectable item)
{
return m_itemToNodeMap.get().Lookup(item);
}
bool ViewModel::IndexOfNode(winrt::TreeViewNode const& targetNode, uint32_t& index)
{
return GetVectorInnerImpl()->IndexOf(targetNode, index);
}
void ViewModel::TreeViewNodeVectorChanged(winrt::TreeViewNode const& sender, winrt::IInspectable const& args)
{
winrt::CollectionChange collectionChange = args.as<winrt::IVectorChangedEventArgs>().CollectionChange();
unsigned int index = args.as<winrt::IVectorChangedEventArgs>().Index();
switch (collectionChange)
{
// Reset case, commonly seen when a TreeNode is cleared.
// removes all nodes that need removing then
// toggles a collapse / expand to ensure order.
case (winrt::CollectionChange::Reset):
{
auto resetNode = sender.as<winrt::TreeViewNode>();
if (resetNode.IsExpanded())
{
//The lowIndex is the index of the first child, while the high index is the index of the last descendant in the list.
const unsigned int lowIndex = GetNextIndexInFlatTree(resetNode);
const unsigned int highIndex = IndexOfNextSibling(resetNode) - 1;
RemoveNodesAndDescendentsWithFlatIndexRange(lowIndex, highIndex);
// reset the status of resetNodes children
CollapseNode(resetNode);
ExpandNode(resetNode);
}
break;
}
// We will find the correct index of insertion by first checking if the
// node we are inserting into is expanded. If it is we will start walking
// down the tree and counting the open items. This is to ensure we place
// the inserted item in the correct index. If along the way we bump into
// the item being inserted, we insert there then return, because we don't
// need to do anything further.
case (winrt::CollectionChange::ItemInserted):
{
auto targetNode = sender.as<winrt::TreeViewNode>().Children().GetAt(index).as<winrt::TreeViewNode>();
if (IsContentMode())
{
m_itemToNodeMap.get().Insert(targetNode.Content(), targetNode);
}
auto parentNode = targetNode.Parent();
const unsigned int nextNodeIndex = GetNextIndexInFlatTree(parentNode);
int allOpenedDescendantsCount = 0;
if (parentNode.IsExpanded())
{
for (unsigned int i = 0; i < parentNode.Children().Size(); i++)
{
auto childNode = parentNode.Children().GetAt(i).as<winrt::TreeViewNode>();
if (childNode == targetNode)
{
AddNodeToView(targetNode, nextNodeIndex + i + allOpenedDescendantsCount);
if (targetNode.IsExpanded())
{
AddNodeDescendantsToView(targetNode, nextNodeIndex + i, allOpenedDescendantsCount);
}
}
else if (childNode.IsExpanded())
{
allOpenedDescendantsCount += CountDescendants(childNode);
}
}
}
break;
}
// Removes a node from the ViewModel when a TreeNode
// removes a child.
case (winrt::CollectionChange::ItemRemoved):
{
auto removingNodeParent = sender.as<winrt::TreeViewNode>();
if (removingNodeParent.IsExpanded())
{
auto removedNode = GetRemovedChildTreeViewNodeByIndex(removingNodeParent, index);
RemoveNodeAndDescendantsFromView(removedNode);
if (IsContentMode())
{
m_itemToNodeMap.get().Remove(removedNode.Content());
}
}
break;
}
// Triggered by a replace such as SetAt.
// Updates the TreeNode that changed in the ViewModel.
case (winrt::CollectionChange::ItemChanged):
{
auto targetNode = sender.as<winrt::TreeViewNode>().Children().GetAt(index).as<winrt::TreeViewNode>();
auto changingNodeParent = sender.as<winrt::TreeViewNode>();
if (changingNodeParent.IsExpanded())
{
auto removedNode = GetRemovedChildTreeViewNodeByIndex(changingNodeParent, index);
[[gsl::suppress(con)]]
{
unsigned int removedNodeIndex = 0;
MUX_ASSERT(IndexOfNode(removedNode, removedNodeIndex));
RemoveNodeAndDescendantsFromView(removedNode);
InsertAt(removedNodeIndex, targetNode.as<winrt::IInspectable>());
}
if (IsContentMode())
{
m_itemToNodeMap.get().Remove(removedNode.Content());
m_itemToNodeMap.get().Insert(targetNode.Content(), targetNode);
}
}
break;
}
}
}
void ViewModel::SelectedNodeChildrenChanged(winrt::TreeViewNode const& sender, winrt::IInspectable const& args)
{
winrt::CollectionChange collectionChange = args.as<winrt::IVectorChangedEventArgs>().CollectionChange();
unsigned int index = args.as<winrt::IVectorChangedEventArgs>().Index();
auto changingChildrenNode = sender.as<winrt::TreeViewNode>();
switch (collectionChange)
{
case (winrt::CollectionChange::ItemInserted):
{
auto newNode = changingChildrenNode.Children().GetAt(index);
// If we are in multi select, we want the new child items to be also selected.
if (!IsInSingleSelectionMode())
{
UpdateNodeSelection(newNode, NodeSelectionState(changingChildrenNode));
}
break;
}
case (winrt::CollectionChange::ItemChanged):
{
auto newNode = changingChildrenNode.Children().GetAt(index);
UpdateNodeSelection(newNode, NodeSelectionState(changingChildrenNode));
auto selectedNodes = winrt::get_self<SelectedTreeNodeVector>(m_selectedNodes.get());
for (unsigned int i = 0; i < selectedNodes->Size(); i++)
{
auto selectNode = selectedNodes->GetAt(i);
auto ancestorNode = selectNode.Parent();
while (ancestorNode && ancestorNode.Parent())
{
ancestorNode = ancestorNode.Parent();
}
if (ancestorNode != m_originNode.get())
{
selectedNodes->RemoveAtCore(i);
m_selectedNodeChildrenChangedEventTokenVector.erase(m_selectedNodeChildrenChangedEventTokenVector.begin() + i);
}
}
break;
}
case (winrt::CollectionChange::ItemRemoved):
case (winrt::CollectionChange::Reset):
{
//This checks if there are still children, then re-evaluates parents selection based on current state of remaining children
//If a node has 2 children selected, and 1 unselected, and the unselected is removed, we then change the parent node to selected.
//If the last child is removed, we preserve the current selection state of the parent, and this code need not execute.
if (changingChildrenNode.Children().Size() > 0)
{
auto firstChildNode = changingChildrenNode.Children().GetAt(0);
UpdateSelectionStateOfAncestors(firstChildNode);
}
auto selectedNodes = winrt::get_self<SelectedTreeNodeVector>(m_selectedNodes.get());
for (unsigned int i = 0; i < selectedNodes->Size(); i++)
{
auto selectNode = selectedNodes->GetAt(i);
auto ancestorNode = selectNode.Parent();
while (ancestorNode && ancestorNode.Parent())
{
ancestorNode = ancestorNode.Parent();
}
if (ancestorNode != m_originNode.get())
{
selectedNodes->RemoveAtCore(i);
m_selectedNodeChildrenChangedEventTokenVector.erase(m_selectedNodeChildrenChangedEventTokenVector.begin() + i);
}
}
break;
}
}
}
void ViewModel::TreeViewNodePropertyChanged(winrt::TreeViewNode const& sender, winrt::IDependencyPropertyChangedEventArgs const& args)
{
winrt::IDependencyProperty property = args.Property();
if (property == TreeViewNode::s_IsExpandedProperty)
{
TreeViewNodeIsExpandedPropertyChanged(sender, args);
}
else if (property == TreeViewNode::s_HasChildrenProperty)
{
TreeViewNodeHasChildrenPropertyChanged(sender, args);
}
}
void ViewModel::TreeViewNodeIsExpandedPropertyChanged(winrt::TreeViewNode const& sender, winrt::IDependencyPropertyChangedEventArgs const& args)
{
auto targetNode = sender.as<winrt::TreeViewNode>();
if (targetNode.IsExpanded())
{
if (targetNode.Children().Size() != 0)
{
int openedDescendantOffset = 0;
unsigned int index;
IndexOfNode(targetNode, index);
index = index + 1;
for (unsigned int i = 0; i < targetNode.Children().Size(); i++)
{
winrt::TreeViewNode childNode{ nullptr };
childNode = targetNode.Children().GetAt(i).as<winrt::TreeViewNode>();
AddNodeToView(childNode, index + i + openedDescendantOffset);
openedDescendantOffset = AddNodeDescendantsToView(childNode, index + i, openedDescendantOffset);
}
}
//Notify TreeView that a node is being expanded.
m_nodeExpandingEventSource(targetNode, nullptr);
}
else
{
for (unsigned int i = 0; i < targetNode.Children().Size(); i++)
{
winrt::TreeViewNode childNode{ nullptr };
childNode = targetNode.Children().GetAt(i).as<winrt::TreeViewNode>();
RemoveNodeAndDescendantsFromView(childNode);
}
//Notify TreeView that a node is being collapsed
m_nodeCollapsedEventSource(targetNode, nullptr);
}
}
void ViewModel::TreeViewNodeHasChildrenPropertyChanged(winrt::TreeViewNode const& sender, winrt::IDependencyPropertyChangedEventArgs const& args)
{
if (m_TreeViewList)
{
auto targetNode = sender.as<winrt::TreeViewNode>();
auto container = winrt::get_self<TreeViewList>(m_TreeViewList.get())->ContainerFromNode(targetNode);
if (container)
{
winrt::TreeViewItem targetItem = container.as<winrt::TreeViewItem>();
targetItem.GlyphOpacity(targetNode.HasChildren() ? 1.0 : 0.0);
}
}
}
void ViewModel::IsContentMode(const bool value)
{
m_isContentMode = value;
}
bool ViewModel::IsContentMode()
{
return m_isContentMode;
}
void ViewModel::ClearEventTokenVectors()
{
// Remove ChildrenChanged and ExpandedChanged events
auto inner = GetVectorInnerImpl();
for (uint32_t i =0 ; i < Size(); i++)
{
if (auto current = inner->SafeGetAt(i))
{
auto tvnCurrent = winrt::get_self<TreeViewNode>(current.as<winrt::TreeViewNode>());
tvnCurrent->ChildrenChanged(m_collectionChangedEventTokenVector.at(i));
tvnCurrent->RemoveExpandedChanged(m_IsExpandedChangedEventTokenVector.at(i));
}
}
// Remove SelectedNodeChildrenChangedEvent
if (auto selectedNodes = m_selectedNodes.safe_get())
{
for (uint32_t i = 0; i < selectedNodes.Size(); i++)
{
if (auto current = selectedNodes.GetAt(i))
{
auto node = winrt::get_self<TreeViewNode>(current.as<winrt::TreeViewNode>());
node->ChildrenChanged(m_selectedNodeChildrenChangedEventTokenVector[i]);
}
}
}
// Clear token vectors
m_collectionChangedEventTokenVector.clear();
m_IsExpandedChangedEventTokenVector.clear();
m_selectedNodeChildrenChangedEventTokenVector.clear();
}
| 33.932787 | 184 | 0.638751 | riverar |
eca81fbb773cabc99faaf2b9b23db83ceb9112a7 | 9,122 | hpp | C++ | VS/Spike-Izhikevich-LIB/v1/updateState_serial.hpp | HJLebbink/Spike-Izhi | b8ff31a436f55c0db6132362e8572bf999d699b5 | [
"MIT"
] | null | null | null | VS/Spike-Izhikevich-LIB/v1/updateState_serial.hpp | HJLebbink/Spike-Izhi | b8ff31a436f55c0db6132362e8572bf999d699b5 | [
"MIT"
] | null | null | null | VS/Spike-Izhikevich-LIB/v1/updateState_serial.hpp | HJLebbink/Spike-Izhi | b8ff31a436f55c0db6132362e8572bf999d699b5 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2017 Henk-Jan Lebbink
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <stdio.h> // for printf // stdio functions are used since C++ streams aren't necessarily thread safe
//#include <intrin.h> // needed for compiler intrinsics
#include <array>
#include "../../Spike-Tools-LIB/SpikeSet1Sec.hpp"
#include "../../Spike-Tools-LIB/Constants.hpp"
#include "../../Spike-Izhikevich-LIB/SpikeTypesIzhikevich.hpp"
namespace spike
{
namespace v1
{
static inline int ltpIndex(const int neuronId, const int time, const int N)
{
return (time * N) + neuronId;
}
template <size_t nNeurons>
static inline void updateState_X64_Blitz(float v[], float u[], const float ic[], const float is[], const float a[])
{
for (size_t i = 0; i < nNeurons; ++i)
{
const float tt = 140 - u[i] + (is[i] * ic[i]);
//const float tt = 140 - u[i] + ic[i];
v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability
v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms
u[i] += a[i] * ((0.2f * v[i]) - u[i]);
}
}
template <size_t nNeurons>
static inline void updateState_X64(float v[], float u[], const float ic[], const float is[], const float a[], const float b[])
{
//__debugbreak();
//#pragma loop(hint_parallel(4))
for (size_t i = 0; i < nNeurons; ++i)
{
BOOST_ASSERT_MSG_HJ(!std::isfinite(v[i]), "v[" << i << "] is not finite");
BOOST_ASSERT_MSG_HJ(!std::isfinite(u[i]), "u[" << i << "] is not finite");
//const float tt = 140 - u[i] + (is[i] * ic[i]);
const float tt = 140 - u[i] + ic[i];
v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability
v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms
u[i] += a[i] * ((b[i] * v[i]) - u[i]);
if (u[i] > 50)
{
u[i] = 50;
}
if (v[i] > 100)
{
v[i] = 100;
}
}
}
template <size_t N, size_t D>
static inline void updateStdp_X64(const unsigned int t, float ltd[N], float ltp[N][1001 + D])
{
for (unsigned int i = 0; i < N; ++i)
{
ltd[i] *= 0.95f;
ltp[i][t + D + 1] = 0.95f * ltp[i][t + D];
}
}
template <size_t nNeurons>
static inline void updateState_Sse(float v[], float u[], const float ic[], const float is[], const float a[], const float b[])
{
const __m128 c1 = _mm_set1_ps(0.5f);
const __m128 c2 = _mm_set1_ps(0.04f);
const __m128 c3 = _mm_set1_ps(5.0f);
const __m128 c4 = _mm_set1_ps(140.0f);
for (size_t i = 0; i < nNeurons; i += 4)
{
const __m128 ici = _mm_load_ps(&ic[i]);
//const __m128 isi = _mm_load_ps(&is[i]);
__m128 vi = _mm_load_ps(&v[i]);
__m128 ui = _mm_load_ps(&u[i]);
// + 140 - u[i] + (is[i] * ic[i])
// const __m128 tt = _mm_add_ps(_mm_sub_ps(_mm_mul_ps(isi, ici), ui), c4);
// + 140 - u[i] + ic[i]
const __m128 tt = _mm_add_ps(_mm_sub_ps(ici, ui), c4);
//////////////////////////////////////////
// v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability
const __m128 x1a = _mm_mul_ps(vi, c2);
const __m128 x2a = _mm_add_ps(x1a, c3);
const __m128 x3a = _mm_mul_ps(x2a, vi);
const __m128 x4a = _mm_add_ps(x3a, tt);
const __m128 x5a = _mm_mul_ps(x4a, c1);
vi = _mm_add_ps(x5a, vi);
//////////////////////////////////////////
// v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms
const __m128 x1b = _mm_mul_ps(vi, c2);
const __m128 x2b = _mm_add_ps(x1b, c3);
const __m128 x3b = _mm_mul_ps(x2b, vi);
const __m128 x4b = _mm_add_ps(x3b, tt);
const __m128 x5b = _mm_mul_ps(x4b, c1);
vi = _mm_add_ps(x5b, vi);
//////////////////////////////////////////
// u[i] += a[i] * ((b[i] * v[i]) - u[i]);
const __m128 bi = _mm_load_ps(&b[i]);
const __m128 y1 = _mm_mul_ps(vi, bi);
const __m128 y2 = _mm_sub_ps(y1, ui);
const __m128 ai = _mm_load_ps(&a[i]);
const __m128 y3 = _mm_mul_ps(y2, ai);
ui = _mm_add_ps(y3, ui);
/*
BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[0]), "v[" << i << "][0] = " << vi.m128_f32[0] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[1]), "v[" << i << "][1] = " << vi.m128_f32[1] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[2]), "v[" << i << "][2] = " << vi.m128_f32[2] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[3]), "v[" << i << "][3] = " << vi.m128_f32[3] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[0]), "u[" << i << "][0] = " << ui.m128_f32[0] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[1]), "u[" << i << "][1] = " << ui.m128_f32[1] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[2]), "u[" << i << "][2] = " << ui.m128_f32[2] << " is not finite");
BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[3]), "u[" << i << "][3] = " << ui.m128_f32[3] << " is not finite");
*/
_mm_store_ps(&v[i], vi);
_mm_store_ps(&u[i], ui);
}
}
template <size_t N, Delay D>
static inline void updateStdp_Sse(const unsigned int t, float ltd[N], float ltp[N][1001 + D])
{
for (unsigned int i = 0; i < N; i += 4)
{
// ltd[i] *= 0.95f;
_mm_store_ps(<d[i], _mm_mul_ps(_mm_set1_ps(0.95f), _mm_load_ps(<d[i])));
// ltp[ltpIndex(i, t+D+1)+0] = 0.95f * ltp[ltpIndex(i, t+D)+0];
_mm_store_ps(<p[i][t + D + 1], _mm_mul_ps(_mm_set1_ps(0.95f), _mm_load_ps(<p[i][t + D])));
}
}
template <size_t nNeurons>
static inline void updateState_Avx(float v[], float u[], const float ic[], const float is[], const float a[])
{
for (size_t i = 0; i < nNeurons; i += 8)
{
const __m256 ai = _mm256_load_ps(&a[i]);
const __m256 ici = _mm256_load_ps(&ic[i]);
const __m256 isi = _mm256_load_ps(&is[i]);
__m256 vi = _mm256_load_ps(&v[i]);
__m256 ui = _mm256_load_ps(&u[i]);
const __m256 c1 = _mm256_set1_ps(0.5f);
const __m256 c2 = _mm256_set1_ps(0.04f);
const __m256 c3 = _mm256_set1_ps(5.0f);
const __m256 c4 = _mm256_set1_ps(140.0f);
// + 140 - u[i] + (is[i] * ic[i])
// const __m256 tt = _mm256_add_ps(_mm256_sub_ps(_mm256_mul_ps(isi, ici), ui), c4);
// + 140 - u[i] + ic[i]
const __m256 tt = _mm256_add_ps(_mm256_sub_ps(ici, ui), c4);
//////////////////////////////////////////
// v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + 140 - u[i] + ic[i]); // for numerical stability
const __m256 x1a = _mm256_mul_ps(vi, c2);
const __m256 x2a = _mm256_add_ps(x1a, c3);
const __m256 x3a = _mm256_mul_ps(x2a, vi);
const __m256 x4a = _mm256_add_ps(x3a, tt);
const __m256 x5a = _mm256_mul_ps(x4a, c1);
vi = _mm256_add_ps(x5a, vi);
//////////////////////////////////////////
// v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + 140 - u[i] + ic[i]); // time step is 0.5 ms
const __m256 x1b = _mm256_mul_ps(vi, c2);
const __m256 x2b = _mm256_add_ps(x1b, c3);
const __m256 x3b = _mm256_mul_ps(x2b, vi);
const __m256 x4b = _mm256_add_ps(x3b, tt);
const __m256 x5b = _mm256_mul_ps(x4b, c1);
vi = _mm256_add_ps(x5b, vi);
//////////////////////////////////////////
// u[i] += a[i] * ((0.2f * v[i]) - u[i]);
const __m256 c5 = _mm256_set1_ps(0.2f);
const __m256 y1 = _mm256_mul_ps(vi, c5);
const __m256 y2 = _mm256_sub_ps(y1, ui);
const __m256 y3 = _mm256_mul_ps(y2, ai);
ui = _mm256_add_ps(y3, ui);
_mm256_store_ps(&v[i], vi);
_mm256_store_ps(&u[i], ui);
}
}
template <size_t nNeurons, Delay D>
static inline void updateStdp_Avx(const unsigned int t, float ltd[], float ltp[][1001 + D])
{
for (unsigned int i = 0; i < nNeurons; i += 8)
{
// ltd[i] *= 0.95f;
_mm256_store_ps(<d[i], _mm256_mul_ps(_mm256_set1_ps(0.95f), _mm256_load_ps(<d[i])));
// ltp[ltpIndex(i, t+D+1)+0] = 0.95f * ltp[ltpIndex(i, t+D)+0];
_mm256_store_ps(<p[i][t + D + 1], _mm256_mul_ps(_mm256_set1_ps(0.95f), _mm256_load_ps(<p[i][t + D])));
}
}
}
} | 36.931174 | 128 | 0.580355 | HJLebbink |
ecb2f1f7e91ba6250416afd08b898fecd446b16d | 976 | hpp | C++ | modules/boost/simd/sdk/include/boost/simd/forward/allocator.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 34 | 2017-05-19T18:10:17.000Z | 2022-01-04T02:18:13.000Z | modules/boost/simd/sdk/include/boost/simd/forward/allocator.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/boost/simd/sdk/include/boost/simd/forward/allocator.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 7 | 2017-12-02T12:59:17.000Z | 2021-07-31T12:46:14.000Z | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI
// Copyright 2011 - 2013 MetaScale SAS
//
// 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
//==============================================================================
#ifndef BOOST_SIMD_FORWARD_ALLOCATOR_HPP_INCLUDED
#define BOOST_SIMD_FORWARD_ALLOCATOR_HPP_INCLUDED
#include <boost/simd/preprocessor/parameters.hpp>
#if !defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
template<typename T, std::size_t N = BOOST_SIMD_CONFIG_ALIGNMENT>
struct allocator;
template<typename A, std::size_t N = BOOST_SIMD_CONFIG_ALIGNMENT>
struct allocator_adaptor;
} }
#endif
#endif
| 34.857143 | 80 | 0.589139 | psiha |
ecb5e50f93c23a2ac398624e7e4981e9b03cd969 | 870 | cpp | C++ | 0035 - Search Insert Position/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | 5 | 2018-10-18T06:47:19.000Z | 2020-06-19T09:30:03.000Z | 0035 - Search Insert Position/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | 0035 - Search Insert Position/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | //
// main.cpp
// 35 - Search Insert Position
//
// Created by ynfMac on 2019/6/26.
// Copyright © 2019 ynfMac. All rights reserved.
// 直接一趟循环根据值的大小进行比较 时间复杂度0(n),空间复杂度0(1)
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int> &nums, int target){
int length = nums.size();
if( length == 0 ){ return 0;}
if(target <= nums[0]) {
return 0;
}
for(int i = 1; i < length;i ++) {
if ( target == nums[i] || target > nums[i - 1] && target < nums[i] ) {
return i;
}
}
return length;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
vector<int> a = vector<int>{1,3,5,6};
cout << Solution().searchInsert(a, 5);
std::cout << "Hello, World!\n";
return 0;
}
| 22.307692 | 82 | 0.527586 | xiaoswu |
ecb9f8b871cb80450f3b630bc3e2a179131d0ab7 | 1,358 | cpp | C++ | core_cs/oops/this_pointer.cpp | saurabhraj042/dsaPrep | 0973a03bc565a2850003c7e48d99b97ff83b1d01 | [
"MIT"
] | 23 | 2021-10-30T04:11:52.000Z | 2021-11-27T09:16:18.000Z | core_cs/oops/this_pointer.cpp | Pawanupadhyay10/placement-prep | 0449fa7cbc56e7933e6b090936ab7c15ca5f290f | [
"MIT"
] | null | null | null | core_cs/oops/this_pointer.cpp | Pawanupadhyay10/placement-prep | 0449fa7cbc56e7933e6b090936ab7c15ca5f290f | [
"MIT"
] | 4 | 2021-10-30T03:26:05.000Z | 2021-11-14T12:15:04.000Z | /**
* # 'This' keyword is a OBJECT POINTER present inside the INSTANCE_MEMBER FUNCTION
* block of a CLASS and it stores the ADDRESS of CALLER OBJECT.
*
* # It's value cannot be modified.
*
* # USES :
* -> used to refer current class instance variable / When local variable’s name is same as member’s name
* -> To return reference to the calling object
* -> To pass refrence of itself as an arguement
* */
#include<bits/stdc++.h>
using namespace std;
class Demo {
private :
Demo* caller_ob_ref;
Demo* other_ob_ref;
public :
Demo () {
caller_ob_ref = this;
other_ob_ref = NULL;
}
// Refrencing current object reference
Demo* GetObjRef () {
// this object pointer stores add of caller object
return this;
}
void RecObjRef (Demo* other_ob_ref) {
this->other_ob_ref = other_ob_ref;
}
void ShowValues () {
cout << "Caller Object Add :" << caller_ob_ref << endl;
cout << "Other Object Add :" << other_ob_ref << endl;
}
};
int main () {
Demo objectA;
objectA.ShowValues();
cout << endl;
Demo objectB;
objectA.RecObjRef(&objectB);
objectA.ShowValues();
} | 25.622642 | 114 | 0.550074 | saurabhraj042 |
ecbc4541f6813bc33e67ac719e11c9c07ffaf3d1 | 26,548 | hpp | C++ | include/cppdevtk/base/generic_locking_algorithms.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/generic_locking_algorithms.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/generic_locking_algorithms.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <[email protected]>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <[email protected]>, <[email protected]>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if (!(defined(CPPDEVTK_DETAIL_BUILD) || defined(CPPDEVTK_BASE_MUTEX_HPP_INCLUDED_)))
# error "Do not include directly (non-std file); please include <cppdevtk/base/mutex.hpp> instead!!!"
#endif
#ifndef CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_
#define CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_
#include "config.hpp"
#include "locks.hpp"
#include "lock_exception.hpp"
#include "deadlock_exception.hpp"
#include "cassert.hpp"
namespace cppdevtk {
namespace base {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \defgroup generic_locking_algorithms Generic locking algorithms
/// \sa C++ 11, 30.4.3 Generic locking algorithms
/// @{
template <class TL1, class TL2>
int TryLock(TL1& l1, TL2& l2);
template <class TL1, class TL2, class TL3>
int TryLock(TL1& l1, TL2& l2, TL3& l3);
template <class TL1, class TL2, class TL3, class TL4>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4);
template <class TL1, class TL2, class TL3, class TL4, class TL5>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10);
template <class TL1, class TL2>
void Lock(TL1& l1, TL2& l2);
template <class TL1, class TL2, class TL3>
void Lock(TL1& l1, TL2& l2, TL3& l3);
template <class TL1, class TL2, class TL3, class TL4>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4);
template <class TL1, class TL2, class TL3, class TL4, class TL5>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10);
namespace detail {
template <class TL1, class TL2>
int LockHelper(TL1& l1, TL2& l2);
template <class TL1, class TL2, class TL3>
int LockHelper(TL1& l1, TL2& l2, TL3& l3);
template <class TL1, class TL2, class TL3, class TL4>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4);
template <class TL1, class TL2, class TL3, class TL4, class TL5>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9);
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10);
} // namespace detail
/// @} // generic_locking_algorithms
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline functions / template definitions.
template <class TL1, class TL2>
inline int TryLock(TL1& l1, TL2& l2) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
if (l2.TryLock()) {
uniqueLock.Release();
return -1;
}
return 1;
}
return 0;
}
template <class TL1, class TL2, class TL3>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5, l6);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) {
UniqueLock<TL1> uniqueLock(l1, tryToLock);
if (uniqueLock.OwnsLock()) {
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9, l10);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
return 0;
}
template <class TL1, class TL2>
void Lock(TL1& l1, TL2& l2) {
const int kNumLockables = 2;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3>
void Lock(TL1& l1, TL2& l2, TL3& l3) {
const int kNumLockables = 3;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4) {
const int kNumLockables = 4;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) {
const int kNumLockables = 5;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) {
const int kNumLockables = 6;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l6, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l6, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l6, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
case 5:
lockableIdx = detail::LockHelper(l6, l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 5) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) {
const int kNumLockables = 7;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l6, l7, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l6, l7, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
case 5:
lockableIdx = detail::LockHelper(l6, l7, l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 5) % kNumLockables;
break;
case 6:
lockableIdx = detail::LockHelper(l7, l1, l2, l3, l4, l5, l6);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 6) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) {
const int kNumLockables = 8;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l6, l7, l8, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
case 5:
lockableIdx = detail::LockHelper(l6, l7, l8, l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 5) % kNumLockables;
break;
case 6:
lockableIdx = detail::LockHelper(l7, l8, l1, l2, l3, l4, l5, l6);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 6) % kNumLockables;
break;
case 7:
lockableIdx = detail::LockHelper(l8, l1, l2, l3, l4, l5, l6, l7);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 7) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) {
const int kNumLockables = 9;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8, l9);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l9, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l9, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l9, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l6, l7, l8, l9, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
case 5:
lockableIdx = detail::LockHelper(l6, l7, l8, l9, l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 5) % kNumLockables;
break;
case 6:
lockableIdx = detail::LockHelper(l7, l8, l9, l1, l2, l3, l4, l5, l6);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 6) % kNumLockables;
break;
case 7:
lockableIdx = detail::LockHelper(l8, l9, l1, l2, l3, l4, l5, l6, l7);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 7) % kNumLockables;
break;
case 8:
lockableIdx = detail::LockHelper(l9, l1, l2, l3, l4, l5, l6, l7, l8);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 8) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) {
const int kNumLockables = 10;
int lockableIdx = 0;
do {
switch (lockableIdx) {
case 0:
lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10);
if (lockableIdx == -1) {
return;
}
break;
case 1:
lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l9, l10, l1);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 1) % kNumLockables;
break;
case 2:
lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l9, l10, l1, l2);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 2) % kNumLockables;
break;
case 3:
lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l9, l10, l1, l2, l3);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 3) % kNumLockables;
break;
case 4:
lockableIdx = detail::LockHelper(l5, l6, l7, l8, l9, l10, l1, l2, l3, l4);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 4) % kNumLockables;
break;
case 5:
lockableIdx = detail::LockHelper(l6, l7, l8, l9, l10, l1, l2, l3, l4, l5);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 5) % kNumLockables;
break;
case 6:
lockableIdx = detail::LockHelper(l7, l8, l9, l10, l1, l2, l3, l4, l5, l6);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 6) % kNumLockables;
break;
case 7:
lockableIdx = detail::LockHelper(l8, l9, l10, l1, l2, l3, l4, l5, l6, l7);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 7) % kNumLockables;
break;
case 8:
lockableIdx = detail::LockHelper(l9, l10, l1, l2, l3, l4, l5, l6, l7, l8);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 8) % kNumLockables;
break;
case 9:
lockableIdx = detail::LockHelper(l10, l1, l2, l3, l4, l5, l6, l7, l8, l9);
if (lockableIdx == -1) {
return;
}
lockableIdx = (lockableIdx + 9) % kNumLockables;
break;
default: // silence compiler warning about missing default in switch
CPPDEVTK_ASSERT(0 && "we should never get here");
break;
}
}
while (true);
}
namespace detail {
template <class TL1, class TL2>
inline int LockHelper(TL1& l1, TL2& l2) {
UniqueLock<TL1> uniqueLock(l1);
if (l2.TryLock()) {
uniqueLock.Release();
return -1;
}
return 1;
}
template <class TL1, class TL2, class TL3>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5, l6);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10>
inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) {
UniqueLock<TL1> uniqueLock(l1);
const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9, l10);
if (kIdx == -1) {
uniqueLock.Release();
return kIdx;
}
return (kIdx + 1);
}
} // namespace detail
} // namespace base
} // namespace cppdevtk
#endif // CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_
| 30.065685 | 126 | 0.587314 | CoSoSys |
ecbf9a007dae66655d2b6fc0fd6d6a53cca02466 | 1,700 | hpp | C++ | src/Domain/Mouse.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Mouse.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Mouse.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | #if !defined MOUSE
#define MOUSE
#include "Entity.hpp"
#include "Utils.hpp"
#include "Text.hpp"
#include "Shape.hpp"
struct Mouse : public Entity{
bool must_draw = true;
int must_draw_cooldown = 500;
glm::vec3 color_on_left_click = {0.2f, 1.0f, 0.2f};
glm::vec3 color_on_right_click = {1.0f, 0.0f, 0.5f};
glm::vec3 normal_color = {1.0f, 1.0f, 1.0f};
Mouse(){
this->setNome("Mouse");
this->setColor(this->normal_color);
this->transform.eulerRotation.z = 45.0f;
this->is_movable = true;
}
virtual void draw(){ if (must_draw) Entity::draw(); } // Desenha se puder ser desenhado
virtual void update_position_on_world(int x, int y){
glm::vec4 position_on_world = glm::inverse(parent->transform.modelMatrix)*glm::vec4(x, y, 0.0f, 1.0f);
this->transform.position.x = position_on_world.x;
this->transform.position.y = position_on_world.y;
}
virtual void act(int* keyStatus, GLdouble deltaTime){
must_draw_cooldown -= deltaTime;
if(keyStatus[(int) ('m')] && must_draw_cooldown <= 0){
must_draw_cooldown = 500;
must_draw = !must_draw;
std::string message = must_draw ? "Mouse is showing" : "Mouse is not showing";
#if defined TEST
//std::cout << message << std::endl;
#endif
Left_Corner_Timed_Minitext::change_left_corner_text(message);
}
if(keyStatus[MOUSE_LEFT_CLICK]) this->setColor(color_on_left_click);
else if(keyStatus[MOUSE_RIGHT_CLICK]) this->setColor(color_on_right_click);
else this->setColor(normal_color);
}
};
#endif | 32.692308 | 110 | 0.620588 | LBBassani |
ecc46f7bed0c0c55b147b2729576b1f90a14a828 | 3,920 | cpp | C++ | src/naive_kinematics.cpp | HiroIshida/tinyfk | d7987521b5e824c1d83c9485e50c2915223bbd6e | [
"MIT"
] | 8 | 2020-11-22T15:37:30.000Z | 2021-11-15T17:10:17.000Z | src/naive_kinematics.cpp | HiroIshida/tinyfk | d7987521b5e824c1d83c9485e50c2915223bbd6e | [
"MIT"
] | 14 | 2020-11-22T16:24:04.000Z | 2022-02-08T03:07:20.000Z | src/naive_kinematics.cpp | HiroIshida/tinyfk | d7987521b5e824c1d83c9485e50c2915223bbd6e | [
"MIT"
] | 1 | 2021-05-28T14:25:30.000Z | 2021-05-28T14:25:30.000Z | /*
Copyright (c) 2020 Hirokazu Ishida
This software is released under the MIT License, see LICENSE.
tinyfk: https://github.com/HiroIshida/tinyfk
*/
// inefficient methods which will be used only in test
#include "tinyfk.hpp"
namespace tinyfk
{
void RobotModel::get_link_point(
unsigned int link_id, urdf::Pose& out_tf_rlink_to_elink, bool basealso) const
{
// h : here , e: endeffector , r: root, p: parent
// e.g. hlink means here_link and rlink means root_link
urdf::LinkSharedPtr hlink = _links[link_id];
urdf::Pose tf_hlink_to_elink; // unit transform by default
while(true){
// transform from parent to child links are computed by combining
// three transforms: tf_here_to_joint, tf_joint_to_joint, tf_joint_to_parent, in order.
const urdf::JointSharedPtr& pjoint = hlink->parent_joint;
if(pjoint == nullptr){
if(basealso){tf_hlink_to_elink = pose_transform(_base_pose._pose, tf_hlink_to_elink);}
break;
}
urdf::Pose tf_plink_to_hlink;
const urdf::Pose& tf_plink_to_pjoint = pjoint->parent_to_joint_origin_transform;
if(pjoint->type==urdf::Joint::FIXED){
tf_plink_to_hlink = tf_plink_to_pjoint;
}else{
double angle = _joint_angles[pjoint->id];
urdf::Pose tf_pjoint_to_hlink = pjoint->transform(angle);
tf_plink_to_hlink = pose_transform(tf_plink_to_pjoint, tf_pjoint_to_hlink);
}
urdf::Pose tf_plink_to_elink = pose_transform(tf_plink_to_hlink, tf_hlink_to_elink);
// update here node
tf_hlink_to_elink = std::move(tf_plink_to_elink);
hlink = hlink->getParent();
}
out_tf_rlink_to_elink = tf_hlink_to_elink;
}
Eigen::MatrixXd RobotModel::get_jacobian_naive(
unsigned int elink_id, const std::vector<unsigned int>& joint_ids, bool rotalso, bool basealso)
{
unsigned int n_pose_dim = (rotalso ? 6 : 3);
unsigned int n_joints = joint_ids.size();
unsigned int n_dof = (basealso ? n_joints + 3 : n_joints);
Eigen::MatrixXd J = Eigen::MatrixXd::Zero(n_pose_dim, n_dof);
double dx = 1e-7;
std::vector<double> q0 = this->get_joint_angles(joint_ids);
urdf::Pose pose0, pose1;
this->get_link_point(elink_id, pose0, basealso);
for(unsigned int i=0; i<n_joints; i++){
int jid = joint_ids[i];
this->set_joint_angle(jid, q0[i] + dx);
this->get_link_point(elink_id, pose1, basealso);
this->set_joint_angle(jid, q0[i]); // must to set to the original
urdf::Vector3& pos0 = pose0.position;
urdf::Vector3& pos1 = pose1.position;
J(0, i) = (pos1.x - pos0.x)/dx;
J(1, i) = (pos1.y - pos0.y)/dx;
J(2, i) = (pos1.z - pos0.z)/dx;
if(rotalso){
urdf::Vector3&& rpy0 = pose0.rotation.getRPY();
urdf::Vector3&& rpy1 = pose1.rotation.getRPY();
urdf::Vector3 rpy_diff = rpy1 - rpy0;
J(3, i) = rpy_diff.x/dx;
J(4, i) = rpy_diff.y/dx;
J(5, i) = rpy_diff.z/dx;
}
}
if(basealso){
for(unsigned int i=0; i<3; i++){
std::array<double, 3>& tmp = _base_pose._pose3d;
tmp[i] += dx;
this->set_base_pose(tmp[0], tmp[1], tmp[2]);
this->get_link_point(elink_id, pose1, true);
tmp[i] -= dx;
this->set_base_pose(tmp[0], tmp[1], tmp[2]);
urdf::Vector3& pos0 = pose0.position;
urdf::Vector3& pos1 = pose1.position;
J(0, n_joints+i) = (pos1.x - pos0.x)/dx;
J(1, n_joints+i) = (pos1.y - pos0.y)/dx;
J(2, n_joints+i) = (pos1.z - pos0.z)/dx;
if(rotalso){
urdf::Vector3&& rpy0 = pose0.rotation.getRPY();
urdf::Vector3&& rpy1 = pose1.rotation.getRPY();
urdf::Vector3 rpy_diff = rpy1 - rpy0;
J(3, n_joints+i) = rpy_diff.x/dx;
J(4, n_joints+i) = rpy_diff.y/dx;
J(5, n_joints+i) = rpy_diff.z/dx;
}
}
}
return J;
}
}
| 34.086957 | 102 | 0.625 | HiroIshida |
ecc48c623a40429df44e238a6e077e7bdb028112 | 1,488 | cpp | C++ | src/ConfigManager.cpp | razerx100/Sol | c9d7da09207aada805be277a9cc2ab2d0f9d4e02 | [
"MIT"
] | null | null | null | src/ConfigManager.cpp | razerx100/Sol | c9d7da09207aada805be277a9cc2ab2d0f9d4e02 | [
"MIT"
] | null | null | null | src/ConfigManager.cpp | razerx100/Sol | c9d7da09207aada805be277a9cc2ab2d0f9d4e02 | [
"MIT"
] | null | null | null | #include <ConfigManager.hpp>
void ConfigManager::ReplaceInString(
const std::string& replacement, std::string& textStr,
std::int64_t start, std::int64_t end
) noexcept {
textStr.replace(start, end - start, replacement);
}
std::string ConfigManager::GetLineFromString(
const std::string& textString,
std::int64_t start, std::int64_t end
) noexcept {
std::string foundLine;
foundLine = std::string(textString.begin() + start, textString.begin() + end);
return foundLine;
}
std::pair<std::int64_t, std::int64_t> ConfigManager::FindInString(
const std::string& textStr, const std::string& searchItem
) noexcept {
auto start = std::search(
textStr.begin(), textStr.end(), searchItem.begin(), searchItem.end()
);
std::string::const_iterator end;
if (start != textStr.end())
end = std::find(start, textStr.end(), '\n');
std::int64_t startPos = -1;
std::int64_t endPos = -1;
if (start != textStr.end() && end != textStr.end()) {
startPos = std::distance(textStr.begin(), start);
endPos = std::distance(textStr.begin(), end) + 1;
}
return { startPos, endPos };
}
std::string ConfigManager::FileToString(const char* fileName) noexcept {
std::ifstream input(fileName, std::ios_base::in);
std::string buffer;
std::string str;
while (std::getline(input, buffer))
str.append(buffer + "\n"s);
return str;
}
| 28.075472 | 83 | 0.625 | razerx100 |
ecc4b1a6ad94cb9b786721e829c217728a5e6fea | 73,612 | hpp | C++ | high_level_controller/examples/cpp/central_routing/include/lane_graph_one_lane/lane_graph.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 9 | 2020-06-24T11:22:15.000Z | 2022-01-13T14:14:13.000Z | high_level_controller/examples/cpp/central_routing/include/lane_graph_one_lane/lane_graph.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 1 | 2021-05-10T13:48:04.000Z | 2021-05-10T13:48:04.000Z | high_level_controller/examples/cpp/central_routing/include/lane_graph_one_lane/lane_graph.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 2 | 2021-11-08T11:59:29.000Z | 2022-03-15T13:50:54.000Z | #pragma once
// Generated by map_print/map_print2/lane_graph_to_cpp.m
// Do not edit
#include <vector>
/**
* \defgroup lane_graph_one_lane Lane Graph With One Lane
* \ingroup central_routing
* TODO
*/
/**
* \struct LaneGraph
* \brief TODO
* \ingroup lane_graph_one_lane
*/
struct LaneGraph {
//! TODO
const size_t n_nodes = 44;
//! TODO
const std::vector<double> nodes_x = std::vector<double>{2.2500e+00,3.1500e+00,3.8074e+00,4.2103e+00,4.2450e+00,4.0623e+00,3.8242e+00,3.0500e+00,2.4750e+00,2.6065e+00,3.1425e+00,2.2500e+00,2.4750e+00,2.0250e+00,3.0500e+00,1.3500e+00,6.9264e-01,2.8966e-01,2.5500e-01,6.7576e-01,4.3775e-01,1.4500e+00,1.8935e+00,1.3575e+00,2.0250e+00,1.4500e+00,3.1500e+00,2.2500e+00,3.8074e+00,4.2103e+00,3.8242e+00,4.0623e+00,2.6065e+00,2.4750e+00,3.1425e+00,2.2500e+00,2.0250e+00,1.3500e+00,6.9264e-01,2.8966e-01,4.3775e-01,6.7576e-01,1.8935e+00,1.3575e+00,};
//! TODO
const std::vector<double> nodes_y = std::vector<double>{3.7450e+00,3.7390e+00,3.5902e+00,2.9310e+00,2.0000e+00,2.9071e+00,2.3258e+00,2.2250e+00,2.8000e+00,3.4081e+00,3.5892e+00,2.2250e+00,2.0000e+00,2.8000e+00,1.7750e+00,3.7390e+00,3.5902e+00,2.9310e+00,2.0000e+00,2.3258e+00,2.9071e+00,2.2250e+00,3.4081e+00,3.5892e+00,2.0000e+00,1.7750e+00,2.6100e-01,2.5500e-01,4.0979e-01,1.0690e+00,1.6742e+00,1.0929e+00,5.9189e-01,1.2000e+00,4.1081e-01,1.7750e+00,1.2000e+00,2.6100e-01,4.0979e-01,1.0690e+00,1.0929e+00,1.6742e+00,5.9189e-01,4.1081e-01,};
//! TODO
const std::vector<double> nodes_cos = std::vector<double>{1.0000e+00,9.9875e-01,8.7677e-01,1.5918e-01,0.0000e+00,1.5925e-01,-8.7962e-01,-1.0000e+00,-4.0327e-05,6.1691e-01,9.9874e-01,-1.0000e+00,0.0000e+00,-4.0327e-05,1.0000e+00,9.9875e-01,8.7677e-01,1.5918e-01,0.0000e+00,-8.7962e-01,1.5925e-01,-1.0000e+00,6.1691e-01,9.9874e-01,0.0000e+00,1.0000e+00,-9.9875e-01,-1.0000e+00,-8.7677e-01,-1.5918e-01,8.7962e-01,-1.5925e-01,-6.1691e-01,4.0327e-05,-9.9874e-01,1.0000e+00,4.0327e-05,-9.9875e-01,-8.7677e-01,-1.5918e-01,-1.5925e-01,8.7962e-01,-6.1691e-01,-9.9874e-01,};
//! TODO
const std::vector<double> nodes_sin = std::vector<double>{0.0000e+00,-5.0058e-02,-4.8090e-01,-9.8725e-01,-1.0000e+00,-9.8724e-01,-4.7568e-01,3.4305e-05,1.0000e+00,7.8703e-01,-5.0169e-02,0.0000e+00,1.0000e+00,-1.0000e+00,3.4305e-05,5.0058e-02,4.8090e-01,9.8725e-01,1.0000e+00,4.7568e-01,9.8724e-01,-3.4305e-05,-7.8703e-01,5.0169e-02,-1.0000e+00,-3.4305e-05,-5.0058e-02,0.0000e+00,-4.8090e-01,-9.8725e-01,-4.7568e-01,-9.8724e-01,7.8703e-01,1.0000e+00,-5.0169e-02,0.0000e+00,-1.0000e+00,5.0058e-02,4.8090e-01,9.8725e-01,9.8724e-01,4.7568e-01,-7.8703e-01,5.0169e-02,};
//! TODO
const size_t n_edges = 56;
//! TODO
const size_t n_edge_path_nodes = 25;
//! TODO
const std::vector<size_t> edges_start_index = std::vector<size_t>{0,1,2,3,5,6,8,9,7,7,12,13,10,2,15,16,17,18,19,21,22,23,11,13,13,25,16,20,26,28,29,4,30,14,32,34,35,33,33,7,28,31,27,37,38,39,40,41,36,42,25,25,24,33,43,38,};
//! TODO
const std::vector<size_t> edges_end_index = std::vector<size_t>{1,2,3,4,6,7,9,10,11,8,8,14,2,5,0,15,16,17,20,19,13,22,21,21,24,8,23,16,27,26,28,29,31,30,33,32,14,14,12,36,34,28,37,38,39,18,41,25,42,43,35,36,36,21,38,40,};
//! TODO
const std::vector<std::vector<double>> edges_x = std::vector<std::vector<double>>
{
std::vector<double>{2.2500e+00,2.2874e+00,2.3249e+00,2.3627e+00,2.4001e+00,2.4376e+00,2.4750e+00,2.5125e+00,2.5499e+00,2.5877e+00,2.6252e+00,2.6626e+00,2.7001e+00,2.7375e+00,2.7749e+00,2.8127e+00,2.8502e+00,2.8876e+00,2.9251e+00,2.9625e+00,3.0000e+00,3.0378e+00,3.0752e+00,3.1126e+00,3.1500e+00,},
std::vector<double>{3.1500e+00,3.1781e+00,3.2066e+00,3.2347e+00,3.2632e+00,3.2912e+00,3.3196e+00,3.3476e+00,3.3755e+00,3.4038e+00,3.4316e+00,3.4597e+00,3.4874e+00,3.5150e+00,3.5428e+00,3.5701e+00,3.5977e+00,3.6247e+00,3.6518e+00,3.6784e+00,3.7047e+00,3.7311e+00,3.7568e+00,3.7824e+00,3.8074e+00,},
std::vector<double>{3.8074e+00,3.8398e+00,3.8716e+00,3.9020e+00,3.9312e+00,3.9590e+00,3.9834e+00,4.0049e+00,4.0252e+00,4.0443e+00,4.0624e+00,4.0792e+00,4.0948e+00,4.1094e+00,4.1231e+00,4.1356e+00,4.1472e+00,4.1578e+00,4.1677e+00,4.1766e+00,4.1847e+00,4.1921e+00,4.1989e+00,4.2049e+00,4.2103e+00,},
std::vector<double>{4.2103e+00,4.2161e+00,4.2212e+00,4.2255e+00,4.2292e+00,4.2324e+00,4.2350e+00,4.2372e+00,4.2391e+00,4.2405e+00,4.2417e+00,4.2426e+00,4.2434e+00,4.2439e+00,4.2443e+00,4.2446e+00,4.2448e+00,4.2449e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,},
std::vector<double>{4.0623e+00,4.0671e+00,4.0710e+00,4.0738e+00,4.0755e+00,4.0760e+00,4.0752e+00,4.0730e+00,4.0695e+00,4.0646e+00,4.0582e+00,4.0503e+00,4.0410e+00,4.0302e+00,4.0180e+00,4.0044e+00,3.9895e+00,3.9731e+00,3.9555e+00,3.9365e+00,3.9162e+00,3.8948e+00,3.8724e+00,3.8488e+00,3.8242e+00,},
std::vector<double>{3.8242e+00,3.7987e+00,3.7723e+00,3.7448e+00,3.7167e+00,3.6879e+00,3.6584e+00,3.6282e+00,3.5975e+00,3.5658e+00,3.5340e+00,3.5017e+00,3.4689e+00,3.4357e+00,3.4020e+00,3.3677e+00,3.3334e+00,3.2988e+00,3.2639e+00,3.2287e+00,3.1933e+00,3.1574e+00,3.1217e+00,3.0859e+00,3.0500e+00,},
std::vector<double>{2.4750e+00,2.4750e+00,2.4751e+00,2.4753e+00,2.4758e+00,2.4765e+00,2.4776e+00,2.4790e+00,2.4809e+00,2.4834e+00,2.4864e+00,2.4900e+00,2.4943e+00,2.4993e+00,2.5050e+00,2.5114e+00,2.5187e+00,2.5267e+00,2.5356e+00,2.5453e+00,2.5559e+00,2.5673e+00,2.5795e+00,2.5926e+00,2.6065e+00,},
std::vector<double>{2.6065e+00,2.6212e+00,2.6367e+00,2.6532e+00,2.6702e+00,2.6880e+00,2.7066e+00,2.7258e+00,2.7457e+00,2.7664e+00,2.7876e+00,2.8094e+00,2.8317e+00,2.8546e+00,2.8781e+00,2.9023e+00,2.9268e+00,2.9518e+00,2.9773e+00,3.0034e+00,3.0300e+00,3.0574e+00,3.0851e+00,3.1135e+00,3.1425e+00,},
std::vector<double>{3.0500e+00,3.0167e+00,2.9833e+00,2.9500e+00,2.9167e+00,2.8834e+00,2.8500e+00,2.8167e+00,2.7834e+00,2.7499e+00,2.7167e+00,2.6834e+00,2.6499e+00,2.6166e+00,2.5833e+00,2.5501e+00,2.5166e+00,2.4833e+00,2.4500e+00,2.4166e+00,2.3833e+00,2.3500e+00,2.3167e+00,2.2833e+00,2.2500e+00,},
std::vector<double>{3.0500e+00,3.0012e+00,2.9543e+00,2.9097e+00,2.8670e+00,2.8263e+00,2.7873e+00,2.7504e+00,2.7155e+00,2.6826e+00,2.6520e+00,2.6237e+00,2.5976e+00,2.5741e+00,2.5532e+00,2.5349e+00,2.5191e+00,2.5060e+00,2.4955e+00,2.4875e+00,2.4817e+00,2.4780e+00,2.4759e+00,2.4751e+00,2.4750e+00,},
std::vector<double>{2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,},
std::vector<double>{2.0250e+00,2.0251e+00,2.0261e+00,2.0289e+00,2.0345e+00,2.0440e+00,2.0584e+00,2.0784e+00,2.1049e+00,2.1383e+00,2.1787e+00,2.2258e+00,2.2796e+00,2.3388e+00,2.4025e+00,2.4698e+00,2.5397e+00,2.6102e+00,2.6805e+00,2.7498e+00,2.8167e+00,2.8806e+00,2.9411e+00,2.9978e+00,3.0500e+00,},
std::vector<double>{3.1425e+00,3.1708e+00,3.1992e+00,3.2275e+00,3.2558e+00,3.2840e+00,3.3123e+00,3.3402e+00,3.3681e+00,3.3959e+00,3.4234e+00,3.4509e+00,3.4786e+00,3.5063e+00,3.5341e+00,3.5622e+00,3.5905e+00,3.6188e+00,3.6471e+00,3.6752e+00,3.7029e+00,3.7300e+00,3.7564e+00,3.7823e+00,3.8074e+00,},
std::vector<double>{3.8074e+00,3.8350e+00,3.8618e+00,3.8871e+00,3.9107e+00,3.9323e+00,3.9516e+00,3.9684e+00,3.9827e+00,3.9945e+00,4.0040e+00,4.0115e+00,4.0172e+00,4.0215e+00,4.0249e+00,4.0275e+00,4.0299e+00,4.0323e+00,4.0351e+00,4.0383e+00,4.0421e+00,4.0466e+00,4.0516e+00,4.0570e+00,4.0623e+00,},
std::vector<double>{1.3500e+00,1.3874e+00,1.4248e+00,1.4626e+00,1.5000e+00,1.5375e+00,1.5749e+00,1.6124e+00,1.6498e+00,1.6876e+00,1.7251e+00,1.7625e+00,1.7999e+00,1.8374e+00,1.8748e+00,1.9126e+00,1.9501e+00,1.9875e+00,2.0250e+00,2.0624e+00,2.0999e+00,2.1377e+00,2.1751e+00,2.2126e+00,2.2500e+00,},
std::vector<double>{6.9264e-01,7.1756e-01,7.4321e-01,7.6891e-01,7.9527e-01,8.2160e-01,8.4851e-01,8.7532e-01,9.0233e-01,9.2985e-01,9.5719e-01,9.8500e-01,1.0126e+00,1.0403e+00,1.0684e+00,1.0962e+00,1.1245e+00,1.1524e+00,1.1808e+00,1.2088e+00,1.2368e+00,1.2653e+00,1.2934e+00,1.3219e+00,1.3500e+00,},
std::vector<double>{2.8966e-01,2.9508e-01,3.0117e-01,3.0786e-01,3.1525e-01,3.2339e-01,3.3240e-01,3.4216e-01,3.5281e-01,3.6437e-01,3.7703e-01,3.9057e-01,4.0517e-01,4.2084e-01,4.3779e-01,4.5573e-01,4.7482e-01,4.9510e-01,5.1677e-01,5.4098e-01,5.6883e-01,5.9804e-01,6.2874e-01,6.6023e-01,6.9264e-01,},
std::vector<double>{2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5501e-01,2.5505e-01,2.5511e-01,2.5523e-01,2.5542e-01,2.5570e-01,2.5609e-01,2.5663e-01,2.5735e-01,2.5829e-01,2.5947e-01,2.6095e-01,2.6277e-01,2.6499e-01,2.6763e-01,2.7080e-01,2.7452e-01,2.7887e-01,2.8387e-01,2.8966e-01,},
std::vector<double>{6.7576e-01,6.5119e-01,6.2764e-01,6.0517e-01,5.8362e-01,5.6346e-01,5.4453e-01,5.2687e-01,5.1054e-01,4.9556e-01,4.8197e-01,4.6979e-01,4.5895e-01,4.4967e-01,4.4183e-01,4.3545e-01,4.3049e-01,4.2696e-01,4.2480e-01,4.2399e-01,4.2448e-01,4.2618e-01,4.2903e-01,4.3293e-01,4.3775e-01,},
std::vector<double>{1.4500e+00,1.4141e+00,1.3783e+00,1.3422e+00,1.3067e+00,1.2713e+00,1.2361e+00,1.2012e+00,1.1666e+00,1.1319e+00,1.0980e+00,1.0643e+00,1.0311e+00,9.9834e-01,9.6600e-01,9.3385e-01,9.0254e-01,8.7178e-01,8.4163e-01,8.1213e-01,7.8331e-01,7.5497e-01,7.2770e-01,7.0128e-01,6.7576e-01,},
std::vector<double>{1.8935e+00,1.9074e+00,1.9205e+00,1.9327e+00,1.9442e+00,1.9547e+00,1.9644e+00,1.9733e+00,1.9813e+00,1.9886e+00,1.9950e+00,2.0007e+00,2.0057e+00,2.0100e+00,2.0136e+00,2.0166e+00,2.0191e+00,2.0210e+00,2.0224e+00,2.0235e+00,2.0242e+00,2.0247e+00,2.0249e+00,2.0250e+00,2.0250e+00,},
std::vector<double>{1.3575e+00,1.3865e+00,1.4149e+00,1.4429e+00,1.4700e+00,1.4966e+00,1.5227e+00,1.5482e+00,1.5732e+00,1.5980e+00,1.6219e+00,1.6454e+00,1.6683e+00,1.6906e+00,1.7124e+00,1.7338e+00,1.7543e+00,1.7742e+00,1.7934e+00,1.8120e+00,1.8298e+00,1.8470e+00,1.8633e+00,1.8788e+00,1.8935e+00,},
std::vector<double>{2.2500e+00,2.2167e+00,2.1833e+00,2.1500e+00,2.1167e+00,2.0834e+00,2.0500e+00,2.0167e+00,1.9834e+00,1.9499e+00,1.9167e+00,1.8834e+00,1.8499e+00,1.8166e+00,1.7833e+00,1.7501e+00,1.7166e+00,1.6833e+00,1.6500e+00,1.6166e+00,1.5833e+00,1.5500e+00,1.5167e+00,1.4833e+00,1.4500e+00,},
std::vector<double>{2.0250e+00,2.0249e+00,2.0241e+00,2.0220e+00,2.0183e+00,2.0125e+00,2.0045e+00,1.9940e+00,1.9809e+00,1.9651e+00,1.9468e+00,1.9259e+00,1.9023e+00,1.8763e+00,1.8480e+00,1.8174e+00,1.7845e+00,1.7496e+00,1.7127e+00,1.6737e+00,1.6330e+00,1.5903e+00,1.5457e+00,1.4988e+00,1.4500e+00,},
std::vector<double>{2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,},
std::vector<double>{1.4500e+00,1.5022e+00,1.5589e+00,1.6194e+00,1.6833e+00,1.7502e+00,1.8195e+00,1.8898e+00,1.9603e+00,2.0302e+00,2.0975e+00,2.1612e+00,2.2207e+00,2.2742e+00,2.3213e+00,2.3617e+00,2.3951e+00,2.4216e+00,2.4416e+00,2.4560e+00,2.4655e+00,2.4711e+00,2.4739e+00,2.4749e+00,2.4750e+00,},
std::vector<double>{6.9264e-01,7.1772e-01,7.4356e-01,7.7000e-01,7.9711e-01,8.2477e-01,8.5295e-01,8.8120e-01,9.0949e-01,9.3783e-01,9.6586e-01,9.9370e-01,1.0215e+00,1.0491e+00,1.0766e+00,1.1041e+00,1.1319e+00,1.1598e+00,1.1877e+00,1.2160e+00,1.2442e+00,1.2725e+00,1.3008e+00,1.3292e+00,1.3575e+00,},
std::vector<double>{4.3775e-01,4.4302e-01,4.4837e-01,4.5338e-01,4.5785e-01,4.6170e-01,4.6494e-01,4.6766e-01,4.7008e-01,4.7247e-01,4.7514e-01,4.7845e-01,4.8280e-01,4.8851e-01,4.9596e-01,5.0547e-01,5.1733e-01,5.3160e-01,5.4838e-01,5.6772e-01,5.8928e-01,6.1287e-01,6.3819e-01,6.6499e-01,6.9264e-01,},
std::vector<double>{3.1500e+00,3.1126e+00,3.0752e+00,3.0374e+00,3.0000e+00,2.9625e+00,2.9251e+00,2.8876e+00,2.8502e+00,2.8124e+00,2.7749e+00,2.7375e+00,2.7001e+00,2.6626e+00,2.6252e+00,2.5874e+00,2.5499e+00,2.5125e+00,2.4750e+00,2.4376e+00,2.4001e+00,2.3623e+00,2.3249e+00,2.2874e+00,2.2500e+00,},
std::vector<double>{3.8074e+00,3.7824e+00,3.7568e+00,3.7311e+00,3.7047e+00,3.6784e+00,3.6515e+00,3.6247e+00,3.5977e+00,3.5701e+00,3.5428e+00,3.5150e+00,3.4874e+00,3.4597e+00,3.4316e+00,3.4038e+00,3.3755e+00,3.3476e+00,3.3192e+00,3.2912e+00,3.2632e+00,3.2347e+00,3.2066e+00,3.1781e+00,3.1500e+00,},
std::vector<double>{4.2103e+00,4.2049e+00,4.1988e+00,4.1921e+00,4.1847e+00,4.1766e+00,4.1676e+00,4.1578e+00,4.1472e+00,4.1356e+00,4.1230e+00,4.1094e+00,4.0948e+00,4.0792e+00,4.0622e+00,4.0443e+00,4.0252e+00,4.0049e+00,3.9832e+00,3.9590e+00,3.9312e+00,3.9020e+00,3.8713e+00,3.8398e+00,3.8074e+00,},
std::vector<double>{4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2449e+00,4.2448e+00,4.2446e+00,4.2443e+00,4.2439e+00,4.2434e+00,4.2426e+00,4.2417e+00,4.2405e+00,4.2391e+00,4.2372e+00,4.2350e+00,4.2324e+00,4.2292e+00,4.2255e+00,4.2211e+00,4.2161e+00,4.2103e+00,},
std::vector<double>{3.8242e+00,3.8488e+00,3.8724e+00,3.8948e+00,3.9164e+00,3.9365e+00,3.9555e+00,3.9731e+00,3.9895e+00,4.0044e+00,4.0180e+00,4.0302e+00,4.0411e+00,4.0503e+00,4.0582e+00,4.0646e+00,4.0695e+00,4.0730e+00,4.0752e+00,4.0760e+00,4.0755e+00,4.0738e+00,4.0710e+00,4.0671e+00,4.0623e+00,},
std::vector<double>{3.0500e+00,3.0859e+00,3.1217e+00,3.1578e+00,3.1933e+00,3.2287e+00,3.2639e+00,3.2988e+00,3.3334e+00,3.3681e+00,3.4020e+00,3.4357e+00,3.4689e+00,3.5017e+00,3.5340e+00,3.5661e+00,3.5975e+00,3.6282e+00,3.6584e+00,3.6879e+00,3.7167e+00,3.7450e+00,3.7723e+00,3.7987e+00,3.8242e+00,},
std::vector<double>{2.6065e+00,2.5926e+00,2.5795e+00,2.5673e+00,2.5558e+00,2.5453e+00,2.5356e+00,2.5267e+00,2.5187e+00,2.5114e+00,2.5050e+00,2.4993e+00,2.4943e+00,2.4900e+00,2.4864e+00,2.4834e+00,2.4809e+00,2.4790e+00,2.4776e+00,2.4765e+00,2.4758e+00,2.4753e+00,2.4751e+00,2.4750e+00,2.4750e+00,},
std::vector<double>{3.1425e+00,3.1135e+00,3.0851e+00,3.0571e+00,3.0300e+00,3.0034e+00,2.9773e+00,2.9518e+00,2.9268e+00,2.9020e+00,2.8781e+00,2.8546e+00,2.8317e+00,2.8094e+00,2.7876e+00,2.7662e+00,2.7457e+00,2.7258e+00,2.7066e+00,2.6880e+00,2.6702e+00,2.6530e+00,2.6367e+00,2.6212e+00,2.6065e+00,},
std::vector<double>{2.2500e+00,2.2833e+00,2.3167e+00,2.3500e+00,2.3833e+00,2.4166e+00,2.4500e+00,2.4833e+00,2.5166e+00,2.5501e+00,2.5833e+00,2.6166e+00,2.6501e+00,2.6834e+00,2.7167e+00,2.7499e+00,2.7834e+00,2.8167e+00,2.8500e+00,2.8834e+00,2.9167e+00,2.9500e+00,2.9833e+00,3.0167e+00,3.0500e+00,},
std::vector<double>{2.4750e+00,2.4751e+00,2.4759e+00,2.4780e+00,2.4817e+00,2.4875e+00,2.4955e+00,2.5060e+00,2.5191e+00,2.5349e+00,2.5532e+00,2.5741e+00,2.5977e+00,2.6237e+00,2.6520e+00,2.6826e+00,2.7155e+00,2.7504e+00,2.7873e+00,2.8263e+00,2.8670e+00,2.9097e+00,2.9543e+00,3.0012e+00,3.0500e+00,},
std::vector<double>{2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,},
std::vector<double>{3.0500e+00,2.9978e+00,2.9411e+00,2.8806e+00,2.8167e+00,2.7498e+00,2.6805e+00,2.6102e+00,2.5397e+00,2.4698e+00,2.4025e+00,2.3388e+00,2.2793e+00,2.2258e+00,2.1787e+00,2.1383e+00,2.1049e+00,2.0784e+00,2.0584e+00,2.0440e+00,2.0345e+00,2.0289e+00,2.0261e+00,2.0251e+00,2.0250e+00,},
std::vector<double>{3.8074e+00,3.7823e+00,3.7564e+00,3.7300e+00,3.7029e+00,3.6752e+00,3.6471e+00,3.6188e+00,3.5905e+00,3.5622e+00,3.5341e+00,3.5063e+00,3.4785e+00,3.4509e+00,3.4234e+00,3.3959e+00,3.3681e+00,3.3402e+00,3.3123e+00,3.2840e+00,3.2558e+00,3.2275e+00,3.1992e+00,3.1708e+00,3.1425e+00,},
std::vector<double>{4.0623e+00,4.0570e+00,4.0516e+00,4.0466e+00,4.0421e+00,4.0383e+00,4.0351e+00,4.0323e+00,4.0299e+00,4.0275e+00,4.0249e+00,4.0215e+00,4.0172e+00,4.0115e+00,4.0040e+00,3.9945e+00,3.9827e+00,3.9684e+00,3.9516e+00,3.9323e+00,3.9107e+00,3.8871e+00,3.8618e+00,3.8350e+00,3.8074e+00,},
std::vector<double>{2.2500e+00,2.2126e+00,2.1751e+00,2.1373e+00,2.0999e+00,2.0624e+00,2.0250e+00,1.9875e+00,1.9501e+00,1.9123e+00,1.8748e+00,1.8374e+00,1.7999e+00,1.7625e+00,1.7251e+00,1.6873e+00,1.6498e+00,1.6124e+00,1.5749e+00,1.5375e+00,1.5000e+00,1.4622e+00,1.4248e+00,1.3874e+00,1.3500e+00,},
std::vector<double>{1.3500e+00,1.3219e+00,1.2934e+00,1.2653e+00,1.2368e+00,1.2088e+00,1.1804e+00,1.1524e+00,1.1245e+00,1.0962e+00,1.0684e+00,1.0403e+00,1.0126e+00,9.8500e-01,9.5719e-01,9.2985e-01,9.0233e-01,8.7532e-01,8.4818e-01,8.2160e-01,7.9527e-01,7.6891e-01,7.4321e-01,7.1756e-01,6.9264e-01,},
std::vector<double>{6.9264e-01,6.6023e-01,6.2845e-01,5.9804e-01,5.6883e-01,5.4098e-01,5.1656e-01,4.9510e-01,4.7482e-01,4.5573e-01,4.3763e-01,4.2084e-01,4.0517e-01,3.9057e-01,3.7690e-01,3.6437e-01,3.5281e-01,3.4216e-01,3.3231e-01,3.2339e-01,3.1525e-01,3.0786e-01,3.0111e-01,2.9508e-01,2.8966e-01,},
std::vector<double>{2.8966e-01,2.8387e-01,2.7883e-01,2.7452e-01,2.7080e-01,2.6763e-01,2.6497e-01,2.6277e-01,2.6095e-01,2.5947e-01,2.5828e-01,2.5735e-01,2.5663e-01,2.5609e-01,2.5569e-01,2.5542e-01,2.5523e-01,2.5511e-01,2.5504e-01,2.5501e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,},
std::vector<double>{4.3775e-01,4.3293e-01,4.2903e-01,4.2618e-01,4.2447e-01,4.2399e-01,4.2480e-01,4.2696e-01,4.3049e-01,4.3545e-01,4.4183e-01,4.4967e-01,4.5905e-01,4.6979e-01,4.8197e-01,4.9556e-01,5.1054e-01,5.2687e-01,5.4453e-01,5.6346e-01,5.8382e-01,6.0517e-01,6.2764e-01,6.5119e-01,6.7576e-01,},
std::vector<double>{6.7576e-01,7.0128e-01,7.2770e-01,7.5524e-01,7.8331e-01,8.1213e-01,8.4163e-01,8.7178e-01,9.0254e-01,9.3416e-01,9.6600e-01,9.9834e-01,1.0311e+00,1.0643e+00,1.0980e+00,1.1323e+00,1.1666e+00,1.2012e+00,1.2361e+00,1.2713e+00,1.3067e+00,1.3426e+00,1.3783e+00,1.4141e+00,1.4500e+00,},
std::vector<double>{2.0250e+00,2.0250e+00,2.0249e+00,2.0247e+00,2.0242e+00,2.0235e+00,2.0224e+00,2.0210e+00,2.0191e+00,2.0166e+00,2.0136e+00,2.0100e+00,2.0057e+00,2.0007e+00,1.9950e+00,1.9886e+00,1.9813e+00,1.9733e+00,1.9644e+00,1.9547e+00,1.9441e+00,1.9327e+00,1.9205e+00,1.9074e+00,1.8935e+00,},
std::vector<double>{1.8935e+00,1.8788e+00,1.8633e+00,1.8468e+00,1.8298e+00,1.8120e+00,1.7934e+00,1.7742e+00,1.7543e+00,1.7336e+00,1.7124e+00,1.6906e+00,1.6683e+00,1.6454e+00,1.6219e+00,1.5977e+00,1.5732e+00,1.5482e+00,1.5227e+00,1.4966e+00,1.4700e+00,1.4426e+00,1.4149e+00,1.3865e+00,1.3575e+00,},
std::vector<double>{1.4500e+00,1.4833e+00,1.5167e+00,1.5500e+00,1.5833e+00,1.6166e+00,1.6500e+00,1.6833e+00,1.7166e+00,1.7501e+00,1.7833e+00,1.8166e+00,1.8501e+00,1.8834e+00,1.9167e+00,1.9499e+00,1.9834e+00,2.0167e+00,2.0500e+00,2.0834e+00,2.1167e+00,2.1500e+00,2.1833e+00,2.2167e+00,2.2500e+00,},
std::vector<double>{1.4500e+00,1.4988e+00,1.5457e+00,1.5903e+00,1.6330e+00,1.6737e+00,1.7127e+00,1.7496e+00,1.7845e+00,1.8174e+00,1.8480e+00,1.8763e+00,1.9024e+00,1.9259e+00,1.9468e+00,1.9651e+00,1.9809e+00,1.9940e+00,2.0045e+00,2.0125e+00,2.0183e+00,2.0220e+00,2.0241e+00,2.0249e+00,2.0250e+00,},
std::vector<double>{2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,},
std::vector<double>{2.4750e+00,2.4749e+00,2.4739e+00,2.4711e+00,2.4655e+00,2.4560e+00,2.4416e+00,2.4216e+00,2.3951e+00,2.3617e+00,2.3213e+00,2.2742e+00,2.2204e+00,2.1612e+00,2.0975e+00,2.0302e+00,1.9603e+00,1.8898e+00,1.8195e+00,1.7502e+00,1.6833e+00,1.6194e+00,1.5589e+00,1.5022e+00,1.4500e+00,},
std::vector<double>{1.3575e+00,1.3292e+00,1.3008e+00,1.2725e+00,1.2442e+00,1.2160e+00,1.1877e+00,1.1598e+00,1.1319e+00,1.1041e+00,1.0766e+00,1.0491e+00,1.0214e+00,9.9370e-01,9.6586e-01,9.3783e-01,9.0949e-01,8.8120e-01,8.5295e-01,8.2477e-01,7.9711e-01,7.7000e-01,7.4356e-01,7.1772e-01,6.9264e-01,},
std::vector<double>{6.9264e-01,6.6499e-01,6.3819e-01,6.1287e-01,5.8928e-01,5.6772e-01,5.4838e-01,5.3160e-01,5.1733e-01,5.0547e-01,4.9596e-01,4.8851e-01,4.8277e-01,4.7845e-01,4.7514e-01,4.7247e-01,4.7008e-01,4.6766e-01,4.6494e-01,4.6170e-01,4.5785e-01,4.5338e-01,4.4837e-01,4.4302e-01,4.3775e-01,},
};
//! TODO
const std::vector<std::vector<double>> edges_y = std::vector<std::vector<double>>
{
std::vector<double>{3.7450e+00,3.7450e+00,3.7450e+00,3.7450e+00,3.7451e+00,3.7451e+00,3.7452e+00,3.7453e+00,3.7454e+00,3.7455e+00,3.7456e+00,3.7457e+00,3.7458e+00,3.7459e+00,3.7459e+00,3.7459e+00,3.7457e+00,3.7455e+00,3.7452e+00,3.7447e+00,3.7441e+00,3.7432e+00,3.7421e+00,3.7407e+00,3.7390e+00,},
std::vector<double>{3.7390e+00,3.7375e+00,3.7357e+00,3.7337e+00,3.7315e+00,3.7289e+00,3.7260e+00,3.7228e+00,3.7193e+00,3.7153e+00,3.7110e+00,3.7061e+00,3.7009e+00,3.6951e+00,3.6888e+00,3.6819e+00,3.6744e+00,3.6664e+00,3.6576e+00,3.6483e+00,3.6383e+00,3.6274e+00,3.6158e+00,3.6033e+00,3.5902e+00,},
std::vector<double>{3.5902e+00,3.5715e+00,3.5510e+00,3.5292e+00,3.5057e+00,3.4807e+00,3.4561e+00,3.4321e+00,3.4072e+00,3.3812e+00,3.3543e+00,3.3268e+00,3.2987e+00,3.2700e+00,3.2405e+00,3.2109e+00,3.1808e+00,3.1505e+00,3.1195e+00,3.0886e+00,3.0574e+00,3.0261e+00,2.9943e+00,2.9627e+00,2.9310e+00,},
std::vector<double>{2.9310e+00,2.8925e+00,2.8539e+00,2.8155e+00,2.7767e+00,2.7379e+00,2.6991e+00,2.6605e+00,2.6216e+00,2.5827e+00,2.5438e+00,2.5052e+00,2.4663e+00,2.4273e+00,2.3884e+00,2.3498e+00,2.3108e+00,2.2719e+00,2.2330e+00,2.1944e+00,2.1554e+00,2.1165e+00,2.0776e+00,2.0389e+00,2.0000e+00,},
std::vector<double>{2.9071e+00,2.8750e+00,2.8436e+00,2.8128e+00,2.7824e+00,2.7528e+00,2.7238e+00,2.6954e+00,2.6675e+00,2.6402e+00,2.6135e+00,2.5875e+00,2.5619e+00,2.5373e+00,2.5134e+00,2.4904e+00,2.4682e+00,2.4469e+00,2.4265e+00,2.4072e+00,2.3886e+00,2.3713e+00,2.3551e+00,2.3399e+00,2.3258e+00,},
std::vector<double>{2.3258e+00,2.3128e+00,2.3009e+00,2.2899e+00,2.2801e+00,2.2713e+00,2.2635e+00,2.2566e+00,2.2505e+00,2.2453e+00,2.2409e+00,2.2372e+00,2.2342e+00,2.2317e+00,2.2297e+00,2.2282e+00,2.2271e+00,2.2263e+00,2.2257e+00,2.2254e+00,2.2252e+00,2.2251e+00,2.2250e+00,2.2250e+00,2.2250e+00,},
std::vector<double>{2.8000e+00,2.8304e+00,2.8604e+00,2.8900e+00,2.9196e+00,2.9485e+00,2.9770e+00,3.0051e+00,3.0328e+00,3.0601e+00,3.0870e+00,3.1134e+00,3.1397e+00,3.1652e+00,3.1902e+00,3.2148e+00,3.2388e+00,3.2622e+00,3.2850e+00,3.3072e+00,3.3290e+00,3.3499e+00,3.3700e+00,3.3895e+00,3.4081e+00,},
std::vector<double>{3.4081e+00,3.4260e+00,3.4430e+00,3.4593e+00,3.4745e+00,3.4889e+00,3.5023e+00,3.5148e+00,3.5263e+00,3.5370e+00,3.5466e+00,3.5552e+00,3.5629e+00,3.5696e+00,3.5753e+00,3.5802e+00,3.5842e+00,3.5873e+00,3.5895e+00,3.5910e+00,3.5918e+00,3.5919e+00,3.5914e+00,3.5905e+00,3.5892e+00,},
std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,},
std::vector<double>{2.2250e+00,2.2251e+00,2.2259e+00,2.2280e+00,2.2317e+00,2.2375e+00,2.2455e+00,2.2560e+00,2.2691e+00,2.2849e+00,2.3032e+00,2.3241e+00,2.3477e+00,2.3737e+00,2.4020e+00,2.4326e+00,2.4655e+00,2.5004e+00,2.5373e+00,2.5763e+00,2.6170e+00,2.6597e+00,2.7043e+00,2.7512e+00,2.8000e+00,},
std::vector<double>{2.0000e+00,2.0333e+00,2.0667e+00,2.1000e+00,2.1333e+00,2.1666e+00,2.2000e+00,2.2333e+00,2.2666e+00,2.3001e+00,2.3333e+00,2.3666e+00,2.4001e+00,2.4334e+00,2.4667e+00,2.4999e+00,2.5334e+00,2.5667e+00,2.6000e+00,2.6334e+00,2.6667e+00,2.7000e+00,2.7333e+00,2.7667e+00,2.8000e+00,},
std::vector<double>{2.8000e+00,2.7478e+00,2.6911e+00,2.6306e+00,2.5667e+00,2.4998e+00,2.4305e+00,2.3602e+00,2.2897e+00,2.2198e+00,2.1525e+00,2.0888e+00,2.0293e+00,1.9758e+00,1.9287e+00,1.8883e+00,1.8549e+00,1.8284e+00,1.8084e+00,1.7940e+00,1.7845e+00,1.7789e+00,1.7761e+00,1.7751e+00,1.7750e+00,},
std::vector<double>{3.5892e+00,3.5878e+00,3.5867e+00,3.5864e+00,3.5871e+00,3.5889e+00,3.5920e+00,3.5962e+00,3.6014e+00,3.6074e+00,3.6138e+00,3.6204e+00,3.6269e+00,3.6328e+00,3.6379e+00,3.6417e+00,3.6441e+00,3.6446e+00,3.6430e+00,3.6393e+00,3.6333e+00,3.6252e+00,3.6152e+00,3.6033e+00,3.5902e+00,},
std::vector<double>{3.5902e+00,3.5742e+00,3.5566e+00,3.5371e+00,3.5156e+00,3.4921e+00,3.4665e+00,3.4393e+00,3.4108e+00,3.3810e+00,3.3505e+00,3.3194e+00,3.2879e+00,3.2562e+00,3.2245e+00,3.1927e+00,3.1607e+00,3.1288e+00,3.0970e+00,3.0651e+00,3.0334e+00,3.0018e+00,2.9702e+00,2.9386e+00,2.9071e+00,},
std::vector<double>{3.7390e+00,3.7407e+00,3.7421e+00,3.7432e+00,3.7441e+00,3.7447e+00,3.7452e+00,3.7455e+00,3.7457e+00,3.7459e+00,3.7459e+00,3.7459e+00,3.7458e+00,3.7457e+00,3.7456e+00,3.7455e+00,3.7454e+00,3.7453e+00,3.7452e+00,3.7451e+00,3.7451e+00,3.7450e+00,3.7450e+00,3.7450e+00,3.7450e+00,},
std::vector<double>{3.5902e+00,3.6033e+00,3.6158e+00,3.6274e+00,3.6383e+00,3.6483e+00,3.6578e+00,3.6664e+00,3.6744e+00,3.6819e+00,3.6888e+00,3.6951e+00,3.7009e+00,3.7061e+00,3.7110e+00,3.7153e+00,3.7193e+00,3.7228e+00,3.7261e+00,3.7289e+00,3.7315e+00,3.7337e+00,3.7357e+00,3.7375e+00,3.7390e+00,},
std::vector<double>{2.9310e+00,2.9627e+00,2.9946e+00,3.0261e+00,3.0574e+00,3.0886e+00,3.1198e+00,3.1505e+00,3.1808e+00,3.2109e+00,3.2408e+00,3.2700e+00,3.2987e+00,3.3268e+00,3.3545e+00,3.3812e+00,3.4072e+00,3.4321e+00,3.4564e+00,3.4807e+00,3.5057e+00,3.5292e+00,3.5512e+00,3.5715e+00,3.5902e+00,},
std::vector<double>{2.0000e+00,2.0389e+00,2.0779e+00,2.1165e+00,2.1554e+00,2.1944e+00,2.2333e+00,2.2719e+00,2.3108e+00,2.3498e+00,2.3887e+00,2.4273e+00,2.4663e+00,2.5052e+00,2.5441e+00,2.5827e+00,2.6216e+00,2.6605e+00,2.6994e+00,2.7379e+00,2.7767e+00,2.8155e+00,2.8542e+00,2.8925e+00,2.9310e+00,},
std::vector<double>{2.3258e+00,2.3399e+00,2.3551e+00,2.3713e+00,2.3888e+00,2.4072e+00,2.4265e+00,2.4469e+00,2.4682e+00,2.4904e+00,2.5134e+00,2.5373e+00,2.5621e+00,2.5875e+00,2.6135e+00,2.6402e+00,2.6675e+00,2.6954e+00,2.7238e+00,2.7528e+00,2.7827e+00,2.8128e+00,2.8436e+00,2.8750e+00,2.9071e+00,},
std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2251e+00,2.2252e+00,2.2254e+00,2.2257e+00,2.2263e+00,2.2271e+00,2.2282e+00,2.2297e+00,2.2317e+00,2.2342e+00,2.2372e+00,2.2409e+00,2.2454e+00,2.2505e+00,2.2566e+00,2.2635e+00,2.2713e+00,2.2801e+00,2.2900e+00,2.3009e+00,2.3128e+00,2.3258e+00,},
std::vector<double>{3.4081e+00,3.3895e+00,3.3700e+00,3.3499e+00,3.3288e+00,3.3072e+00,3.2850e+00,3.2622e+00,3.2388e+00,3.2148e+00,3.1902e+00,3.1652e+00,3.1394e+00,3.1134e+00,3.0870e+00,3.0601e+00,3.0328e+00,3.0051e+00,2.9770e+00,2.9485e+00,2.9193e+00,2.8900e+00,2.8604e+00,2.8304e+00,2.8000e+00,},
std::vector<double>{3.5892e+00,3.5905e+00,3.5914e+00,3.5919e+00,3.5918e+00,3.5910e+00,3.5895e+00,3.5873e+00,3.5842e+00,3.5802e+00,3.5753e+00,3.5696e+00,3.5629e+00,3.5552e+00,3.5466e+00,3.5369e+00,3.5263e+00,3.5148e+00,3.5023e+00,3.4889e+00,3.4745e+00,3.4591e+00,3.4430e+00,3.4260e+00,3.4081e+00,},
std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,},
std::vector<double>{2.8000e+00,2.7512e+00,2.7043e+00,2.6597e+00,2.6170e+00,2.5763e+00,2.5373e+00,2.5004e+00,2.4655e+00,2.4326e+00,2.4020e+00,2.3737e+00,2.3476e+00,2.3241e+00,2.3032e+00,2.2849e+00,2.2691e+00,2.2560e+00,2.2455e+00,2.2375e+00,2.2317e+00,2.2280e+00,2.2259e+00,2.2251e+00,2.2250e+00,},
std::vector<double>{2.8000e+00,2.7667e+00,2.7333e+00,2.7000e+00,2.6667e+00,2.6334e+00,2.6000e+00,2.5667e+00,2.5334e+00,2.4999e+00,2.4667e+00,2.4334e+00,2.3999e+00,2.3666e+00,2.3333e+00,2.3001e+00,2.2666e+00,2.2333e+00,2.2000e+00,2.1666e+00,2.1333e+00,2.1000e+00,2.0667e+00,2.0333e+00,2.0000e+00,},
std::vector<double>{1.7750e+00,1.7751e+00,1.7761e+00,1.7789e+00,1.7845e+00,1.7940e+00,1.8084e+00,1.8284e+00,1.8549e+00,1.8883e+00,1.9287e+00,1.9758e+00,2.0296e+00,2.0888e+00,2.1525e+00,2.2198e+00,2.2897e+00,2.3602e+00,2.4305e+00,2.4998e+00,2.5667e+00,2.6306e+00,2.6911e+00,2.7478e+00,2.8000e+00,},
std::vector<double>{3.5902e+00,3.6033e+00,3.6152e+00,3.6252e+00,3.6333e+00,3.6393e+00,3.6430e+00,3.6446e+00,3.6441e+00,3.6417e+00,3.6379e+00,3.6328e+00,3.6268e+00,3.6204e+00,3.6138e+00,3.6074e+00,3.6014e+00,3.5962e+00,3.5920e+00,3.5889e+00,3.5871e+00,3.5864e+00,3.5867e+00,3.5878e+00,3.5892e+00,},
std::vector<double>{2.9071e+00,2.9386e+00,2.9702e+00,3.0018e+00,3.0334e+00,3.0651e+00,3.0970e+00,3.1288e+00,3.1607e+00,3.1927e+00,3.2245e+00,3.2562e+00,3.2880e+00,3.3194e+00,3.3505e+00,3.3810e+00,3.4108e+00,3.4393e+00,3.4665e+00,3.4921e+00,3.5156e+00,3.5371e+00,3.5566e+00,3.5742e+00,3.5902e+00,},
std::vector<double>{2.6100e-01,2.5929e-01,2.5791e-01,2.5679e-01,2.5593e-01,2.5527e-01,2.5480e-01,2.5447e-01,2.5426e-01,2.5415e-01,2.5412e-01,2.5414e-01,2.5421e-01,2.5430e-01,2.5441e-01,2.5452e-01,2.5463e-01,2.5473e-01,2.5482e-01,2.5489e-01,2.5494e-01,2.5497e-01,2.5499e-01,2.5500e-01,2.5500e-01,},
std::vector<double>{4.0979e-01,3.9666e-01,3.8418e-01,3.7264e-01,3.6173e-01,3.5169e-01,3.4224e-01,3.3357e-01,3.2555e-01,3.1805e-01,3.1123e-01,3.0488e-01,2.9914e-01,2.9388e-01,2.8904e-01,2.8470e-01,2.8071e-01,2.7717e-01,2.7394e-01,2.7109e-01,2.6855e-01,2.6627e-01,2.6428e-01,2.6251e-01,2.6100e-01,},
std::vector<double>{1.0690e+00,1.0373e+00,1.0054e+00,9.7390e-01,9.4258e-01,9.1143e-01,8.8021e-01,8.4954e-01,8.1917e-01,7.8913e-01,7.5920e-01,7.3000e-01,7.0132e-01,6.7320e-01,6.4548e-01,6.1876e-01,5.9285e-01,5.6785e-01,5.4364e-01,5.1929e-01,4.9427e-01,4.7085e-01,4.4881e-01,4.2854e-01,4.0979e-01,},
std::vector<double>{2.0000e+00,1.9611e+00,1.9221e+00,1.8835e+00,1.8446e+00,1.8056e+00,1.7667e+00,1.7281e+00,1.6892e+00,1.6502e+00,1.6113e+00,1.5727e+00,1.5337e+00,1.4948e+00,1.4559e+00,1.4173e+00,1.3784e+00,1.3395e+00,1.3006e+00,1.2621e+00,1.2233e+00,1.1845e+00,1.1458e+00,1.1075e+00,1.0690e+00,},
std::vector<double>{1.6742e+00,1.6601e+00,1.6449e+00,1.6287e+00,1.6112e+00,1.5928e+00,1.5735e+00,1.5531e+00,1.5318e+00,1.5096e+00,1.4866e+00,1.4627e+00,1.4379e+00,1.4125e+00,1.3865e+00,1.3598e+00,1.3325e+00,1.3046e+00,1.2762e+00,1.2472e+00,1.2173e+00,1.1872e+00,1.1564e+00,1.1250e+00,1.0929e+00,},
std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7749e+00,1.7748e+00,1.7746e+00,1.7743e+00,1.7737e+00,1.7729e+00,1.7718e+00,1.7703e+00,1.7683e+00,1.7658e+00,1.7628e+00,1.7591e+00,1.7546e+00,1.7495e+00,1.7434e+00,1.7365e+00,1.7287e+00,1.7199e+00,1.7100e+00,1.6991e+00,1.6872e+00,1.6742e+00,},
std::vector<double>{5.9189e-01,6.1053e-01,6.2995e-01,6.5012e-01,6.7120e-01,6.9276e-01,7.1498e-01,7.3782e-01,7.6125e-01,7.8524e-01,8.0976e-01,8.3480e-01,8.6058e-01,8.8657e-01,9.1302e-01,9.3991e-01,9.6721e-01,9.9492e-01,1.0230e+00,1.0515e+00,1.0807e+00,1.1100e+00,1.1396e+00,1.1696e+00,1.2000e+00,},
std::vector<double>{4.1081e-01,4.0949e-01,4.0855e-01,4.0809e-01,4.0822e-01,4.0899e-01,4.1048e-01,4.1274e-01,4.1583e-01,4.1981e-01,4.2466e-01,4.3043e-01,4.3714e-01,4.4480e-01,4.5342e-01,4.6312e-01,4.7369e-01,4.8522e-01,4.9770e-01,5.1113e-01,5.2548e-01,5.4089e-01,5.5704e-01,5.7405e-01,5.9189e-01,},
std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,},
std::vector<double>{1.2000e+00,1.2488e+00,1.2957e+00,1.3403e+00,1.3830e+00,1.4237e+00,1.4627e+00,1.4996e+00,1.5345e+00,1.5674e+00,1.5980e+00,1.6263e+00,1.6524e+00,1.6759e+00,1.6968e+00,1.7151e+00,1.7309e+00,1.7440e+00,1.7545e+00,1.7625e+00,1.7683e+00,1.7720e+00,1.7741e+00,1.7749e+00,1.7750e+00,},
std::vector<double>{1.2000e+00,1.2333e+00,1.2667e+00,1.3000e+00,1.3333e+00,1.3666e+00,1.4000e+00,1.4333e+00,1.4666e+00,1.5001e+00,1.5333e+00,1.5666e+00,1.6001e+00,1.6334e+00,1.6667e+00,1.6999e+00,1.7334e+00,1.7667e+00,1.8000e+00,1.8334e+00,1.8667e+00,1.9000e+00,1.9333e+00,1.9667e+00,2.0000e+00,},
std::vector<double>{2.2250e+00,2.2249e+00,2.2239e+00,2.2211e+00,2.2155e+00,2.2060e+00,2.1916e+00,2.1716e+00,2.1451e+00,2.1117e+00,2.0713e+00,2.0242e+00,1.9704e+00,1.9112e+00,1.8475e+00,1.7802e+00,1.7103e+00,1.6398e+00,1.5695e+00,1.5002e+00,1.4333e+00,1.3694e+00,1.3089e+00,1.2522e+00,1.2000e+00,},
std::vector<double>{4.0979e-01,3.9669e-01,3.8484e-01,3.7476e-01,3.6666e-01,3.6071e-01,3.5697e-01,3.5544e-01,3.5593e-01,3.5826e-01,3.6212e-01,3.6719e-01,3.7315e-01,3.7960e-01,3.8621e-01,3.9264e-01,3.9861e-01,4.0379e-01,4.0799e-01,4.1108e-01,4.1294e-01,4.1364e-01,4.1331e-01,4.1223e-01,4.1081e-01,},
std::vector<double>{1.0929e+00,1.0614e+00,1.0298e+00,9.9825e-01,9.6663e-01,9.3493e-01,9.0300e-01,8.7118e-01,8.3934e-01,8.0734e-01,7.7552e-01,7.4376e-01,7.1197e-01,6.8055e-01,6.4950e-01,6.1902e-01,5.8922e-01,5.6066e-01,5.3350e-01,5.0791e-01,4.8436e-01,4.6286e-01,4.4341e-01,4.2578e-01,4.0979e-01,},
std::vector<double>{2.5500e-01,2.5500e-01,2.5499e-01,2.5497e-01,2.5494e-01,2.5489e-01,2.5482e-01,2.5473e-01,2.5463e-01,2.5452e-01,2.5441e-01,2.5430e-01,2.5421e-01,2.5414e-01,2.5412e-01,2.5415e-01,2.5426e-01,2.5447e-01,2.5480e-01,2.5527e-01,2.5593e-01,2.5680e-01,2.5791e-01,2.5929e-01,2.6100e-01,},
std::vector<double>{2.6100e-01,2.6251e-01,2.6428e-01,2.6627e-01,2.6855e-01,2.7109e-01,2.7398e-01,2.7717e-01,2.8071e-01,2.8470e-01,2.8904e-01,2.9388e-01,2.9914e-01,3.0488e-01,3.1123e-01,3.1805e-01,3.2555e-01,3.3357e-01,3.4235e-01,3.5169e-01,3.6173e-01,3.7264e-01,3.8418e-01,3.9666e-01,4.0979e-01,},
std::vector<double>{4.0979e-01,4.2854e-01,4.4901e-01,4.7085e-01,4.9427e-01,5.1929e-01,5.4386e-01,5.6785e-01,5.9285e-01,6.1876e-01,6.4574e-01,6.7320e-01,7.0132e-01,7.3000e-01,7.5948e-01,7.8913e-01,8.1917e-01,8.4954e-01,8.8051e-01,9.1143e-01,9.4258e-01,9.7390e-01,1.0057e+00,1.0373e+00,1.0690e+00,},
std::vector<double>{1.0690e+00,1.1075e+00,1.1461e+00,1.1845e+00,1.2233e+00,1.2621e+00,1.3009e+00,1.3395e+00,1.3784e+00,1.4173e+00,1.4562e+00,1.4948e+00,1.5337e+00,1.5727e+00,1.6116e+00,1.6502e+00,1.6892e+00,1.7281e+00,1.7670e+00,1.8056e+00,1.8446e+00,1.8835e+00,1.9224e+00,1.9611e+00,2.0000e+00,},
std::vector<double>{1.0929e+00,1.1250e+00,1.1564e+00,1.1872e+00,1.2176e+00,1.2472e+00,1.2762e+00,1.3046e+00,1.3325e+00,1.3598e+00,1.3865e+00,1.4125e+00,1.4381e+00,1.4627e+00,1.4866e+00,1.5096e+00,1.5318e+00,1.5531e+00,1.5735e+00,1.5928e+00,1.6114e+00,1.6287e+00,1.6449e+00,1.6601e+00,1.6742e+00,},
std::vector<double>{1.6742e+00,1.6872e+00,1.6991e+00,1.7101e+00,1.7199e+00,1.7287e+00,1.7365e+00,1.7434e+00,1.7495e+00,1.7547e+00,1.7591e+00,1.7628e+00,1.7658e+00,1.7683e+00,1.7703e+00,1.7718e+00,1.7729e+00,1.7737e+00,1.7743e+00,1.7746e+00,1.7748e+00,1.7749e+00,1.7750e+00,1.7750e+00,1.7750e+00,},
std::vector<double>{1.2000e+00,1.1696e+00,1.1396e+00,1.1100e+00,1.0804e+00,1.0515e+00,1.0230e+00,9.9492e-01,9.6721e-01,9.3991e-01,9.1302e-01,8.8657e-01,8.6033e-01,8.3480e-01,8.0976e-01,7.8524e-01,7.6125e-01,7.3782e-01,7.1498e-01,6.9276e-01,6.7099e-01,6.5012e-01,6.2995e-01,6.1053e-01,5.9189e-01,},
std::vector<double>{5.9189e-01,5.7405e-01,5.5704e-01,5.4074e-01,5.2548e-01,5.1113e-01,4.9770e-01,4.8522e-01,4.7369e-01,4.6302e-01,4.5342e-01,4.4480e-01,4.3714e-01,4.3043e-01,4.2466e-01,4.1977e-01,4.1583e-01,4.1274e-01,4.1048e-01,4.0899e-01,4.0822e-01,4.0810e-01,4.0855e-01,4.0949e-01,4.1081e-01,},
std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,},
std::vector<double>{1.7750e+00,1.7749e+00,1.7741e+00,1.7720e+00,1.7683e+00,1.7625e+00,1.7545e+00,1.7440e+00,1.7309e+00,1.7151e+00,1.6968e+00,1.6759e+00,1.6523e+00,1.6263e+00,1.5980e+00,1.5674e+00,1.5345e+00,1.4996e+00,1.4627e+00,1.4237e+00,1.3830e+00,1.3403e+00,1.2957e+00,1.2488e+00,1.2000e+00,},
std::vector<double>{2.0000e+00,1.9667e+00,1.9333e+00,1.9000e+00,1.8667e+00,1.8334e+00,1.8000e+00,1.7667e+00,1.7334e+00,1.6999e+00,1.6667e+00,1.6334e+00,1.5999e+00,1.5666e+00,1.5333e+00,1.5001e+00,1.4666e+00,1.4333e+00,1.4000e+00,1.3666e+00,1.3333e+00,1.3000e+00,1.2667e+00,1.2333e+00,1.2000e+00,},
std::vector<double>{1.2000e+00,1.2522e+00,1.3089e+00,1.3694e+00,1.4333e+00,1.5002e+00,1.5695e+00,1.6398e+00,1.7103e+00,1.7802e+00,1.8475e+00,1.9112e+00,1.9707e+00,2.0242e+00,2.0713e+00,2.1117e+00,2.1451e+00,2.1716e+00,2.1916e+00,2.2060e+00,2.2155e+00,2.2211e+00,2.2239e+00,2.2249e+00,2.2250e+00,},
std::vector<double>{4.1081e-01,4.1223e-01,4.1331e-01,4.1364e-01,4.1294e-01,4.1108e-01,4.0799e-01,4.0379e-01,3.9861e-01,3.9264e-01,3.8621e-01,3.7960e-01,3.7312e-01,3.6719e-01,3.6212e-01,3.5826e-01,3.5593e-01,3.5544e-01,3.5697e-01,3.6071e-01,3.6666e-01,3.7476e-01,3.8484e-01,3.9669e-01,4.0979e-01,},
std::vector<double>{4.0979e-01,4.2578e-01,4.4341e-01,4.6286e-01,4.8436e-01,5.0791e-01,5.3350e-01,5.6066e-01,5.8922e-01,6.1902e-01,6.4950e-01,6.8055e-01,7.1212e-01,7.4376e-01,7.7552e-01,8.0734e-01,8.3934e-01,8.7118e-01,9.0300e-01,9.3493e-01,9.6663e-01,9.9825e-01,1.0298e+00,1.0614e+00,1.0929e+00,},
};
//! TODO
const std::vector<std::vector<double>> edges_cos = std::vector<std::vector<double>>
{
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9998e-01,9.9994e-01,9.9989e-01,9.9980e-01,9.9966e-01,9.9945e-01,9.9916e-01,9.9875e-01,},
std::vector<double>{9.9874e-01,9.9834e-01,9.9782e-01,9.9718e-01,9.9639e-01,9.9543e-01,9.9425e-01,9.9286e-01,9.9119e-01,9.8918e-01,9.8684e-01,9.8405e-01,9.8083e-01,9.7709e-01,9.7269e-01,9.6768e-01,9.6184e-01,9.5525e-01,9.4764e-01,9.3909e-01,9.2943e-01,9.1839e-01,9.0613e-01,8.9223e-01,8.7689e-01,},
std::vector<double>{8.7668e-01,8.5381e-01,8.2711e-01,7.9696e-01,7.6281e-01,7.2437e-01,6.8524e-01,6.4841e-01,6.1169e-01,5.7533e-01,5.3922e-01,5.0421e-01,4.7011e-01,4.3707e-01,4.0489e-01,3.7425e-01,3.4491e-01,3.1691e-01,2.9005e-01,2.6484e-01,2.4102e-01,2.1860e-01,1.9736e-01,1.7769e-01,1.5934e-01,},
std::vector<double>{1.5917e-01,1.3887e-01,1.2022e-01,1.0346e-01,8.8219e-02,7.4569e-02,6.2418e-02,5.1759e-02,4.2332e-02,3.4137e-02,2.7085e-02,2.1129e-02,1.6086e-02,1.1920e-02,8.5433e-03,5.8890e-03,3.8309e-03,2.3096e-03,1.2433e-03,5.5588e-04,1.5791e-04,-2.1301e-05,-5.7829e-05,-2.6650e-05,-7.9530e-10,},
std::vector<double>{1.5916e-01,1.3673e-01,1.0857e-01,7.5298e-02,3.6965e-02,-5.2149e-03,-5.1077e-02,-1.0008e-01,-1.5165e-01,-2.0519e-01,-2.6008e-01,-3.1569e-01,-3.7194e-01,-4.2714e-01,-4.8128e-01,-5.3381e-01,-5.8426e-01,-6.3223e-01,-6.7737e-01,-7.1943e-01,-7.5856e-01,-7.9391e-01,-8.2582e-01,-8.5433e-01,-8.7951e-01,},
std::vector<double>{-8.7973e-01,-9.0149e-01,-9.2047e-01,-9.3679e-01,-9.5038e-01,-9.6165e-01,-9.7086e-01,-9.7827e-01,-9.8413e-01,-9.8871e-01,-9.9215e-01,-9.9471e-01,-9.9655e-01,-9.9784e-01,-9.9870e-01,-9.9927e-01,-9.9962e-01,-9.9981e-01,-9.9992e-01,-9.9997e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{3.6946e-08,1.1936e-03,4.8199e-03,1.0906e-02,1.9566e-02,3.0641e-02,4.4201e-02,6.0232e-02,7.8707e-02,9.9586e-02,1.2281e-01,1.4831e-01,1.7627e-01,2.0604e-01,2.3775e-01,2.7123e-01,3.0632e-01,3.4280e-01,3.8046e-01,4.1906e-01,4.5870e-01,4.9836e-01,5.3812e-01,5.7768e-01,6.1673e-01,},
std::vector<double>{6.1710e-01,6.5496e-01,6.9208e-01,7.2815e-01,7.6220e-01,7.9434e-01,8.2436e-01,8.5208e-01,8.7737e-01,9.0033e-01,9.2048e-01,9.3804e-01,9.5306e-01,9.6561e-01,9.7585e-01,9.8399e-01,9.9009e-01,9.9447e-01,9.9738e-01,9.9909e-01,9.9987e-01,9.9998e-01,9.9968e-01,9.9920e-01,9.9874e-01,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9792e-01,-9.9374e-01,-9.8549e-01,-9.7147e-01,-9.5026e-01,-9.2055e-01,-8.8126e-01,-8.3243e-01,-7.7419e-01,-7.0711e-01,-6.3332e-01,-5.5452e-01,-4.7303e-01,-3.9102e-01,-3.1183e-01,-2.3752e-01,-1.7002e-01,-1.1196e-01,-6.4637e-02,-2.9452e-02,-7.4995e-03,-5.8615e-08,},
std::vector<double>{-1.7344e-13,-2.2733e-08,-9.2211e-08,-1.7243e-07,-2.8353e-07,-3.9645e-07,-4.5504e-07,-4.7637e-07,-4.9573e-07,-4.7817e-07,-3.6141e-07,-1.5529e-07,5.4920e-08,2.0080e-07,3.0102e-07,4.0445e-07,5.0182e-07,5.2826e-07,4.6262e-07,3.6293e-07,2.7853e-07,1.8535e-07,8.4890e-08,2.5600e-08,-3.4688e-13,},
std::vector<double>{5.8625e-08,7.4285e-03,2.9314e-02,6.4437e-02,1.1170e-01,1.6972e-01,2.3717e-01,3.1145e-01,3.9063e-01,4.7264e-01,5.5413e-01,6.3295e-01,7.0711e-01,7.7389e-01,8.3217e-01,8.8104e-01,9.2038e-01,9.5014e-01,9.7138e-01,9.8544e-01,9.9371e-01,9.9791e-01,9.9957e-01,9.9997e-01,1.0000e+00,},
std::vector<double>{9.9874e-01,9.9889e-01,9.9964e-01,9.9999e-01,9.9900e-01,9.9619e-01,9.9162e-01,9.8597e-01,9.8021e-01,9.7542e-01,9.7265e-01,9.7255e-01,9.7531e-01,9.8050e-01,9.8717e-01,9.9382e-01,9.9869e-01,9.9985e-01,9.9574e-01,9.8528e-01,9.6853e-01,9.4651e-01,9.2151e-01,8.9681e-01,8.7678e-01,},
std::vector<double>{8.7678e-01,8.5245e-01,8.1593e-01,7.6771e-01,7.0852e-01,6.4008e-01,5.6463e-01,4.8614e-01,4.0774e-01,3.3245e-01,2.6400e-01,2.0438e-01,1.5506e-01,1.1748e-01,9.1685e-02,7.7371e-02,7.3685e-02,7.9282e-02,9.2241e-02,1.1029e-01,1.3039e-01,1.4931e-01,1.6332e-01,1.6821e-01,1.5925e-01,},
std::vector<double>{9.9875e-01,9.9916e-01,9.9945e-01,9.9966e-01,9.9980e-01,9.9989e-01,9.9994e-01,9.9998e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{8.7689e-01,8.9223e-01,9.0613e-01,9.1839e-01,9.2943e-01,9.3909e-01,9.4774e-01,9.5525e-01,9.6184e-01,9.6768e-01,9.7269e-01,9.7709e-01,9.8083e-01,9.8405e-01,9.8684e-01,9.8918e-01,9.9119e-01,9.9286e-01,9.9427e-01,9.9543e-01,9.9639e-01,9.9718e-01,9.9782e-01,9.9834e-01,9.9874e-01,},
std::vector<double>{1.5934e-01,1.7769e-01,1.9756e-01,2.1860e-01,2.4102e-01,2.6484e-01,2.9030e-01,3.1691e-01,3.4491e-01,3.7425e-01,4.0518e-01,4.3707e-01,4.7011e-01,5.0421e-01,5.3955e-01,5.7533e-01,6.1169e-01,6.4841e-01,6.8559e-01,7.2437e-01,7.6281e-01,7.9696e-01,8.2737e-01,8.5381e-01,8.7668e-01,},
std::vector<double>{-7.9530e-10,-2.6650e-05,-5.7905e-05,-2.1301e-05,1.5791e-04,5.5588e-04,1.2502e-03,2.3096e-03,3.8309e-03,5.8890e-03,8.5670e-03,1.1920e-02,1.6086e-02,2.1129e-02,2.7136e-02,3.4137e-02,4.2332e-02,5.1759e-02,6.2508e-02,7.4569e-02,8.8219e-02,1.0346e-01,1.2036e-01,1.3887e-01,1.5917e-01,},
std::vector<double>{-8.7951e-01,-8.5433e-01,-8.2582e-01,-7.9391e-01,-7.5820e-01,-7.1943e-01,-6.7737e-01,-6.3223e-01,-5.8426e-01,-5.3381e-01,-4.8128e-01,-4.2714e-01,-3.7140e-01,-3.1569e-01,-2.6008e-01,-2.0519e-01,-1.5165e-01,-1.0008e-01,-5.1077e-02,-5.2149e-03,3.7351e-02,7.5298e-02,1.0857e-01,1.3673e-01,1.5916e-01,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9997e-01,-9.9992e-01,-9.9981e-01,-9.9962e-01,-9.9927e-01,-9.9870e-01,-9.9784e-01,-9.9655e-01,-9.9471e-01,-9.9215e-01,-9.8867e-01,-9.8413e-01,-9.7827e-01,-9.7086e-01,-9.6165e-01,-9.5038e-01,-9.3665e-01,-9.2047e-01,-9.0149e-01,-8.7973e-01,},
std::vector<double>{6.1673e-01,5.7768e-01,5.3812e-01,4.9836e-01,4.5832e-01,4.1906e-01,3.8046e-01,3.4280e-01,3.0632e-01,2.7123e-01,2.3775e-01,2.0604e-01,1.7599e-01,1.4831e-01,1.2281e-01,9.9586e-02,7.8707e-02,6.0232e-02,4.4201e-02,3.0641e-02,1.9471e-02,1.0906e-02,4.8199e-03,1.1936e-03,3.6946e-08,},
std::vector<double>{9.9874e-01,9.9920e-01,9.9968e-01,9.9998e-01,9.9987e-01,9.9909e-01,9.9738e-01,9.9447e-01,9.9009e-01,9.8392e-01,9.7585e-01,9.6561e-01,9.5306e-01,9.3804e-01,9.2048e-01,9.0013e-01,8.7737e-01,8.5208e-01,8.2436e-01,7.9434e-01,7.6220e-01,7.2781e-01,6.9208e-01,6.5496e-01,6.1710e-01,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{-5.8615e-08,-7.4995e-03,-2.9452e-02,-6.4637e-02,-1.1196e-01,-1.7002e-01,-2.3752e-01,-3.1183e-01,-3.9102e-01,-4.7303e-01,-5.5452e-01,-6.3332e-01,-7.0745e-01,-7.7419e-01,-8.3243e-01,-8.8126e-01,-9.2055e-01,-9.5026e-01,-9.7147e-01,-9.8549e-01,-9.9374e-01,-9.9792e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,},
std::vector<double>{-3.4688e-13,2.5600e-08,8.4890e-08,1.8535e-07,2.7853e-07,3.6293e-07,4.6262e-07,5.2826e-07,5.0182e-07,4.0445e-07,3.0102e-07,2.0080e-07,5.4045e-08,-1.5529e-07,-3.6141e-07,-4.7817e-07,-4.9573e-07,-4.7637e-07,-4.5504e-07,-3.9645e-07,-2.8353e-07,-1.7243e-07,-9.2211e-08,-2.2733e-08,-1.7344e-13,},
std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9791e-01,9.9371e-01,9.8544e-01,9.7138e-01,9.5014e-01,9.2038e-01,8.8104e-01,8.3217e-01,7.7389e-01,7.0677e-01,6.3295e-01,5.5413e-01,4.7264e-01,3.9063e-01,3.1145e-01,2.3717e-01,1.6972e-01,1.1170e-01,6.4437e-02,2.9314e-02,7.4285e-03,5.8625e-08,},
std::vector<double>{8.7678e-01,8.9681e-01,9.2151e-01,9.4651e-01,9.6853e-01,9.8528e-01,9.9574e-01,9.9985e-01,9.9869e-01,9.9382e-01,9.8717e-01,9.8050e-01,9.7529e-01,9.7255e-01,9.7265e-01,9.7542e-01,9.8021e-01,9.8597e-01,9.9162e-01,9.9619e-01,9.9900e-01,9.9999e-01,9.9964e-01,9.9889e-01,9.9874e-01,},
std::vector<double>{1.5925e-01,1.6821e-01,1.6332e-01,1.4931e-01,1.3039e-01,1.1029e-01,9.2241e-02,7.9282e-02,7.3685e-02,7.7371e-02,9.1685e-02,1.1748e-01,1.5527e-01,2.0438e-01,2.6400e-01,3.3245e-01,4.0774e-01,4.8614e-01,5.6463e-01,6.4008e-01,7.0852e-01,7.6771e-01,8.1593e-01,8.5245e-01,8.7678e-01,},
std::vector<double>{-9.9875e-01,-9.9916e-01,-9.9945e-01,-9.9966e-01,-9.9980e-01,-9.9989e-01,-9.9994e-01,-9.9998e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{-8.7689e-01,-8.9223e-01,-9.0613e-01,-9.1839e-01,-9.2943e-01,-9.3909e-01,-9.4774e-01,-9.5525e-01,-9.6184e-01,-9.6768e-01,-9.7269e-01,-9.7709e-01,-9.8083e-01,-9.8405e-01,-9.8684e-01,-9.8918e-01,-9.9119e-01,-9.9286e-01,-9.9427e-01,-9.9543e-01,-9.9639e-01,-9.9718e-01,-9.9782e-01,-9.9834e-01,-9.9874e-01,},
std::vector<double>{-1.5934e-01,-1.7769e-01,-1.9756e-01,-2.1860e-01,-2.4102e-01,-2.6484e-01,-2.9030e-01,-3.1691e-01,-3.4491e-01,-3.7425e-01,-4.0518e-01,-4.3707e-01,-4.7011e-01,-5.0421e-01,-5.3955e-01,-5.7533e-01,-6.1169e-01,-6.4841e-01,-6.8559e-01,-7.2437e-01,-7.6281e-01,-7.9696e-01,-8.2737e-01,-8.5381e-01,-8.7668e-01,},
std::vector<double>{7.9530e-10,2.6650e-05,5.7905e-05,2.1301e-05,-1.5791e-04,-5.5588e-04,-1.2502e-03,-2.3096e-03,-3.8309e-03,-5.8890e-03,-8.5670e-03,-1.1920e-02,-1.6086e-02,-2.1129e-02,-2.7136e-02,-3.4137e-02,-4.2332e-02,-5.1759e-02,-6.2508e-02,-7.4569e-02,-8.8219e-02,-1.0346e-01,-1.2036e-01,-1.3887e-01,-1.5917e-01,},
std::vector<double>{8.7951e-01,8.5433e-01,8.2582e-01,7.9391e-01,7.5820e-01,7.1943e-01,6.7737e-01,6.3223e-01,5.8426e-01,5.3381e-01,4.8128e-01,4.2714e-01,3.7140e-01,3.1569e-01,2.6008e-01,2.0519e-01,1.5165e-01,1.0008e-01,5.1077e-02,5.2149e-03,-3.7351e-02,-7.5298e-02,-1.0857e-01,-1.3673e-01,-1.5916e-01,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9997e-01,9.9992e-01,9.9981e-01,9.9962e-01,9.9927e-01,9.9870e-01,9.9784e-01,9.9655e-01,9.9471e-01,9.9215e-01,9.8867e-01,9.8413e-01,9.7827e-01,9.7086e-01,9.6165e-01,9.5038e-01,9.3665e-01,9.2047e-01,9.0149e-01,8.7973e-01,},
std::vector<double>{-6.1673e-01,-5.7768e-01,-5.3812e-01,-4.9836e-01,-4.5832e-01,-4.1906e-01,-3.8046e-01,-3.4280e-01,-3.0632e-01,-2.7123e-01,-2.3775e-01,-2.0604e-01,-1.7599e-01,-1.4831e-01,-1.2281e-01,-9.9586e-02,-7.8707e-02,-6.0232e-02,-4.4201e-02,-3.0641e-02,-1.9471e-02,-1.0906e-02,-4.8199e-03,-1.1936e-03,-3.6946e-08,},
std::vector<double>{-9.9874e-01,-9.9920e-01,-9.9968e-01,-9.9998e-01,-9.9987e-01,-9.9909e-01,-9.9738e-01,-9.9447e-01,-9.9009e-01,-9.8392e-01,-9.7585e-01,-9.6561e-01,-9.5306e-01,-9.3804e-01,-9.2048e-01,-9.0013e-01,-8.7737e-01,-8.5208e-01,-8.2436e-01,-7.9434e-01,-7.6220e-01,-7.2781e-01,-6.9208e-01,-6.5496e-01,-6.1710e-01,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{5.8615e-08,7.4995e-03,2.9452e-02,6.4637e-02,1.1196e-01,1.7002e-01,2.3752e-01,3.1183e-01,3.9102e-01,4.7303e-01,5.5452e-01,6.3332e-01,7.0745e-01,7.7419e-01,8.3243e-01,8.8126e-01,9.2055e-01,9.5026e-01,9.7147e-01,9.8549e-01,9.9374e-01,9.9792e-01,9.9957e-01,9.9997e-01,1.0000e+00,},
std::vector<double>{3.4688e-13,-2.5600e-08,-8.4890e-08,-1.8535e-07,-2.7853e-07,-3.6293e-07,-4.6262e-07,-5.2826e-07,-5.0182e-07,-4.0445e-07,-3.0102e-07,-2.0080e-07,-5.4045e-08,1.5529e-07,3.6141e-07,4.7817e-07,4.9573e-07,4.7637e-07,4.5504e-07,3.9645e-07,2.8353e-07,1.7243e-07,9.2211e-08,2.2733e-08,1.7344e-13,},
std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9791e-01,-9.9371e-01,-9.8544e-01,-9.7138e-01,-9.5014e-01,-9.2038e-01,-8.8104e-01,-8.3217e-01,-7.7389e-01,-7.0677e-01,-6.3295e-01,-5.5413e-01,-4.7264e-01,-3.9063e-01,-3.1145e-01,-2.3717e-01,-1.6972e-01,-1.1170e-01,-6.4437e-02,-2.9314e-02,-7.4285e-03,-5.8625e-08,},
std::vector<double>{-8.7678e-01,-8.9681e-01,-9.2151e-01,-9.4651e-01,-9.6853e-01,-9.8528e-01,-9.9574e-01,-9.9985e-01,-9.9869e-01,-9.9382e-01,-9.8717e-01,-9.8050e-01,-9.7529e-01,-9.7255e-01,-9.7265e-01,-9.7542e-01,-9.8021e-01,-9.8597e-01,-9.9162e-01,-9.9619e-01,-9.9900e-01,-9.9999e-01,-9.9964e-01,-9.9889e-01,-9.9874e-01,},
std::vector<double>{-1.5925e-01,-1.6821e-01,-1.6332e-01,-1.4931e-01,-1.3039e-01,-1.1029e-01,-9.2241e-02,-7.9282e-02,-7.3685e-02,-7.7371e-02,-9.1685e-02,-1.1748e-01,-1.5527e-01,-2.0438e-01,-2.6400e-01,-3.3245e-01,-4.0774e-01,-4.8614e-01,-5.6463e-01,-6.4008e-01,-7.0852e-01,-7.6771e-01,-8.1593e-01,-8.5245e-01,-8.7678e-01,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9998e-01,-9.9994e-01,-9.9989e-01,-9.9980e-01,-9.9966e-01,-9.9945e-01,-9.9916e-01,-9.9875e-01,},
std::vector<double>{-9.9874e-01,-9.9834e-01,-9.9782e-01,-9.9718e-01,-9.9639e-01,-9.9543e-01,-9.9425e-01,-9.9286e-01,-9.9119e-01,-9.8918e-01,-9.8684e-01,-9.8405e-01,-9.8083e-01,-9.7709e-01,-9.7269e-01,-9.6768e-01,-9.6184e-01,-9.5525e-01,-9.4764e-01,-9.3909e-01,-9.2943e-01,-9.1839e-01,-9.0613e-01,-8.9223e-01,-8.7689e-01,},
std::vector<double>{-8.7668e-01,-8.5381e-01,-8.2711e-01,-7.9696e-01,-7.6281e-01,-7.2437e-01,-6.8524e-01,-6.4841e-01,-6.1169e-01,-5.7533e-01,-5.3922e-01,-5.0421e-01,-4.7011e-01,-4.3707e-01,-4.0489e-01,-3.7425e-01,-3.4491e-01,-3.1691e-01,-2.9005e-01,-2.6484e-01,-2.4102e-01,-2.1860e-01,-1.9736e-01,-1.7769e-01,-1.5934e-01,},
std::vector<double>{-1.5917e-01,-1.3887e-01,-1.2022e-01,-1.0346e-01,-8.8219e-02,-7.4569e-02,-6.2418e-02,-5.1759e-02,-4.2332e-02,-3.4137e-02,-2.7085e-02,-2.1129e-02,-1.6086e-02,-1.1920e-02,-8.5433e-03,-5.8890e-03,-3.8309e-03,-2.3096e-03,-1.2433e-03,-5.5588e-04,-1.5791e-04,2.1301e-05,5.7829e-05,2.6650e-05,7.9530e-10,},
std::vector<double>{-1.5916e-01,-1.3673e-01,-1.0857e-01,-7.5298e-02,-3.6965e-02,5.2149e-03,5.1077e-02,1.0008e-01,1.5165e-01,2.0519e-01,2.6008e-01,3.1569e-01,3.7194e-01,4.2714e-01,4.8128e-01,5.3381e-01,5.8426e-01,6.3223e-01,6.7737e-01,7.1943e-01,7.5856e-01,7.9391e-01,8.2582e-01,8.5433e-01,8.7951e-01,},
std::vector<double>{8.7973e-01,9.0149e-01,9.2047e-01,9.3679e-01,9.5038e-01,9.6165e-01,9.7086e-01,9.7827e-01,9.8413e-01,9.8871e-01,9.9215e-01,9.9471e-01,9.9655e-01,9.9784e-01,9.9870e-01,9.9927e-01,9.9962e-01,9.9981e-01,9.9992e-01,9.9997e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{-3.6946e-08,-1.1936e-03,-4.8199e-03,-1.0906e-02,-1.9566e-02,-3.0641e-02,-4.4201e-02,-6.0232e-02,-7.8707e-02,-9.9586e-02,-1.2281e-01,-1.4831e-01,-1.7627e-01,-2.0604e-01,-2.3775e-01,-2.7123e-01,-3.0632e-01,-3.4280e-01,-3.8046e-01,-4.1906e-01,-4.5870e-01,-4.9836e-01,-5.3812e-01,-5.7768e-01,-6.1673e-01,},
std::vector<double>{-6.1710e-01,-6.5496e-01,-6.9208e-01,-7.2815e-01,-7.6220e-01,-7.9434e-01,-8.2436e-01,-8.5208e-01,-8.7737e-01,-9.0033e-01,-9.2048e-01,-9.3804e-01,-9.5306e-01,-9.6561e-01,-9.7585e-01,-9.8399e-01,-9.9009e-01,-9.9447e-01,-9.9738e-01,-9.9909e-01,-9.9987e-01,-9.9998e-01,-9.9968e-01,-9.9920e-01,-9.9874e-01,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9792e-01,9.9374e-01,9.8549e-01,9.7147e-01,9.5026e-01,9.2055e-01,8.8126e-01,8.3243e-01,7.7419e-01,7.0711e-01,6.3332e-01,5.5452e-01,4.7303e-01,3.9102e-01,3.1183e-01,2.3752e-01,1.7002e-01,1.1196e-01,6.4637e-02,2.9452e-02,7.4995e-03,5.8615e-08,},
std::vector<double>{1.7344e-13,2.2733e-08,9.2211e-08,1.7243e-07,2.8353e-07,3.9645e-07,4.5504e-07,4.7637e-07,4.9573e-07,4.7817e-07,3.6141e-07,1.5529e-07,-5.4920e-08,-2.0080e-07,-3.0102e-07,-4.0445e-07,-5.0182e-07,-5.2826e-07,-4.6262e-07,-3.6293e-07,-2.7853e-07,-1.8535e-07,-8.4890e-08,-2.5600e-08,3.4688e-13,},
std::vector<double>{-5.8625e-08,-7.4285e-03,-2.9314e-02,-6.4437e-02,-1.1170e-01,-1.6972e-01,-2.3717e-01,-3.1145e-01,-3.9063e-01,-4.7264e-01,-5.5413e-01,-6.3295e-01,-7.0711e-01,-7.7389e-01,-8.3217e-01,-8.8104e-01,-9.2038e-01,-9.5014e-01,-9.7138e-01,-9.8544e-01,-9.9371e-01,-9.9791e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,},
std::vector<double>{-9.9874e-01,-9.9889e-01,-9.9964e-01,-9.9999e-01,-9.9900e-01,-9.9619e-01,-9.9162e-01,-9.8597e-01,-9.8021e-01,-9.7542e-01,-9.7265e-01,-9.7255e-01,-9.7531e-01,-9.8050e-01,-9.8717e-01,-9.9382e-01,-9.9869e-01,-9.9985e-01,-9.9574e-01,-9.8528e-01,-9.6853e-01,-9.4651e-01,-9.2151e-01,-8.9681e-01,-8.7678e-01,},
std::vector<double>{-8.7678e-01,-8.5245e-01,-8.1593e-01,-7.6771e-01,-7.0852e-01,-6.4008e-01,-5.6463e-01,-4.8614e-01,-4.0774e-01,-3.3245e-01,-2.6400e-01,-2.0438e-01,-1.5506e-01,-1.1748e-01,-9.1685e-02,-7.7371e-02,-7.3685e-02,-7.9282e-02,-9.2241e-02,-1.1029e-01,-1.3039e-01,-1.4931e-01,-1.6332e-01,-1.6821e-01,-1.5925e-01,},
};
//! TODO
const std::vector<std::vector<double>> edges_sin = std::vector<std::vector<double>>
{
std::vector<double>{2.8280e-09,8.7033e-05,3.2684e-04,6.8721e-04,1.1230e-03,1.5971e-03,2.0674e-03,2.4902e-03,2.8192e-03,3.0077e-03,3.0017e-03,2.7517e-03,2.2038e-03,1.3022e-03,-1.1162e-05,-1.8156e-03,-4.1394e-03,-7.0609e-03,-1.0646e-02,-1.4962e-02,-2.0079e-02,-2.6128e-02,-3.3068e-02,-4.1027e-02,-5.0078e-02,},
std::vector<double>{-5.0170e-02,-5.7655e-02,-6.6035e-02,-7.5042e-02,-8.4936e-02,-9.5504e-02,-1.0704e-01,-1.1930e-01,-1.3244e-01,-1.4668e-01,-1.6169e-01,-1.7788e-01,-1.9486e-01,-2.1285e-01,-2.3212e-01,-2.5220e-01,-2.7360e-01,-2.9580e-01,-3.1935e-01,-3.4366e-01,-3.6900e-01,-3.9568e-01,-4.2299e-01,-4.5159e-01,-4.8070e-01,},
std::vector<double>{-4.8107e-01,-5.2058e-01,-5.6205e-01,-6.0403e-01,-6.4662e-01,-6.8942e-01,-7.2831e-01,-7.6129e-01,-7.9110e-01,-8.1792e-01,-8.4217e-01,-8.6358e-01,-8.8261e-01,-8.9943e-01,-9.1437e-01,-9.2733e-01,-9.3864e-01,-9.4845e-01,-9.5701e-01,-9.6429e-01,-9.7052e-01,-9.7581e-01,-9.8033e-01,-9.8409e-01,-9.8722e-01,},
std::vector<double>{-9.8725e-01,-9.9031e-01,-9.9275e-01,-9.9463e-01,-9.9610e-01,-9.9722e-01,-9.9805e-01,-9.9866e-01,-9.9910e-01,-9.9942e-01,-9.9963e-01,-9.9978e-01,-9.9987e-01,-9.9993e-01,-9.9996e-01,-9.9998e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{-9.8725e-01,-9.9061e-01,-9.9409e-01,-9.9716e-01,-9.9932e-01,-9.9999e-01,-9.9869e-01,-9.9498e-01,-9.8843e-01,-9.7872e-01,-9.6559e-01,-9.4886e-01,-9.2826e-01,-9.0418e-01,-8.7657e-01,-8.4561e-01,-8.1157e-01,-7.7478e-01,-7.3564e-01,-6.9457e-01,-6.5161e-01,-6.0804e-01,-5.6393e-01,-5.1974e-01,-4.7589e-01,},
std::vector<double>{-4.7547e-01,-4.3279e-01,-3.9081e-01,-3.4989e-01,-3.1110e-01,-2.7429e-01,-2.3965e-01,-2.0733e-01,-1.7745e-01,-1.4982e-01,-1.2502e-01,-1.0277e-01,-8.3032e-02,-6.5764e-02,-5.0880e-02,-3.8165e-02,-2.7734e-02,-1.9306e-02,-1.2714e-02,-7.7711e-03,-4.2732e-03,-1.9803e-03,-6.9309e-04,-1.2527e-04,-2.2879e-09,},
std::vector<double>{1.0000e+00,1.0000e+00,9.9999e-01,9.9994e-01,9.9981e-01,9.9953e-01,9.9902e-01,9.9818e-01,9.9690e-01,9.9503e-01,9.9243e-01,9.8894e-01,9.8434e-01,9.7854e-01,9.7133e-01,9.6251e-01,9.5193e-01,9.3941e-01,9.2480e-01,9.0796e-01,8.8859e-01,8.6697e-01,8.4287e-01,8.1626e-01,7.8718e-01,},
std::vector<double>{7.8689e-01,7.5566e-01,7.2182e-01,6.8542e-01,6.4734e-01,6.0748e-01,5.6607e-01,5.2341e-01,4.7981e-01,4.3520e-01,3.9079e-01,3.4653e-01,3.0280e-01,2.5998e-01,2.1846e-01,1.7824e-01,1.4045e-01,1.0504e-01,7.2350e-02,4.2693e-02,1.6370e-02,-6.5324e-03,-2.5301e-02,-3.9907e-02,-5.0086e-02,},
std::vector<double>{1.7344e-13,-8.1628e-09,-3.3111e-08,-6.1918e-08,-1.0181e-07,-1.4236e-07,-1.6340e-07,-1.7106e-07,-1.7801e-07,-1.7170e-07,-1.2978e-07,-5.5762e-08,1.9721e-08,7.2103e-08,1.0809e-07,1.4523e-07,1.8019e-07,1.8969e-07,1.6612e-07,1.3032e-07,1.0001e-07,6.6555e-08,3.0482e-08,9.1925e-09,-3.4688e-13,},
std::vector<double>{5.8615e-08,7.4285e-03,2.9314e-02,6.4437e-02,1.1170e-01,1.6972e-01,2.3717e-01,3.1145e-01,3.9063e-01,4.7264e-01,5.5413e-01,6.3295e-01,7.0711e-01,7.7389e-01,8.3217e-01,8.8104e-01,9.2038e-01,9.5014e-01,9.7138e-01,9.8544e-01,9.9371e-01,9.9791e-01,9.9957e-01,9.9997e-01,1.0000e+00,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9792e-01,-9.9374e-01,-9.8549e-01,-9.7147e-01,-9.5026e-01,-9.2055e-01,-8.8126e-01,-8.3243e-01,-7.7419e-01,-7.0711e-01,-6.3332e-01,-5.5452e-01,-4.7303e-01,-3.9102e-01,-3.1183e-01,-2.3752e-01,-1.7002e-01,-1.1196e-01,-6.4637e-02,-2.9452e-02,-7.4995e-03,-5.8625e-08,},
std::vector<double>{-5.0124e-02,-4.7058e-02,-2.6797e-02,5.3534e-03,4.4786e-02,8.7252e-02,1.2917e-01,1.6689e-01,1.9796e-01,2.2035e-01,2.3225e-01,2.3269e-01,2.2085e-01,1.9650e-01,1.5970e-01,1.1099e-01,5.1198e-02,-1.7293e-02,-9.2253e-02,-1.7092e-01,-2.4891e-01,-3.2268e-01,-3.8835e-01,-4.4242e-01,-4.8088e-01,},
std::vector<double>{-4.8088e-01,-5.2280e-01,-5.7815e-01,-6.4079e-01,-7.0570e-01,-7.6831e-01,-8.2534e-01,-8.7388e-01,-9.1310e-01,-9.4312e-01,-9.6452e-01,-9.7889e-01,-9.8791e-01,-9.9308e-01,-9.9579e-01,-9.9700e-01,-9.9728e-01,-9.9685e-01,-9.9574e-01,-9.9390e-01,-9.9146e-01,-9.8879e-01,-9.8657e-01,-9.8575e-01,-9.8724e-01,},
std::vector<double>{5.0078e-02,4.1027e-02,3.3068e-02,2.6066e-02,2.0079e-02,1.4962e-02,1.0646e-02,7.0609e-03,4.1394e-03,1.7961e-03,1.1162e-05,-1.3022e-03,-2.2038e-03,-2.7517e-03,-3.0017e-03,-3.0068e-03,-2.8192e-03,-2.4902e-03,-2.0674e-03,-1.5971e-03,-1.1230e-03,-6.8337e-04,-3.2684e-04,-8.7033e-05,-2.8280e-09,},
std::vector<double>{4.8070e-01,4.5159e-01,4.2299e-01,3.9568e-01,3.6900e-01,3.4366e-01,3.1905e-01,2.9580e-01,2.7360e-01,2.5220e-01,2.3212e-01,2.1285e-01,1.9486e-01,1.7788e-01,1.6169e-01,1.4668e-01,1.3244e-01,1.1930e-01,1.0689e-01,9.5504e-02,8.4936e-02,7.5042e-02,6.6035e-02,5.7655e-02,5.0170e-02,},
std::vector<double>{9.8722e-01,9.8409e-01,9.8029e-01,9.7581e-01,9.7052e-01,9.6429e-01,9.5694e-01,9.4845e-01,9.3864e-01,9.2733e-01,9.1424e-01,8.9943e-01,8.8261e-01,8.6358e-01,8.4195e-01,8.1792e-01,7.9110e-01,7.6129e-01,7.2798e-01,6.8942e-01,6.4662e-01,6.0403e-01,5.6165e-01,5.2058e-01,4.8107e-01,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9998e-01,9.9996e-01,9.9993e-01,9.9987e-01,9.9978e-01,9.9963e-01,9.9942e-01,9.9910e-01,9.9866e-01,9.9804e-01,9.9722e-01,9.9610e-01,9.9463e-01,9.9273e-01,9.9031e-01,9.8725e-01,},
std::vector<double>{4.7589e-01,5.1974e-01,5.6393e-01,6.0804e-01,6.5202e-01,6.9457e-01,7.3564e-01,7.7478e-01,8.1157e-01,8.4561e-01,8.7657e-01,9.0418e-01,9.2847e-01,9.4886e-01,9.6559e-01,9.7872e-01,9.8843e-01,9.9498e-01,9.9869e-01,9.9999e-01,9.9930e-01,9.9716e-01,9.9409e-01,9.9061e-01,9.8725e-01,},
std::vector<double>{2.2879e-09,1.2527e-04,6.9309e-04,1.9970e-03,4.2732e-03,7.7711e-03,1.2714e-02,1.9306e-02,2.7734e-02,3.8276e-02,5.0880e-02,6.5764e-02,8.3032e-02,1.0277e-01,1.2502e-01,1.5007e-01,1.7745e-01,2.0733e-01,2.3965e-01,2.7429e-01,3.1110e-01,3.5027e-01,3.9081e-01,4.3279e-01,4.7547e-01,},
std::vector<double>{-7.8718e-01,-8.1626e-01,-8.4287e-01,-8.6697e-01,-8.8879e-01,-9.0796e-01,-9.2480e-01,-9.3941e-01,-9.5193e-01,-9.6251e-01,-9.7133e-01,-9.7854e-01,-9.8439e-01,-9.8894e-01,-9.9243e-01,-9.9503e-01,-9.9690e-01,-9.9818e-01,-9.9902e-01,-9.9953e-01,-9.9981e-01,-9.9994e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,},
std::vector<double>{5.0086e-02,3.9907e-02,2.5301e-02,6.3326e-03,-1.6370e-02,-4.2693e-02,-7.2350e-02,-1.0504e-01,-1.4045e-01,-1.7862e-01,-2.1846e-01,-2.5998e-01,-3.0280e-01,-3.4653e-01,-3.9079e-01,-4.3563e-01,-4.7981e-01,-5.2341e-01,-5.6607e-01,-6.0748e-01,-6.4734e-01,-6.8578e-01,-7.2182e-01,-7.5566e-01,-7.8689e-01,},
std::vector<double>{3.4688e-13,-9.1925e-09,-3.0482e-08,-6.6555e-08,-1.0001e-07,-1.3032e-07,-1.6612e-07,-1.8969e-07,-1.8019e-07,-1.4523e-07,-1.0809e-07,-7.2103e-08,-1.9406e-08,5.5762e-08,1.2978e-07,1.7170e-07,1.7801e-07,1.7106e-07,1.6340e-07,1.4236e-07,1.0181e-07,6.1918e-08,3.3111e-08,8.1628e-09,-1.7344e-13,},
std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9791e-01,-9.9371e-01,-9.8544e-01,-9.7138e-01,-9.5014e-01,-9.2038e-01,-8.8104e-01,-8.3217e-01,-7.7389e-01,-7.0677e-01,-6.3295e-01,-5.5413e-01,-4.7264e-01,-3.9063e-01,-3.1145e-01,-2.3717e-01,-1.6972e-01,-1.1170e-01,-6.4437e-02,-2.9314e-02,-7.4285e-03,-5.8615e-08,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{5.8625e-08,7.4995e-03,2.9452e-02,6.4637e-02,1.1196e-01,1.7002e-01,2.3752e-01,3.1183e-01,3.9102e-01,4.7303e-01,5.5452e-01,6.3332e-01,7.0745e-01,7.7419e-01,8.3243e-01,8.8126e-01,9.2055e-01,9.5026e-01,9.7147e-01,9.8549e-01,9.9374e-01,9.9792e-01,9.9957e-01,9.9997e-01,1.0000e+00,},
std::vector<double>{4.8088e-01,4.4242e-01,3.8835e-01,3.2268e-01,2.4891e-01,1.7092e-01,9.2253e-02,1.7293e-02,-5.1198e-02,-1.1099e-01,-1.5970e-01,-1.9650e-01,-2.2094e-01,-2.3269e-01,-2.3225e-01,-2.2035e-01,-1.9796e-01,-1.6689e-01,-1.2917e-01,-8.7252e-02,-4.4786e-02,-5.3534e-03,2.6797e-02,4.7058e-02,5.0124e-02,},
std::vector<double>{9.8724e-01,9.8575e-01,9.8657e-01,9.8879e-01,9.9146e-01,9.9390e-01,9.9574e-01,9.9685e-01,9.9728e-01,9.9700e-01,9.9579e-01,9.9308e-01,9.8787e-01,9.7889e-01,9.6452e-01,9.4312e-01,9.1310e-01,8.7388e-01,8.2534e-01,7.6831e-01,7.0570e-01,6.4079e-01,5.7815e-01,5.2280e-01,4.8088e-01,},
std::vector<double>{-5.0078e-02,-4.1027e-02,-3.3068e-02,-2.6066e-02,-2.0079e-02,-1.4962e-02,-1.0646e-02,-7.0609e-03,-4.1394e-03,-1.7961e-03,-1.1162e-05,1.3022e-03,2.2038e-03,2.7517e-03,3.0017e-03,3.0068e-03,2.8192e-03,2.4902e-03,2.0674e-03,1.5971e-03,1.1230e-03,6.8337e-04,3.2684e-04,8.7033e-05,2.8280e-09,},
std::vector<double>{-4.8070e-01,-4.5159e-01,-4.2299e-01,-3.9568e-01,-3.6900e-01,-3.4366e-01,-3.1905e-01,-2.9580e-01,-2.7360e-01,-2.5220e-01,-2.3212e-01,-2.1285e-01,-1.9486e-01,-1.7788e-01,-1.6169e-01,-1.4668e-01,-1.3244e-01,-1.1930e-01,-1.0689e-01,-9.5504e-02,-8.4936e-02,-7.5042e-02,-6.6035e-02,-5.7655e-02,-5.0170e-02,},
std::vector<double>{-9.8722e-01,-9.8409e-01,-9.8029e-01,-9.7581e-01,-9.7052e-01,-9.6429e-01,-9.5694e-01,-9.4845e-01,-9.3864e-01,-9.2733e-01,-9.1424e-01,-8.9943e-01,-8.8261e-01,-8.6358e-01,-8.4195e-01,-8.1792e-01,-7.9110e-01,-7.6129e-01,-7.2798e-01,-6.8942e-01,-6.4662e-01,-6.0403e-01,-5.6165e-01,-5.2058e-01,-4.8107e-01,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9998e-01,-9.9996e-01,-9.9993e-01,-9.9987e-01,-9.9978e-01,-9.9963e-01,-9.9942e-01,-9.9910e-01,-9.9866e-01,-9.9804e-01,-9.9722e-01,-9.9610e-01,-9.9463e-01,-9.9273e-01,-9.9031e-01,-9.8725e-01,},
std::vector<double>{-4.7589e-01,-5.1974e-01,-5.6393e-01,-6.0804e-01,-6.5202e-01,-6.9457e-01,-7.3564e-01,-7.7478e-01,-8.1157e-01,-8.4561e-01,-8.7657e-01,-9.0418e-01,-9.2847e-01,-9.4886e-01,-9.6559e-01,-9.7872e-01,-9.8843e-01,-9.9498e-01,-9.9869e-01,-9.9999e-01,-9.9930e-01,-9.9716e-01,-9.9409e-01,-9.9061e-01,-9.8725e-01,},
std::vector<double>{-2.2879e-09,-1.2527e-04,-6.9309e-04,-1.9970e-03,-4.2732e-03,-7.7711e-03,-1.2714e-02,-1.9306e-02,-2.7734e-02,-3.8276e-02,-5.0880e-02,-6.5764e-02,-8.3032e-02,-1.0277e-01,-1.2502e-01,-1.5007e-01,-1.7745e-01,-2.0733e-01,-2.3965e-01,-2.7429e-01,-3.1110e-01,-3.5027e-01,-3.9081e-01,-4.3279e-01,-4.7547e-01,},
std::vector<double>{7.8718e-01,8.1626e-01,8.4287e-01,8.6697e-01,8.8879e-01,9.0796e-01,9.2480e-01,9.3941e-01,9.5193e-01,9.6251e-01,9.7133e-01,9.7854e-01,9.8439e-01,9.8894e-01,9.9243e-01,9.9503e-01,9.9690e-01,9.9818e-01,9.9902e-01,9.9953e-01,9.9981e-01,9.9994e-01,9.9999e-01,1.0000e+00,1.0000e+00,},
std::vector<double>{-5.0086e-02,-3.9907e-02,-2.5301e-02,-6.3326e-03,1.6370e-02,4.2693e-02,7.2350e-02,1.0504e-01,1.4045e-01,1.7862e-01,2.1846e-01,2.5998e-01,3.0280e-01,3.4653e-01,3.9079e-01,4.3563e-01,4.7981e-01,5.2341e-01,5.6607e-01,6.0748e-01,6.4734e-01,6.8578e-01,7.2182e-01,7.5566e-01,7.8689e-01,},
std::vector<double>{-3.4688e-13,9.1925e-09,3.0482e-08,6.6555e-08,1.0001e-07,1.3032e-07,1.6612e-07,1.8969e-07,1.8019e-07,1.4523e-07,1.0809e-07,7.2103e-08,1.9406e-08,-5.5762e-08,-1.2978e-07,-1.7170e-07,-1.7801e-07,-1.7106e-07,-1.6340e-07,-1.4236e-07,-1.0181e-07,-6.1918e-08,-3.3111e-08,-8.1628e-09,1.7344e-13,},
std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9791e-01,9.9371e-01,9.8544e-01,9.7138e-01,9.5014e-01,9.2038e-01,8.8104e-01,8.3217e-01,7.7389e-01,7.0677e-01,6.3295e-01,5.5413e-01,4.7264e-01,3.9063e-01,3.1145e-01,2.3717e-01,1.6972e-01,1.1170e-01,6.4437e-02,2.9314e-02,7.4285e-03,5.8615e-08,},
std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{-5.8625e-08,-7.4995e-03,-2.9452e-02,-6.4637e-02,-1.1196e-01,-1.7002e-01,-2.3752e-01,-3.1183e-01,-3.9102e-01,-4.7303e-01,-5.5452e-01,-6.3332e-01,-7.0745e-01,-7.7419e-01,-8.3243e-01,-8.8126e-01,-9.2055e-01,-9.5026e-01,-9.7147e-01,-9.8549e-01,-9.9374e-01,-9.9792e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,},
std::vector<double>{-4.8088e-01,-4.4242e-01,-3.8835e-01,-3.2268e-01,-2.4891e-01,-1.7092e-01,-9.2253e-02,-1.7293e-02,5.1198e-02,1.1099e-01,1.5970e-01,1.9650e-01,2.2094e-01,2.3269e-01,2.3225e-01,2.2035e-01,1.9796e-01,1.6689e-01,1.2917e-01,8.7252e-02,4.4786e-02,5.3534e-03,-2.6797e-02,-4.7058e-02,-5.0124e-02,},
std::vector<double>{-9.8724e-01,-9.8575e-01,-9.8657e-01,-9.8879e-01,-9.9146e-01,-9.9390e-01,-9.9574e-01,-9.9685e-01,-9.9728e-01,-9.9700e-01,-9.9579e-01,-9.9308e-01,-9.8787e-01,-9.7889e-01,-9.6452e-01,-9.4312e-01,-9.1310e-01,-8.7388e-01,-8.2534e-01,-7.6831e-01,-7.0570e-01,-6.4079e-01,-5.7815e-01,-5.2280e-01,-4.8088e-01,},
std::vector<double>{-2.8280e-09,-8.7033e-05,-3.2684e-04,-6.8721e-04,-1.1230e-03,-1.5971e-03,-2.0674e-03,-2.4902e-03,-2.8192e-03,-3.0077e-03,-3.0017e-03,-2.7517e-03,-2.2038e-03,-1.3022e-03,1.1162e-05,1.8156e-03,4.1394e-03,7.0609e-03,1.0646e-02,1.4962e-02,2.0079e-02,2.6128e-02,3.3068e-02,4.1027e-02,5.0078e-02,},
std::vector<double>{5.0170e-02,5.7655e-02,6.6035e-02,7.5042e-02,8.4936e-02,9.5504e-02,1.0704e-01,1.1930e-01,1.3244e-01,1.4668e-01,1.6169e-01,1.7788e-01,1.9486e-01,2.1285e-01,2.3212e-01,2.5220e-01,2.7360e-01,2.9580e-01,3.1935e-01,3.4366e-01,3.6900e-01,3.9568e-01,4.2299e-01,4.5159e-01,4.8070e-01,},
std::vector<double>{4.8107e-01,5.2058e-01,5.6205e-01,6.0403e-01,6.4662e-01,6.8942e-01,7.2831e-01,7.6129e-01,7.9110e-01,8.1792e-01,8.4217e-01,8.6358e-01,8.8261e-01,8.9943e-01,9.1437e-01,9.2733e-01,9.3864e-01,9.4845e-01,9.5701e-01,9.6429e-01,9.7052e-01,9.7581e-01,9.8033e-01,9.8409e-01,9.8722e-01,},
std::vector<double>{9.8725e-01,9.9031e-01,9.9275e-01,9.9463e-01,9.9610e-01,9.9722e-01,9.9805e-01,9.9866e-01,9.9910e-01,9.9942e-01,9.9963e-01,9.9978e-01,9.9987e-01,9.9993e-01,9.9996e-01,9.9998e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,},
std::vector<double>{9.8725e-01,9.9061e-01,9.9409e-01,9.9716e-01,9.9932e-01,9.9999e-01,9.9869e-01,9.9498e-01,9.8843e-01,9.7872e-01,9.6559e-01,9.4886e-01,9.2826e-01,9.0418e-01,8.7657e-01,8.4561e-01,8.1157e-01,7.7478e-01,7.3564e-01,6.9457e-01,6.5161e-01,6.0804e-01,5.6393e-01,5.1974e-01,4.7589e-01,},
std::vector<double>{4.7547e-01,4.3279e-01,3.9081e-01,3.4989e-01,3.1110e-01,2.7429e-01,2.3965e-01,2.0733e-01,1.7745e-01,1.4982e-01,1.2502e-01,1.0277e-01,8.3032e-02,6.5764e-02,5.0880e-02,3.8165e-02,2.7734e-02,1.9306e-02,1.2714e-02,7.7711e-03,4.2732e-03,1.9803e-03,6.9309e-04,1.2527e-04,2.2879e-09,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9994e-01,-9.9981e-01,-9.9953e-01,-9.9902e-01,-9.9818e-01,-9.9690e-01,-9.9503e-01,-9.9243e-01,-9.8894e-01,-9.8434e-01,-9.7854e-01,-9.7133e-01,-9.6251e-01,-9.5193e-01,-9.3941e-01,-9.2480e-01,-9.0796e-01,-8.8859e-01,-8.6697e-01,-8.4287e-01,-8.1626e-01,-7.8718e-01,},
std::vector<double>{-7.8689e-01,-7.5566e-01,-7.2182e-01,-6.8542e-01,-6.4734e-01,-6.0748e-01,-5.6607e-01,-5.2341e-01,-4.7981e-01,-4.3520e-01,-3.9079e-01,-3.4653e-01,-3.0280e-01,-2.5998e-01,-2.1846e-01,-1.7824e-01,-1.4045e-01,-1.0504e-01,-7.2350e-02,-4.2693e-02,-1.6370e-02,6.5324e-03,2.5301e-02,3.9907e-02,5.0086e-02,},
std::vector<double>{-1.7344e-13,8.1628e-09,3.3111e-08,6.1918e-08,1.0181e-07,1.4236e-07,1.6340e-07,1.7106e-07,1.7801e-07,1.7170e-07,1.2978e-07,5.5762e-08,-1.9721e-08,-7.2103e-08,-1.0809e-07,-1.4523e-07,-1.8019e-07,-1.8969e-07,-1.6612e-07,-1.3032e-07,-1.0001e-07,-6.6555e-08,-3.0482e-08,-9.1925e-09,3.4688e-13,},
std::vector<double>{-5.8615e-08,-7.4285e-03,-2.9314e-02,-6.4437e-02,-1.1170e-01,-1.6972e-01,-2.3717e-01,-3.1145e-01,-3.9063e-01,-4.7264e-01,-5.5413e-01,-6.3295e-01,-7.0711e-01,-7.7389e-01,-8.3217e-01,-8.8104e-01,-9.2038e-01,-9.5014e-01,-9.7138e-01,-9.8544e-01,-9.9371e-01,-9.9791e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,},
std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,},
std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9792e-01,9.9374e-01,9.8549e-01,9.7147e-01,9.5026e-01,9.2055e-01,8.8126e-01,8.3243e-01,7.7419e-01,7.0711e-01,6.3332e-01,5.5452e-01,4.7303e-01,3.9102e-01,3.1183e-01,2.3752e-01,1.7002e-01,1.1196e-01,6.4637e-02,2.9452e-02,7.4995e-03,5.8625e-08,},
std::vector<double>{5.0124e-02,4.7058e-02,2.6797e-02,-5.3534e-03,-4.4786e-02,-8.7252e-02,-1.2917e-01,-1.6689e-01,-1.9796e-01,-2.2035e-01,-2.3225e-01,-2.3269e-01,-2.2085e-01,-1.9650e-01,-1.5970e-01,-1.1099e-01,-5.1198e-02,1.7293e-02,9.2253e-02,1.7092e-01,2.4891e-01,3.2268e-01,3.8835e-01,4.4242e-01,4.8088e-01,},
std::vector<double>{4.8088e-01,5.2280e-01,5.7815e-01,6.4079e-01,7.0570e-01,7.6831e-01,8.2534e-01,8.7388e-01,9.1310e-01,9.4312e-01,9.6452e-01,9.7889e-01,9.8791e-01,9.9308e-01,9.9579e-01,9.9700e-01,9.9728e-01,9.9685e-01,9.9574e-01,9.9390e-01,9.9146e-01,9.8879e-01,9.8657e-01,9.8575e-01,9.8724e-01,},
};
};
| 261.035461 | 568 | 0.687714 | Durrrr95 |
ecce2b591bb3292aa6526327f58ae6d28fef08dd | 5,627 | cpp | C++ | Utilities/vecmath/test-9.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/vecmath/test-9.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | Utilities/vecmath/test-9.cpp | nocnokneo/MITK | 2902dcaed2ebf83b08c29d73608e8c70ead9e602 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (C) 1997,1998,1999
Kenji Hiranabe, Eiwa System Management, Inc.
This program is free software.
Implemented by Kenji Hiranabe([email protected]),
conforming to the Java(TM) 3D API specification by Sun Microsystems.
Permission to use, copy, modify, distribute and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation. Kenji Hiranabe and Eiwa System Management,Inc.
makes no representations about the suitability of this software for any
purpose. It is provided "AS IS" with NO WARRANTY.
*/
#include "Matrix4.h"
template<class T, class S>
bool equals(T a, S b) {
return fabs(a - b) < 1.0e-5;
}
#ifdef VM_INCLUDE_NAMESPACE
using namespace kh_vecmath;
#endif
template<class T>
void f(T) {
/*
* constructors
*/
Matrix4<T> m1(1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16);
T array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
Matrix4<T> m2(array);
#ifdef VM_INCLUDE_CONVERSION_FROM_2DARRAY
T array2[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
Matrix4<T> m3(array2);
#else
Matrix4<T> m3(m2);
#endif
int k = 0;
for (unsigned i = 0; i < Matrix4<T>::DIMENSION; i++) {
for (unsigned j = 0; j < Matrix4<T>::DIMENSION; j++) {
k++;
#ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR
assert(m1(i,j) == k);
assert(m2(i,j) == k);
assert(m3(i,j) == k);
#endif
assert(m1.getElement(i,j) == k);
assert(m2.getElement(i,j) == k);
assert(m3.getElement(i,j) == k);
}
}
assert(m1 == m2);
assert(m1 == m3);
/*
* set/get row/column
*/
m1.setIdentity();
m1.setScale(2);
assert(m1 == Matrix4<T>(2,0,0,0,
0,2,0,0,
0,0,2,0,
0,0,0,1));
#ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR
for (unsigned i = 0; i < 4; i++)
for (unsigned j = 0; j < 4; j++)
m1(i,j) = 10*i + j;
for (unsigned ii = 0; ii < 4; ii++)
for (unsigned j = 0; j < 4; j++)
assert(10*ii + j == m1(ii,j));
#endif
for (unsigned i2 = 0; i2 < 4; i2++)
for (unsigned j = 0; j < 4; j++)
m1.setElement(i2,j,10*i2 + j);
for (unsigned i3 = 0; i3 < 4; i3++)
for (unsigned j = 0; j < 4; j++)
assert(10*i3 + j == m1.getElement(i3,j));
for (unsigned i4 = 0; i4 < 4; i4++) {
Vector4<T> v1(10*i4,6*i4,i4,17*i4);
Vector4<T> v2;
m1.setRow(i4, v1);
m1.getRow(i4, &v2);
assert(v1 == v2);
}
for (unsigned i5 = 0; i5 < 4; i5++) {
const T t[] = { 1, 2, 3, 4 };
T s[4];
m1.setRow(i5, t);
m1.getRow(i5, s);
for (unsigned j = 0; j < 4; j ++)
assert(t[j] == s[j]);
}
for (unsigned i6 = 0; i6 < 4; i6++) {
Vector4<T> v1(7*i6,5*i6,i6,13*(-i6));
Vector4<T> v2;
m1.setColumn(i6, v1);
m1.getColumn(i6, &v2);
assert(v1 == v2);
}
for (unsigned i7 = 0; i7 < 4; i7++) {
const T t[] = { 1, 2, 3, 4};
T s[4];
m1.setColumn(i7, t);
m1.getColumn(i7, s);
for (unsigned j = 0; j < 4; j ++)
assert(t[j] == s[j]);
}
/*
* scales
*/
m1.setIdentity();
for (unsigned i8 = 1; i8 < 10; i8++) {
m1.setScale(i8);
T s = m1.getScale();
assert(equals(s, i8));
}
/*
* add/sub
*/
m1.set(1, 2, 3, 4,
5, 6, 7, 8,
9, 10,11,12,
13,14,15,16);
m2.add(10, m1);
m2.sub(10);
assert(m1 == m2);
/**
* negate
*/
m1.set(1, 2, 3, 10,
4, 5, 6, 11,
2, 5, 1, 100,
9, 3, 4, 12);
m2.negate(m1);
m3.add(m1, m2);
assert(m3 == Matrix4<T>(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0));
/*
* transpose
*/
m2.transpose(m1);
m2.transpose();
assert(m1 == m2);
/*
* invert
*/
m2.invert(m1);
m2 *= m1;
#ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR
assert(equals(m2(0,0),1));
assert(equals(m2(0,1),0));
assert(equals(m2(0,2),0));
assert(equals(m2(0,3),0));
assert(equals(m2(1,0),0));
assert(equals(m2(1,1),1));
assert(equals(m2(1,2),0));
assert(equals(m2(1,3),0));
assert(equals(m2(2,0),0));
assert(equals(m2(2,1),0));
assert(equals(m2(2,2),1));
assert(equals(m2(2,3),0));
assert(equals(m2(3,0),0));
assert(equals(m2(3,1),0));
assert(equals(m2(3,2),0));
assert(equals(m2(3,3),1));
#endif
assert(equals(m2.getElement(0,0),1));
assert(equals(m2.getElement(0,1),0));
assert(equals(m2.getElement(0,2),0));
assert(equals(m2.getElement(0,3),0));
assert(equals(m2.getElement(1,0),0));
assert(equals(m2.getElement(1,1),1));
assert(equals(m2.getElement(1,2),0));
assert(equals(m2.getElement(1,3),0));
assert(equals(m2.getElement(2,0),0));
assert(equals(m2.getElement(2,1),0));
assert(equals(m2.getElement(2,2),1));
assert(equals(m2.getElement(2,3),0));
assert(equals(m2.getElement(3,0),0));
assert(equals(m2.getElement(3,1),0));
assert(equals(m2.getElement(3,2),0));
assert(equals(m2.getElement(3,3),1));
}
/**
* test for Matrix3
*/
#ifdef TESTALL
int test_9() {
#else
int main(int, char**) {
#endif
f(1.0);
f(1.0f);
return 0;
}
| 25.811927 | 78 | 0.514484 | nocnokneo |
eccf98c4b906f30bd6d8b9fffa09bea0746e3411 | 796 | cpp | C++ | 367-valid-perfect-square.cpp | nave7693/leetcode | 8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49 | [
"MIT"
] | null | null | null | 367-valid-perfect-square.cpp | nave7693/leetcode | 8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49 | [
"MIT"
] | null | null | null | 367-valid-perfect-square.cpp | nave7693/leetcode | 8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/valid-perfect-square
class Solution {
public:
bool isPerfectSquare(int num) {
if (num <= 1) return true;
int lo = 0, hi = num, mid;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if (mid == num / mid) {
return num % mid == 0;
}
if (mid < (num / mid) && (mid + 1) > num / (mid + 1)) return false;
if (num / mid < mid) {
hi = mid;
} else {
lo = mid + 1;
}
}
return false;
}
};
// Newton's method for sqrt
public boolean isPerfectSquare(int num) {
long x = num;
while (x * x > num) {
x = (x + num / x) >> 1;
}
return x * x == num;
} | 25.677419 | 80 | 0.400754 | nave7693 |
ecd167dd1a10e156556670a46752492f5cad1834 | 2,199 | cpp | C++ | test/ut/core/dependency.cpp | szigetics/di | 48eccb76aee03f0eceafe9bf47a713a8c0e7d810 | [
"BSL-1.0"
] | 531 | 2016-01-28T21:51:28.000Z | 2020-06-23T10:59:52.000Z | test/ut/core/dependency.cpp | szigetics/di | 48eccb76aee03f0eceafe9bf47a713a8c0e7d810 | [
"BSL-1.0"
] | 243 | 2016-02-11T14:28:01.000Z | 2020-06-22T08:53:13.000Z | test/ut/core/dependency.cpp | szigetics/di | 48eccb76aee03f0eceafe9bf47a713a8c0e7d810 | [
"BSL-1.0"
] | 86 | 2016-02-01T21:49:15.000Z | 2020-06-17T14:38:53.000Z | //
// Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "boost/di/core/dependency.hpp"
#include <type_traits>
#include "boost/di/concepts/boundable.hpp"
#include "common/fakes/fake_injector.hpp"
#include "common/fakes/fake_scope.hpp"
namespace core {
test is_dependency_types = [] {
expect(!std::is_base_of<dependency_base, void>::value);
expect(!std::is_base_of<dependency_base, int>::value);
expect(std::is_base_of<dependency_base, dependency<scopes::deduce, int>>::value);
expect(std::is_base_of<dependency_base, dependency<scopes::deduce, double, double>>::value);
};
struct name {};
test types = [] {
using dep = dependency<fake_scope<>, int, double, name>;
expect(std::is_same<fake_scope<>, typename dep::scope>::value);
expect(std::is_same<int, typename dep::expected>::value);
expect(std::is_same<double, typename dep::given>::value);
expect(std::is_same<name, typename dep::name>::value);
};
test def_ctor = [] {
dependency<scopes::deduce, int> dep;
(void)dep;
};
test ctor = [] {
fake_scope<>::ctor_calls() = 0;
dependency<fake_scope<>, int> dep{0};
expect(1 == fake_scope<>::ctor_calls());
};
test named = [] {
using dep1 = dependency<scopes::deduce, int>;
expect(std::is_same<no_name, typename dep1::name>::value);
using dep2 = decltype(dep1{}.named(name{}));
expect(std::is_same<name, typename dep2::name>::value);
};
test in = [] {
using dep1 = dependency<fake_scope<>, int>;
expect(std::is_same<fake_scope<>, typename dep1::scope>::value);
using dep2 = decltype(dep1{}.in(scopes::deduce{}));
expect(std::is_same<scopes::deduce, typename dep2::scope>::value);
};
test to = [] {
using dep1 = dependency<scopes::deduce, int>;
expect(std::is_same<scopes::deduce, typename dep1::scope>::value);
using dep2 = decltype(dep1{}.to(42));
expect(std::is_same<scopes::instance, typename dep2::scope>::value);
expect(std::is_same<int, typename dep2::expected>::value);
expect(std::is_same<int, typename dep2::given>::value);
};
} // namespace core
| 31.414286 | 94 | 0.694407 | szigetics |
ecd81106d621631ba3761125eef1e673f913c0b6 | 1,710 | cpp | C++ | ecs/components/retro_collider_component.cpp | SirJonthe/retro3d | 41e45ce4757c1ae900e6355bce6f3c2066dc2c6f | [
"MIT"
] | 7 | 2020-09-26T11:18:25.000Z | 2021-07-02T15:22:46.000Z | ecs/components/retro_collider_component.cpp | SirJonthe/retro3d | 41e45ce4757c1ae900e6355bce6f3c2066dc2c6f | [
"MIT"
] | null | null | null | ecs/components/retro_collider_component.cpp | SirJonthe/retro3d | 41e45ce4757c1ae900e6355bce6f3c2066dc2c6f | [
"MIT"
] | null | null | null | #include "retro_collider_component.h"
#include "retro_transform_component.h"
#include "../retro_entity.h"
namespace retro3d { retro_register_component(ColliderComponent) }
void retro3d::ColliderComponent::OnSpawn( void )
{
m_collider->AttachTransform(GetObject()->AddComponent<retro3d::TransformComponent>()->GetTransform());
m_reinsert = false;
}
retro3d::ColliderComponent::ColliderComponent( void ) : mtlInherit(this), m_filter_flags(uint64_t(~0)), m_is_static(false), m_reinsert(false)
{
CreateCollider<retro3d::AABBCollider>();
}
retro3d::Collider &retro3d::ColliderComponent::GetCollider( void )
{
return *m_collider.GetShared();
}
const retro3d::Collider &retro3d::ColliderComponent::GetCollider( void ) const
{
return *m_collider.GetShared();
}
uint64_t retro3d::ColliderComponent::GetFilterFlags( void ) const
{
return m_filter_flags;
}
bool retro3d::ColliderComponent::GetFilterFlag(uint32_t flag_index) const
{
return (m_filter_flags & (uint64_t(1) << flag_index)) != 0;
}
void retro3d::ColliderComponent::SetFilterFlags(uint64_t filter_flags)
{
m_filter_flags = filter_flags;
m_reinsert = true;
}
void retro3d::ColliderComponent::SetFilterFlag(uint32_t flag_index, bool state)
{
if (state == true) {
m_filter_flags |= (uint64_t(1) << flag_index);
} else {
m_filter_flags &= ~(uint64_t(1) << flag_index);
}
}
bool retro3d::ColliderComponent::IsStatic( void ) const
{
return m_is_static;
}
void retro3d::ColliderComponent::ToggleStatic( void )
{
m_is_static = !m_is_static;
m_reinsert = true;
}
bool retro3d::ColliderComponent::ShouldReinsert( void ) const
{
return m_reinsert;
}
void retro3d::ColliderComponent::ToggleReinsert( void )
{
m_reinsert = !m_reinsert;
}
| 23.424658 | 141 | 0.759064 | SirJonthe |
ecd991b42bd8b5ad0933d785b68f171d16ca7c8a | 48 | cpp | C++ | 3/TCP Server/TCPServerThread.cpp | ulyanyunakh/operating-systems | edb195c5ff72138f9d3f7b940d7acce507cb69d3 | [
"MIT"
] | null | null | null | 3/TCP Server/TCPServerThread.cpp | ulyanyunakh/operating-systems | edb195c5ff72138f9d3f7b940d7acce507cb69d3 | [
"MIT"
] | null | null | null | 3/TCP Server/TCPServerThread.cpp | ulyanyunakh/operating-systems | edb195c5ff72138f9d3f7b940d7acce507cb69d3 | [
"MIT"
] | null | null | null | #include <iostream>
class TCPServerThread {
}; | 9.6 | 23 | 0.729167 | ulyanyunakh |
ece7f4a7e5cb99752e68904425f0082d058e531e | 11,565 | hpp | C++ | viennashe/simulator_quantity.hpp | viennashe/viennashe-dev | e3b9ba1bd8e5b0e3fa9065b433c7915e073c849a | [
"MIT"
] | 3 | 2020-05-07T14:38:52.000Z | 2021-05-30T09:43:18.000Z | viennashe/simulator_quantity.hpp | viennashe/viennashe-dev | e3b9ba1bd8e5b0e3fa9065b433c7915e073c849a | [
"MIT"
] | 1 | 2021-05-02T13:50:52.000Z | 2021-05-03T03:49:51.000Z | viennashe/simulator_quantity.hpp | viennashe/viennashe-dev | e3b9ba1bd8e5b0e3fa9065b433c7915e073c849a | [
"MIT"
] | 3 | 2020-05-07T14:39:07.000Z | 2021-05-08T12:15:26.000Z | #ifndef VIENNASHE_SIMULATOR_QUANTITY_HPP
#define VIENNASHE_SIMULATOR_QUANTITY_HPP
/* ============================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaSHE - The Vienna Spherical Harmonics Expansion Boltzmann Solver
-----------------
http://viennashe.sourceforge.net/
License: MIT (X11), see file LICENSE in the base directory
=============================================================================== */
/** @file viennashe/simulator_quantity.hpp
@brief Defines a generic simulator quantity for use within the solvers of ViennaSHE
*/
#include <vector>
#include <string>
#include "viennagrid/mesh/mesh.hpp"
#include "viennashe/forwards.h"
namespace viennashe
{
/** @brief Holds a function per quantity, which returns the name of the respective quantity as std::string. */
namespace quantity
{
inline std::string potential() { return "Electrostatic potential"; }
inline std::string electron_density() { return "Electron density"; }
inline std::string hole_density() { return "Hole density"; }
inline std::string density_gradient_electron_correction() { return "DG electron correction potential"; }
inline std::string density_gradient_hole_correction() { return "DG hole correction potential"; }
inline std::string lattice_temperature() { return "Lattice temperature"; }
inline std::string electron_distribution_function() { return "Electron distribution function"; }
inline std::string hole_distribution_function() { return "Hole distribution function"; }
}
/** @brief Common representation of any quantity associated with objects of a certain type.
*
* This is the minimum requirement one can have: Return value for a vertex/cell.
*/
template<typename AssociatedT, typename ValueT = double>
class const_quantity
{
public:
typedef const_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
typedef associated_type access_type;
const_quantity(std::string quan_name,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name),
values_(num_values, default_value) {}
const_quantity(std::string quan_name,
std::vector<ValueT> const & values_array)
: name_(quan_name),
values_(values_array) {}
const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { }
void operator=(self_type const & o) { name_(o.name_); values_(o.values_); }
ValueT get_value (associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
std::string name() const { return name_; }
private:
std::string name_;
std::vector<ValueT> values_;
};
template<typename AssociatedT, typename ValueT = double>
class non_const_quantity
{
public:
typedef non_const_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
non_const_quantity(std::string quan_name,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name), values_(num_values, default_value) {}
non_const_quantity(std::string quan_name,
std::vector<ValueT> const & values_array)
: name_(quan_name), values_(values_array) {}
non_const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { }
void operator=(self_type const & o) { name_(o.name_); values_(o.values_); }
ValueT get_value(associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
void set_value(associated_type const & elem, ValueT value) { values_.at(static_cast<std::size_t>(elem.id().get())) = value; }
std::string name() const { return name_; }
private:
std::string name_;
std::vector<ValueT> values_;
};
template <typename ValueT = double>
struct robin_boundary_coefficients
{
ValueT alpha;
ValueT beta;
};
template<typename AssociatedT, typename ValueT = double>
class unknown_quantity
{
std::size_t get_id(AssociatedT const & elem) const { return static_cast<std::size_t>(elem.id().get()); }
public:
typedef unknown_quantity<AssociatedT, ValueT> self_type;
typedef ValueT value_type;
typedef AssociatedT associated_type;
typedef robin_boundary_coefficients<ValueT> robin_boundary_type;
unknown_quantity() {} // to fulfill default constructible concept!
unknown_quantity(std::string const & quan_name,
equation_id quan_equation,
std::size_t num_values,
value_type default_value = value_type())
: name_(quan_name),
equation_(quan_equation),
values_ (num_values, default_value),
boundary_types_ (num_values, BOUNDARY_NONE),
boundary_values_ (num_values, default_value),
boundary_values_alpha_ (num_values, 0),
defined_but_unknown_mask_(num_values, false),
unknowns_indices_ (num_values, -1),
log_damping_(false)
{}
unknown_quantity(self_type const & o)
: name_(o.name_),
equation_(o.equation_),
values_ (o.values_),
boundary_types_ (o.boundary_types_),
boundary_values_ (o.boundary_values_),
boundary_values_alpha_ (o.boundary_values_alpha_),
defined_but_unknown_mask_(o.defined_but_unknown_mask_),
unknowns_indices_ (o.unknowns_indices_),
log_damping_ (o.log_damping_)
{ }
void operator=(self_type const & o)
{
name_ = o.name_;
equation_ = o.equation_;
values_ = o.values_;
boundary_types_ = o.boundary_types_;
boundary_values_ = o.boundary_values_;
boundary_values_alpha_ = o.boundary_values_alpha_;
defined_but_unknown_mask_= o.defined_but_unknown_mask_;
unknowns_indices_ = o.unknowns_indices_;
log_damping_ = o.log_damping_;
}
std::string get_name() const { return name_; }
equation_id get_equation() const { return equation_; }
ValueT get_value(associated_type const & elem) const { return values_.at(get_id(elem)); }
ValueT at (associated_type const & elem) const { return this->get_value(elem); }
ValueT operator()(associated_type const & elem) const { return this->get_value(elem); }
void set_value(associated_type const & elem, ValueT value) { values_.at(get_id(elem)) = value; }
void set_value(associated_type const & elem, robin_boundary_type value) { (void)elem; (void)value; } //TODO: Fix this rather ugly hack which stems from set_boundary_for_material()
// Dirichlet and Neumann
ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(get_id(elem)); }
void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(get_id(elem)) = value; }
// Robin boundary conditions
/** @brief Returns the coefficients alpha and beta for the Robin boundary condition du/dn = beta - alpha u
*
*
* @return A pair holding (beta, alpha). .first returns beta, .second returns alpha
*/
robin_boundary_type get_boundary_values(associated_type const & elem) const
{
robin_boundary_type ret;
ret.alpha = boundary_values_alpha_.at(get_id(elem));
ret.beta = boundary_values_.at(get_id(elem));
return ret;
}
/** @brief Setter function for Robin boundary conditions.
*
* Note that this is an overload rather than a new function 'set_boundary_values' in order to have a uniform setter interface.
*/
void set_boundary_value(associated_type const & elem, robin_boundary_type const & values)
{
boundary_values_.at(get_id(elem)) = values.beta;
boundary_values_alpha_.at(get_id(elem)) = values.alpha;
}
boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(get_id(elem)); }
void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(get_id(elem)) = value; }
bool get_unknown_mask(associated_type const & elem) const { return defined_but_unknown_mask_.at(get_id(elem)); }
void set_unknown_mask(associated_type const & elem, bool value) { defined_but_unknown_mask_.at(get_id(elem)) = value; }
long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(get_id(elem)); }
void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(get_id(elem)) = value; }
std::size_t get_unknown_num() const
{
std::size_t num = 0;
for (std::size_t i=0; i<unknowns_indices_.size(); ++i)
{
if (unknowns_indices_[i] >= 0)
++num;
}
return num;
}
// possible design flaws:
std::vector<ValueT> const & values() const { return values_; }
std::vector<boundary_type_id> const & boundary_types() const { return boundary_types_; }
std::vector<ValueT> const & boundary_values() const { return boundary_values_; }
std::vector<bool> const & defined_but_unknown_mask() const { return defined_but_unknown_mask_; }
std::vector<long> const & unknowns_indices() const { return unknowns_indices_; }
bool get_logarithmic_damping() const { return log_damping_; }
void set_logarithmic_damping(bool b) { log_damping_ = b; }
private:
std::string name_;
equation_id equation_;
std::vector<ValueT> values_;
std::vector<boundary_type_id> boundary_types_;
std::vector<ValueT> boundary_values_;
std::vector<ValueT> boundary_values_alpha_;
std::vector<bool> defined_but_unknown_mask_;
std::vector<long> unknowns_indices_;
bool log_damping_;
};
} //namespace viennashe
#endif
| 43.477444 | 187 | 0.613921 | viennashe |
ece85c79584b94746d009ef9a4923fa34c7d9fdc | 359 | hpp | C++ | src/ChipInfo.hpp | mvadu/CetusBedHeater | 330d440260e72e585856c6f3f96e36664344240a | [
"MIT"
] | null | null | null | src/ChipInfo.hpp | mvadu/CetusBedHeater | 330d440260e72e585856c6f3f96e36664344240a | [
"MIT"
] | null | null | null | src/ChipInfo.hpp | mvadu/CetusBedHeater | 330d440260e72e585856c6f3f96e36664344240a | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "soc/efuse_reg.h"
#include <esp_spi_flash.h>
#include <esp_system.h>
#include <rom/rtc.h>
class ChipInfo
{
public:
ChipInfo();
uint8_t reason;
const char *sdkVersion;
uint8_t chipVersion;
uint8_t coreCount;
uint8_t featureBT;
uint8_t featureBLE;
uint8_t featureWiFi;
bool internalFlash;
uint8_t flashSize;
}; | 17.95 | 26 | 0.738162 | mvadu |
ecec6e1d1f04529ee1678ea0313eb189403b76e8 | 86,956 | cc | C++ | neb/src/callbacks.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | neb/src/callbacks.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | neb/src/callbacks.cc | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2009-2017 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : [email protected]
*/
#include <cstdlib>
#include <ctime>
#include <memory>
#include <QDomDocument>
#include <QDomElement>
#include <QString>
#include <QStringList>
#include <set>
#include <unistd.h>
#include "com/centreon/broker/config/applier/state.hh"
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/neb/callback.hh"
#include "com/centreon/broker/neb/callbacks.hh"
#include "com/centreon/broker/neb/events.hh"
#include "com/centreon/broker/neb/initial.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/broker/neb/set_log_data.hh"
#include "com/centreon/broker/neb/statistics/generator.hh"
#include "com/centreon/engine/broker.hh"
#include "com/centreon/engine/globals.hh"
#include "com/centreon/engine/nebcallbacks.hh"
#include "com/centreon/engine/nebstructs.hh"
#include "com/centreon/engine/hostdependency.hh"
#include "com/centreon/engine/servicedependency.hh"
#include "com/centreon/engine/comment.hh"
#include "com/centreon/engine/hostgroup.hh"
#include "com/centreon/engine/servicegroup.hh"
#include "com/centreon/engine/events/timed_event.hh"
#include "com/centreon/engine/events/defines.hh"
using namespace com::centreon::broker;
// List of Nagios modules.
extern nebmodule* neb_module_list;
// Acknowledgement list.
std::map<std::pair<unsigned int, unsigned int>, neb::acknowledgement>
neb::gl_acknowledgements;
// Downtime list.
struct private_downtime_params {
bool cancelled;
time_t deletion_time;
time_t end_time;
bool started;
time_t start_time;
};
// Unstarted downtimes.
static umap<unsigned int, private_downtime_params> downtimes;
// Load flags.
int neb::gl_mod_flags(0);
// Module handle.
void* neb::gl_mod_handle(nullptr);
// List of common callbacks.
static struct {
unsigned int macro;
int (* callback)(int, void*);
} const gl_callbacks[] = {
{ NEBCALLBACK_ACKNOWLEDGEMENT_DATA, &neb::callback_acknowledgement },
{ NEBCALLBACK_COMMENT_DATA, &neb::callback_comment },
{ NEBCALLBACK_DOWNTIME_DATA, &neb::callback_downtime },
{ NEBCALLBACK_EVENT_HANDLER_DATA, &neb::callback_event_handler },
{ NEBCALLBACK_EXTERNAL_COMMAND_DATA, &neb::callback_external_command },
{ NEBCALLBACK_FLAPPING_DATA, &neb::callback_flapping_status },
{ NEBCALLBACK_HOST_CHECK_DATA, &neb::callback_host_check },
{ NEBCALLBACK_HOST_STATUS_DATA, &neb::callback_host_status },
{ NEBCALLBACK_PROGRAM_STATUS_DATA, &neb::callback_program_status },
{ NEBCALLBACK_SERVICE_CHECK_DATA, &neb::callback_service_check },
{ NEBCALLBACK_SERVICE_STATUS_DATA, &neb::callback_service_status }
};
// List of Engine-specific callbacks.
static struct {
unsigned int macro;
int (* callback)(int, void*);
} const gl_engine_callbacks[] = {
{ NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA, &neb::callback_dependency },
{ NEBCALLBACK_ADAPTIVE_HOST_DATA, &neb::callback_host },
{ NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &neb::callback_service },
{ NEBCALLBACK_CUSTOM_VARIABLE_DATA, &neb::callback_custom_variable },
{ NEBCALLBACK_GROUP_DATA, &neb::callback_group },
{ NEBCALLBACK_GROUP_MEMBER_DATA, &neb::callback_group_member },
{ NEBCALLBACK_MODULE_DATA, &neb::callback_module },
{ NEBCALLBACK_RELATION_DATA, &neb::callback_relation }
};
// Registered callbacks.
std::list<std::shared_ptr<neb::callback> > neb::gl_registered_callbacks;
// External function to get program version.
extern "C" {
char const* get_program_version();
}
// Statistics generator.
static neb::statistics::generator gl_generator;
extern "C" void event_statistics(void* args) {
(void)args;
try {
gl_generator.run();
}
catch (std::exception const& e) {
logging::error(logging::medium)
<< "stats: error occurred while generating statistics event: "
<< e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return ;
}
/**
* @brief Function that process acknowledgement data.
*
* This function is called by Nagios when some acknowledgement data are
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_ACKNOWLEDGEMENT_DATA).
* @param[in] data A pointer to a nebstruct_acknowledgement_data
* containing the acknowledgement data.
*
* @return 0 on success.
*/
int neb::callback_acknowledgement(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating acknowledgement event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_acknowledgement_data const* ack_data;
std::shared_ptr<neb::acknowledgement> ack(new neb::acknowledgement);
// Fill output var.
ack_data = static_cast<nebstruct_acknowledgement_data*>(data);
ack->acknowledgement_type = ack_data->acknowledgement_type;
if (ack_data->author_name)
ack->author = ack_data->author_name;
if (ack_data->comment_data)
ack->comment = ack_data->comment_data;
ack->entry_time = time(nullptr);
if (!ack_data->host_name)
throw (exceptions::msg() << "unnamed host");
if (ack_data->service_description) {
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
ack_data->host_name,
ack_data->service_description);
ack->host_id = p.first;
ack->service_id = p.second;
if (!ack->host_id || !ack->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< ack_data->host_name << "', '"
<< ack_data->service_description << "')");
}
else {
ack->host_id = engine::get_host_id(ack_data->host_name);
if (ack->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< ack_data->host_name << "'");
}
ack->poller_id = config::applier::state::instance().poller_id();
ack->is_sticky = ack_data->is_sticky;
ack->notify_contacts = ack_data->notify_contacts;
ack->persistent_comment = ack_data->persistent_comment;
ack->state = ack_data->state;
gl_acknowledgements[std::make_pair(ack->host_id, ack->service_id)]
= *ack;
// Send event.
gl_publisher.write(ack);
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating acknowledgement event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process comment data.
*
* This function is called by Nagios when some comment data are available.
*
* @param[in] callback_type Type of the callback (NEBCALLBACK_COMMENT_DATA).
* @param[in] data A pointer to a nebstruct_comment_data containing
* the comment data.
*
* @return 0 on success.
*/
int neb::callback_comment(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating comment event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_comment_data const* comment_data;
std::shared_ptr<neb::comment> comment(new neb::comment);
// Fill output var.
comment_data = static_cast<nebstruct_comment_data*>(data);
if (comment_data->author_name)
comment->author = comment_data->author_name;
if (comment_data->comment_data)
comment->data = comment_data->comment_data;
comment->comment_type = comment_data->comment_type;
if (NEBTYPE_COMMENT_DELETE == comment_data->type)
comment->deletion_time = time(nullptr);
comment->entry_time = comment_data->entry_time;
comment->entry_type = comment_data->entry_type;
comment->expire_time = comment_data->expire_time;
comment->expires = comment_data->expires;
if (!comment_data->host_name)
throw (exceptions::msg() << "unnamed host");
if (comment_data->service_description) {
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
comment_data->host_name,
comment_data->service_description);
comment->host_id = p.first;
comment->service_id = p.second;
if (!comment->host_id || !comment->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< comment_data->host_name << "', '"
<< comment_data->service_description << "')");
}
else {
comment->host_id = engine::get_host_id(comment_data->host_name);
if (comment->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< comment_data->host_name << "'");
}
comment->poller_id = config::applier::state::instance().poller_id();
comment->internal_id = comment_data->comment_id;
comment->persistent = comment_data->persistent;
comment->source = comment_data->source;
// Send event.
gl_publisher.write(comment);
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating comment event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process custom variable data.
*
* This function is called by Engine when some custom variable data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_CUSTOMVARIABLE_DATA).
* @param[in] data Pointer to a nebstruct_custom_variable_data
* containing the custom variable data.
*
* @return 0 on success.
*/
int neb::callback_custom_variable(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating custom variable event";
(void)callback_type;
try {
// Input variable.
nebstruct_custom_variable_data const*
cvar(static_cast<nebstruct_custom_variable_data*>(data));
if (cvar && cvar->var_name && cvar->var_value) {
// Host custom variable.
if (NEBTYPE_HOSTCUSTOMVARIABLE_ADD == cvar->type) {
engine::host* hst(static_cast<engine::host*>(cvar->object_ptr));
if (hst && !hst->get_name().empty()) {
// Fill custom variable event.
uint64_t host_id = engine::get_host_id(hst->get_name());
if (host_id != 0) {
std::shared_ptr<custom_variable>
new_cvar(new custom_variable);
new_cvar->enabled = true;
new_cvar->host_id = host_id;
new_cvar->modified = false;
new_cvar->name = cvar->var_name;
new_cvar->var_type = 0;
new_cvar->update_time = cvar->timestamp.tv_sec;
new_cvar->value = cvar->var_value;
new_cvar->default_value = cvar->var_value;
// Send custom variable event.
logging::info(logging::low)
<< "callbacks: new custom variable '" << new_cvar->name
<< "' on host " << new_cvar->host_id;
neb::gl_publisher.write(new_cvar);
}
}
}
else if (NEBTYPE_HOSTCUSTOMVARIABLE_DELETE == cvar->type) {
engine::host* hst(static_cast<engine::host*>(cvar->object_ptr));
if (hst && !hst->get_name().empty()) {
unsigned int host_id = engine::get_host_id(hst->get_name());
if (host_id != 0) {
std::shared_ptr<custom_variable>
old_cvar(new custom_variable);
old_cvar->enabled = false;
old_cvar->host_id = host_id;
old_cvar->name = cvar->var_name;
old_cvar->var_type = 0;
old_cvar->update_time = cvar->timestamp.tv_sec;
// Send custom variable event.
logging::info(logging::low)
<< "callbacks: deleted custom variable '"
<< old_cvar->name << "' on host '" << old_cvar->host_id;
neb::gl_publisher.write(old_cvar);
}
}
}
// Service custom variable.
else if (NEBTYPE_SERVICECUSTOMVARIABLE_ADD == cvar->type) {
engine::service* svc{static_cast<engine::service*>(cvar->object_ptr)};
if (svc && !svc->get_description().empty() && !svc->get_hostname().empty()) {
// Fill custom variable event.
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
svc->get_hostname(),
svc->get_description());
if (p.first && p.second) {
std::shared_ptr<custom_variable>
new_cvar(new custom_variable);
new_cvar->enabled = true;
new_cvar->host_id = p.first;
new_cvar->modified = false;
new_cvar->name = cvar->var_name;
new_cvar->service_id = p.second;
new_cvar->var_type = 1;
new_cvar->update_time = cvar->timestamp.tv_sec;
new_cvar->value = cvar->var_value;
new_cvar->default_value = cvar->var_value;
// Send custom variable event.
logging::info(logging::low)
<< "callbacks: new custom variable '" << new_cvar->name
<< "' on service (" << new_cvar->host_id << ", "
<< new_cvar->service_id << ")";
neb::gl_publisher.write(new_cvar);
}
}
}
else if (NEBTYPE_SERVICECUSTOMVARIABLE_DELETE == cvar->type) {
engine::service* svc{static_cast<engine::service*>(cvar->object_ptr)};
if (svc
&& !svc->get_description().empty()
&& !svc->get_hostname().empty()) {
std::pair<uint64_t, uint64_t> p{engine::get_host_and_service_id(
svc->get_hostname(),
svc->get_description())};
if (p.first && p.second) {
std::shared_ptr<custom_variable>
old_cvar(new custom_variable);
old_cvar->enabled = false;
old_cvar->host_id = p.first;
old_cvar->modified = true;
old_cvar->name = cvar->var_name;
old_cvar->service_id = p.second;
old_cvar->var_type = 1;
old_cvar->update_time = cvar->timestamp.tv_sec;
// Send custom variable event.
logging::info(logging::low)
<< "callbacks: deleted custom variable '" << old_cvar->name
<< "' on service (" << old_cvar->host_id << ", "
<< old_cvar->service_id << ")";
neb::gl_publisher.write(old_cvar);
}
}
}
}
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process dependency data.
*
* This function is called by Centreon Engine when some dependency data
* is available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA).
* @param[in] data A pointer to a
* nebstruct_adaptive_dependency_data
* containing the dependency data.
*
* @return 0 on success.
*/
int neb::callback_dependency(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating dependency event";
(void)callback_type;
try {
// Input variables.
nebstruct_adaptive_dependency_data*
nsadd(static_cast<nebstruct_adaptive_dependency_data*>(data));
// Host dependency.
if ((NEBTYPE_HOSTDEPENDENCY_ADD == nsadd->type)
|| (NEBTYPE_HOSTDEPENDENCY_UPDATE == nsadd->type)
|| (NEBTYPE_HOSTDEPENDENCY_DELETE == nsadd->type)) {
// Find IDs.
uint64_t host_id;
uint64_t dep_host_id;
engine::hostdependency*
dep(static_cast<engine::hostdependency*>(nsadd->object_ptr));
if (!dep->get_hostname().empty()) {
host_id = engine::get_host_id(dep->get_hostname());
}
else {
logging::error(logging::medium)
<< "callbacks: dependency callback called without "
<< "valid host";
host_id = 0;
}
if (!dep->get_dependent_hostname().empty()) {
dep_host_id = engine::get_host_id(dep->get_dependent_hostname());
}
else {
logging::error(logging::medium)
<< "callbacks: dependency callback called without "
<< "valid dependent host";
dep_host_id = 0;
}
// Generate service dependency event.
std::shared_ptr<host_dependency>
hst_dep(new host_dependency);
hst_dep->host_id = host_id;
hst_dep->dependent_host_id = dep_host_id;
hst_dep->enabled = (nsadd->type != NEBTYPE_HOSTDEPENDENCY_DELETE);
if (!dep->get_dependency_period().empty())
hst_dep->dependency_period = QString(dep->get_dependency_period().c_str());
{
QString options;
if (dep->get_fail_on_down())
options.append("d");
if (dep->get_fail_on_up())
options.append("o");
if (dep->get_fail_on_pending())
options.append("p");
if (dep->get_fail_on_unreachable())
options.append("u");
if (dep->get_dependency_type() == engine::dependency::notification)
hst_dep->notification_failure_options = options;
else if (dep->get_dependency_type() == engine::dependency::execution)
hst_dep->execution_failure_options = options;
}
hst_dep->inherits_parent = dep->get_inherits_parent();
logging::info(logging::low) << "callbacks: host " << dep_host_id
<< " depends on host " << host_id;
// Publish dependency event.
neb::gl_publisher.write(hst_dep);
}
// Service dependency.
else if ((NEBTYPE_SERVICEDEPENDENCY_ADD == nsadd->type)
|| (NEBTYPE_SERVICEDEPENDENCY_UPDATE == nsadd->type)
|| (NEBTYPE_SERVICEDEPENDENCY_DELETE == nsadd->type)) {
// Find IDs.
std::pair<uint64_t, uint64_t> ids;
std::pair<uint64_t, uint64_t> dep_ids;
engine::servicedependency*
dep(static_cast<engine::servicedependency*>(nsadd->object_ptr));
if (!dep->get_hostname().empty() && !dep->get_service_description().empty()) {
ids = engine::get_host_and_service_id(
dep->get_hostname(),
dep->get_service_description());
}
else {
logging::error(logging::medium)
<< "callbacks: dependency callback called without "
<< "valid service";
ids.first = 0;
ids.second = 0;
}
if (!dep->get_dependent_hostname().empty()
&& !dep->get_dependent_service_description().empty()) {
dep_ids = engine::get_host_and_service_id(
dep->get_hostname(),
dep->get_service_description());
}
else {
logging::error(logging::medium)
<< "callbacks: dependency callback called without "
<< "valid dependent service";
dep_ids.first = 0;
dep_ids.second = 0;
}
// Generate service dependency event.
std::shared_ptr<service_dependency>
svc_dep(new service_dependency);
svc_dep->host_id = ids.first;
svc_dep->service_id = ids.second;
svc_dep->dependent_host_id = dep_ids.first;
svc_dep->dependent_service_id = dep_ids.second;
svc_dep->enabled
= (nsadd->type != NEBTYPE_SERVICEDEPENDENCY_DELETE);
if (!dep->get_dependency_period().empty())
svc_dep->dependency_period = QString(dep->get_dependency_period().c_str());
{
QString options;
if (dep->get_fail_on_critical())
options.append("c");
if (dep->get_fail_on_ok())
options.append("o");
if (dep->get_fail_on_pending())
options.append("p");
if (dep->get_fail_on_unknown())
options.append("u");
if (dep->get_fail_on_warning())
options.append("w");
if (dep->get_dependency_type() == engine::dependency::notification)
svc_dep->notification_failure_options = options;
else if (dep->get_dependency_type() == engine::dependency::execution)
svc_dep->execution_failure_options = options;
}
svc_dep->inherits_parent = dep->get_inherits_parent();
logging::info(logging::low) << "callbacks: service ("
<< dep_ids.first << ", " << dep_ids.second
<< ") depends on service (" << ids.first << ", " << ids.second
<< ")";
// Publish dependency event.
neb::gl_publisher.write(svc_dep);
}
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process downtime data.
*
* This function is called by Nagios when some downtime data are available.
*
* @param[in] callback_type Type of the callback (NEBCALLBACK_DOWNTIME_DATA).
* @param[in] data A pointer to a nebstruct_downtime_data containing
* the downtime data.
*
* @return 0 on success.
*/
int neb::callback_downtime(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating downtime event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_downtime_data const* downtime_data;
std::shared_ptr<neb::downtime> downtime(new neb::downtime);
// Fill output var.
downtime_data = static_cast<nebstruct_downtime_data*>(data);
if (downtime_data->author_name)
downtime->author = downtime_data->author_name;
if (downtime_data->comment_data)
downtime->comment = downtime_data->comment_data;
downtime->downtime_type = downtime_data->downtime_type;
downtime->duration = downtime_data->duration;
downtime->end_time = downtime_data->end_time;
downtime->entry_time = downtime_data->entry_time;
downtime->fixed = downtime_data->fixed;
if (!downtime_data->host_name)
throw (exceptions::msg() << "unnamed host");
if (downtime_data->service_description) {
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
downtime_data->host_name,
downtime_data->service_description);
downtime->host_id = p.first;
downtime->service_id = p.second;
if (!downtime->host_id || !downtime->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< downtime_data->host_name << "', '"
<< downtime_data->service_description << "')");
}
else {
downtime->host_id = engine::get_host_id(downtime_data->host_name);
if (downtime->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< downtime_data->host_name << "'");
}
downtime->poller_id
= config::applier::state::instance().poller_id();
downtime->internal_id = downtime_data->downtime_id;
downtime->start_time = downtime_data->start_time;
downtime->triggered_by = downtime_data->triggered_by;
private_downtime_params& params(downtimes[downtime->internal_id]);
if ((NEBTYPE_DOWNTIME_ADD == downtime_data->type)
|| (NEBTYPE_DOWNTIME_LOAD == downtime_data->type)) {
params.cancelled = false;
params.deletion_time = -1;
params.end_time = -1;
params.started = false;
params.start_time = -1;
}
else if (NEBTYPE_DOWNTIME_START == downtime_data->type) {
params.started = true;
params.start_time = downtime_data->timestamp.tv_sec;
}
else if (NEBTYPE_DOWNTIME_STOP == downtime_data->type) {
if (NEBATTR_DOWNTIME_STOP_CANCELLED == downtime_data->attr)
params.cancelled = true;
params.end_time = downtime_data->timestamp.tv_sec;
}
else if (NEBTYPE_DOWNTIME_DELETE == downtime_data->type) {
if (!params.started)
params.cancelled = true;
params.deletion_time = downtime_data->timestamp.tv_sec;
}
downtime->actual_start_time = params.start_time;
downtime->actual_end_time = params.end_time;
downtime->deletion_time = params.deletion_time;
downtime->was_cancelled = params.cancelled;
downtime->was_started = params.started;
if (NEBTYPE_DOWNTIME_DELETE == downtime_data->type)
downtimes.erase(downtime->internal_id);
// Send event.
gl_publisher.write(downtime);
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
"generating downtime event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process event handler data.
*
* This function is called by Nagios when some event handler data are
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_EVENT_HANDLER_DATA).
* @param[in] data A pointer to a nebstruct_event_handler_data
* containing the event handler data.
*
* @return 0 on success.
*/
int neb::callback_event_handler(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating event handler event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_event_handler_data const* event_handler_data;
std::shared_ptr<neb::event_handler>
event_handler(new neb::event_handler);
// Fill output var.
event_handler_data = static_cast<nebstruct_event_handler_data*>(data);
if (event_handler_data->command_args)
event_handler->command_args = event_handler_data->command_args;
if (event_handler_data->command_line)
event_handler->command_line = event_handler_data->command_line;
event_handler->early_timeout = event_handler_data->early_timeout;
event_handler->end_time = event_handler_data->end_time.tv_sec;
event_handler->execution_time = event_handler_data->execution_time;
if (!event_handler_data->host_name)
throw (exceptions::msg() << "unnamed host");
if (event_handler_data->service_description) {
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
event_handler_data->host_name,
event_handler_data->service_description);
event_handler->host_id = p.first;
event_handler->service_id = p.second;
if (!event_handler->host_id || !event_handler->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< event_handler_data->host_name << "', '"
<< event_handler_data->service_description << "')");
}
else {
event_handler->host_id = engine::get_host_id(
event_handler_data->host_name);
if (event_handler->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< event_handler_data->host_name << "'");
}
if (event_handler_data->output)
event_handler->output = event_handler_data->output;
event_handler->return_code = event_handler_data->return_code;
event_handler->start_time = event_handler_data->start_time.tv_sec;
event_handler->state = event_handler_data->state;
event_handler->state_type = event_handler_data->state_type;
event_handler->timeout = event_handler_data->timeout;
event_handler->handler_type = event_handler_data->eventhandler_type;
// Send event.
gl_publisher.write(event_handler);
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating event handler event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process external commands.
*
* This function is called by the monitoring engine when some external
* command is received.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_EXTERNALCOMMAND_DATA).
* @param[in] data A pointer to a nebstruct_externalcommand_data
* containing the external command data.
*
* @return 0 on success.
*/
int neb::callback_external_command(int callback_type, void* data) {
// Log message.
logging::debug(logging::low) << "callbacks: external command data";
(void)callback_type;
nebstruct_external_command_data* necd(
static_cast<nebstruct_external_command_data*>(data));
if (necd && (necd->type == NEBTYPE_EXTERNALCOMMAND_START)) {
try {
if (necd->command_type == CMD_CHANGE_CUSTOM_HOST_VAR) {
logging::info(logging::medium)
<< "callbacks: generating host custom variable update event";
// Split argument string.
if (necd->command_args) {
QStringList l(QString(necd->command_args).split(';'));
if (l.size() != 3)
logging::error(logging::medium)
<< "callbacks: invalid host custom variable command";
else {
QStringList::iterator it(l.begin());
QString host(*it++);
QString var_name(*it++);
QString var_value(*it);
// Find host ID.
unsigned int host_id = engine::get_host_id(
host.toStdString().c_str());
if (host_id != 0) {
// Fill custom variable.
std::shared_ptr<neb::custom_variable_status>
cvs(new neb::custom_variable_status);
cvs->host_id = host_id;
cvs->modified = true;
cvs->name = var_name;
cvs->service_id = 0;
cvs->update_time = necd->timestamp.tv_sec;
cvs->value = var_value;
// Send event.
gl_publisher.write(cvs);
}
}
}
}
else if (necd->command_type == CMD_CHANGE_CUSTOM_SVC_VAR) {
logging::info(logging::medium)
<< "callbacks: generating service custom variable update event";
// Split argument string.
if (necd->command_args) {
QStringList l(QString(necd->command_args).split(';'));
if (l.size() != 4)
logging::error(logging::medium)
<< "callbacks: invalid service custom variable command";
else {
QStringList::iterator it(l.begin());
QString host(*it++);
QString service(*it++);
QString var_name(*it++);
QString var_value(*it);
// Find host/service IDs.
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
host.toStdString().c_str(),
service.toStdString().c_str());
if (p.first && p.second) {
// Fill custom variable.
std::shared_ptr<neb::custom_variable_status> cvs(
new neb::custom_variable_status);
cvs->host_id = p.first;
cvs->modified = true;
cvs->name = var_name;
cvs->service_id = p.second;
cvs->update_time = necd->timestamp.tv_sec;
cvs->value = var_value;
// Send event.
gl_publisher.write(cvs);
}
}
}
}
}
// Avoid exception propagation in C code.
catch (...) {}
}
return 0;
}
/**
* @brief Function that process flapping status data.
*
* This function is called by Nagios when some flapping status data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_FLAPPING_DATA).
* @param[in] data A pointer to a nebstruct_flapping_data
* containing the flapping status data.
*
* @return 0 on success.
*/
int neb::callback_flapping_status(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating flapping event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_flapping_data const* flapping_data;
std::shared_ptr<neb::flapping_status> flapping_status(new neb::flapping_status);
// Fill output var.
flapping_data = static_cast<nebstruct_flapping_data*>(data);
flapping_status->event_time = flapping_data->timestamp.tv_sec;
flapping_status->event_type = flapping_data->type;
flapping_status->high_threshold = flapping_data->high_threshold;
if (!flapping_data->host_name)
throw (exceptions::msg() << "unnamed host");
if (flapping_data->service_description) {
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
flapping_data->host_name,
flapping_data->service_description);
flapping_status->host_id = p.first;
flapping_status->service_id = p.second;
if (!flapping_status->host_id || !flapping_status->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< flapping_data->host_name << "', '"
<< flapping_data->service_description << "')");
}
else {
flapping_status->host_id = engine::get_host_id(flapping_data->host_name);
if (flapping_status->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< flapping_data->host_name << "'");
}
flapping_status->low_threshold = flapping_data->low_threshold;
flapping_status->percent_state_change = flapping_data->percent_change;
// flapping_status->reason_type = XXX;
flapping_status->flapping_type = flapping_data->flapping_type;
// Send event.
gl_publisher.write(flapping_status);
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
"generating flapping event: " << e.what();
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process group data.
*
* This function is called by Engine when some group data is available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_GROUP_DATA).
* @param[in] data Pointer to a nebstruct_group_data
* containing the group data.
*
* @return 0 on success.
*/
int neb::callback_group(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating group event";
(void)callback_type;
try {
// Input variable.
nebstruct_group_data const*
group_data(static_cast<nebstruct_group_data*>(data));
// Host group.
if ((NEBTYPE_HOSTGROUP_ADD == group_data->type)
|| (NEBTYPE_HOSTGROUP_UPDATE == group_data->type)
|| (NEBTYPE_HOSTGROUP_DELETE == group_data->type)) {
engine::hostgroup const*
host_group(static_cast<engine::hostgroup*>(group_data->object_ptr));
if (!host_group->get_group_name().empty()) {
std::shared_ptr<neb::host_group> new_hg(new neb::host_group);
new_hg->poller_id
= config::applier::state::instance().poller_id();
new_hg->id = host_group->get_id();
new_hg->enabled
= (group_data->type != NEBTYPE_HOSTGROUP_DELETE
&& !host_group->members.empty());
new_hg->name = host_group->get_group_name().c_str();
// Send host group event.
if (new_hg->id) {
logging::info(logging::low) << "callbacks: new host group "
<< new_hg->id << " ('" << new_hg->name << "') on instance "
<< new_hg->poller_id;
neb::gl_publisher.write(new_hg);
}
}
}
// Service group.
else if ((NEBTYPE_SERVICEGROUP_ADD == group_data->type)
|| (NEBTYPE_SERVICEGROUP_UPDATE == group_data->type)
|| (NEBTYPE_SERVICEGROUP_DELETE == group_data->type)) {
engine::servicegroup const*
service_group(static_cast<engine::servicegroup*>(group_data->object_ptr));
if (!service_group->get_group_name().empty()) {
std::shared_ptr<neb::service_group>
new_sg(new neb::service_group);
new_sg->poller_id
= config::applier::state::instance().poller_id();
new_sg->id = service_group->get_id();
new_sg->enabled
= (group_data->type != NEBTYPE_SERVICEGROUP_DELETE
&& !service_group->members.empty());
new_sg->name = QString(service_group->get_group_name().c_str());
// Send service group event.
if (new_sg->id) {
logging::info(logging::low) << "callbacks:: new service group "
<< new_sg->id << " ('" << new_sg->name << "') on instance "
<< new_sg->poller_id;
neb::gl_publisher.write(new_sg);
}
}
}
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process group membership.
*
* This function is called by Engine when some group membership data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_GROUPMEMBER_DATA).
* @param[in] data Pointer to a nebstruct_group_member_data
* containing membership data.
*
* @return 0 on success.
*/
int neb::callback_group_member(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating group member event";
(void)callback_type;
try {
// Input variable.
nebstruct_group_member_data const*
member_data(static_cast<nebstruct_group_member_data*>(data));
// Host group member.
if ((member_data->type == NEBTYPE_HOSTGROUPMEMBER_ADD)
|| (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE)) {
engine::host const*
hst(static_cast<engine::host*>(member_data->object_ptr));
engine::hostgroup const*
hg(static_cast<engine::hostgroup*>(member_data->group_ptr));
if (!hst->get_name().empty() && !hg->get_group_name().empty()) {
// Output variable.
std::shared_ptr<neb::host_group_member>
hgm(new neb::host_group_member);
hgm->group_id = hg->get_id();
hgm->group_name = QString(hg->get_group_name().c_str());
hgm->poller_id = config::applier::state::instance().poller_id();
unsigned int host_id = engine::get_host_id(hst->get_name());
if (host_id != 0 && hgm->group_id != 0) {
hgm->host_id = host_id;
if (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE) {
logging::info(logging::low) << "callbacks: host "
<< hgm->host_id << " is not a member of group "
<< hgm->group_id << " on instance " << hgm->poller_id
<< " anymore";
hgm->enabled = false;
}
else {
logging::info(logging::low) << "callbacks: host "
<< hgm->host_id << " is a member of group "
<< hgm->group_id << " on instance " << hgm->poller_id;
hgm->enabled = true;
}
// Send host group member event.
if (hgm->host_id && hgm->group_id)
neb::gl_publisher.write(hgm);
}
}
}
// Service group member.
else if ((member_data->type == NEBTYPE_SERVICEGROUPMEMBER_ADD)
|| (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE)) {
engine::service const*
svc(static_cast<engine::service*>(member_data->object_ptr));
engine::servicegroup const*
sg(static_cast<engine::servicegroup*>(member_data->group_ptr));
if (!svc->get_description().empty()
&& !sg->get_group_name().empty()
&& !svc->get_hostname().empty()) {
// Output variable.
std::shared_ptr<neb::service_group_member>
sgm(new neb::service_group_member);
sgm->group_id = sg->get_id();
sgm->group_name = QString(sg->get_group_name().c_str());
sgm->poller_id = config::applier::state::instance().poller_id();
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
svc->get_hostname(),
svc->get_description());
sgm->host_id = p.first;
sgm->service_id = p.second;
if (sgm->host_id && sgm->service_id && sgm->group_id) {
if (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE) {
logging::info(logging::low) << "callbacks: service ("
<< sgm->host_id << ", " << sgm->service_id
<< ") is not a member of group " << sgm->group_id
<< " on instance " << sgm->poller_id << " anymore";
sgm->enabled = false;
}
else {
logging::info(logging::low) << "callbacks: service ("
<< sgm->host_id << ", " << sgm->service_id
<< ") is a member of group " << sgm->group_id
<< " on instance " << sgm->poller_id;
sgm->enabled = true;
}
// Send service group member event.
if (sgm->host_id && sgm->service_id && sgm->group_id)
neb::gl_publisher.write(sgm);
}
}
}
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process host data.
*
* This function is called by Engine when some host data is available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_HOST_DATA).
* @param[in] data A pointer to a nebstruct_host_data
* containing a host data.
*
* @return 0 on success.
*/
int neb::callback_host(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating host event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_adaptive_host_data const*
host_data(static_cast<nebstruct_adaptive_host_data*>(data));
engine::host const*
h(static_cast<engine::host*>(host_data->object_ptr));
std::shared_ptr<neb::host> my_host(new neb::host);
// Set host parameters.
my_host->acknowledged = h->get_problem_has_been_acknowledged();
my_host->acknowledgement_type = h->get_acknowledgement_type();
if (!h->get_action_url().empty())
my_host->action_url = QString(h->get_action_url().c_str());
my_host->active_checks_enabled = h->get_checks_enabled();
if (!h->get_address().empty())
my_host->address = QString(h->get_address().c_str());
if (!h->get_alias().empty())
my_host->alias = QString(h->get_alias().c_str());
my_host->check_freshness = h->get_check_freshness();
if (!h->get_check_command().empty())
my_host->check_command = QString(h->get_check_command().c_str());
my_host->check_interval = h->get_check_interval();
if (!h->get_check_period().empty())
my_host->check_period = QString(h->get_check_period().c_str());
my_host->check_type = h->get_check_type();
my_host->current_check_attempt = h->get_current_attempt();
my_host->current_state = (h->get_has_been_checked()
? h->get_current_state()
: 4); // Pending state.
my_host->default_active_checks_enabled = h->get_checks_enabled();
my_host->default_event_handler_enabled = h->get_event_handler_enabled();
my_host->default_flap_detection_enabled = h->get_flap_detection_enabled();
my_host->default_notifications_enabled = h->get_notifications_enabled();
my_host->default_passive_checks_enabled = h->get_accept_passive_checks();
my_host->downtime_depth = h->get_scheduled_downtime_depth();
if (!h->get_display_name().empty())
my_host->display_name = QString(h->get_display_name().c_str());
my_host->enabled = (host_data->type != NEBTYPE_HOST_DELETE);
if (!h->get_event_handler().empty())
my_host->event_handler = QString(h->get_event_handler().c_str());
my_host->event_handler_enabled = h->get_event_handler_enabled();
my_host->execution_time = h->get_execution_time();
my_host->first_notification_delay = h->get_first_notification_delay();
my_host->notification_number = h->get_notification_number();
my_host->flap_detection_enabled = h->get_flap_detection_enabled();
my_host->flap_detection_on_down = h->get_flap_detection_on(engine::notifier::down);
my_host->flap_detection_on_unreachable
= h->get_flap_detection_on(engine::notifier::unreachable);
my_host->flap_detection_on_up = h->get_flap_detection_on(engine::notifier::up);
my_host->freshness_threshold = h->get_freshness_threshold();
my_host->has_been_checked = h->get_has_been_checked();
my_host->high_flap_threshold = h->get_high_flap_threshold();
if (!h->get_name().empty())
my_host->host_name = QString(h->get_name().c_str());
if (!h->get_icon_image().empty())
my_host->icon_image = QString(h->get_icon_image().c_str());
if (!h->get_icon_image_alt().empty())
my_host->icon_image_alt = QString(h->get_icon_image_alt().c_str());
my_host->is_flapping = h->get_is_flapping();
my_host->last_check = h->get_last_check();
my_host->last_hard_state = h->get_last_hard_state();
my_host->last_hard_state_change = h->get_last_hard_state_change();
my_host->last_notification = h->get_last_notification();
my_host->last_state_change = h->get_last_state_change();
my_host->last_time_down = h->get_last_time_down();
my_host->last_time_unreachable = h->get_last_time_unreachable();
my_host->last_time_up = h->get_last_time_up();
my_host->last_update = time(nullptr);
my_host->latency = h->get_latency();
my_host->low_flap_threshold = h->get_low_flap_threshold();
my_host->max_check_attempts = h->get_max_attempts();
my_host->next_check = h->get_next_check();
my_host->next_notification = h->get_next_notification();
my_host->no_more_notifications = h->get_no_more_notifications();
if (!h->get_notes().empty())
my_host->notes = QString(h->get_notes().c_str());
if (!h->get_notes_url().empty())
my_host->notes_url = QString(h->get_notes_url().c_str());
my_host->notifications_enabled = h->get_notifications_enabled();
my_host->notification_interval = h->get_notification_interval();
if (!h->get_notification_period().empty())
my_host->notification_period = QString(h->get_notification_period().c_str());
my_host->notify_on_down = h->get_notify_on(engine::notifier::down);
my_host->notify_on_downtime = h->get_notify_on(engine::notifier::downtime);
my_host->notify_on_flapping = h->get_notify_on(engine::notifier::flappingstart);
my_host->notify_on_recovery = h->get_notify_on(engine::notifier::up);
my_host->notify_on_unreachable = h->get_notify_on(engine::notifier::unreachable);
my_host->obsess_over = h->get_obsess_over();
if (!h->get_plugin_output().empty()) {
my_host->output = QString(h->get_plugin_output().c_str());
my_host->output.append("\n");
}
if (!h->get_long_plugin_output().empty())
my_host->output.append(QString(h->get_long_plugin_output().c_str()));
my_host->passive_checks_enabled = h->get_accept_passive_checks();
my_host->percent_state_change = h->get_percent_state_change();
if (!h->get_perf_data().empty())
my_host->perf_data = QString(h->get_perf_data().c_str());
my_host->poller_id = config::applier::state::instance().poller_id();
my_host->retain_nonstatus_information
= h->get_retain_nonstatus_information();
my_host->retain_status_information = h->get_retain_status_information();
my_host->retry_interval = h->get_retry_interval();
my_host->should_be_scheduled = h->get_should_be_scheduled();
my_host->stalk_on_down = h->get_stalk_on(engine::notifier::down);
my_host->stalk_on_unreachable = h->get_stalk_on(engine::notifier::unreachable);
my_host->stalk_on_up = h->get_stalk_on(engine::notifier::up);
my_host->state_type = (h->get_has_been_checked()
? h->get_state_type()
: engine::notifier::hard);
if (!h->get_statusmap_image().empty())
my_host->statusmap_image = QString(h->get_statusmap_image().c_str());
my_host->timezone = QString(h->get_timezone().c_str());
// Find host ID.
uint64_t host_id = engine::get_host_id(
my_host->host_name.toStdString().c_str());
if (host_id != 0) {
my_host->host_id = host_id;
// Send host event.
logging::info(logging::low) << "callbacks: new host "
<< my_host->host_id << " ('" << my_host->host_name
<< "') on instance " << my_host->poller_id;
neb::gl_publisher.write(my_host);
// Generate existing custom variables.
for (com::centreon::engine::map_customvar::const_iterator
it{h->custom_variables.begin()}, end{h->custom_variables.end()};
it != end; ++it) {
std::string const& name{it->first};
if (it->second.is_sent() && name != "HOST_ID") {
nebstruct_custom_variable_data data;
memset(&data, 0, sizeof(data));
data.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD;
data.timestamp.tv_sec = host_data->timestamp.tv_sec;
data.var_name = const_cast<char*>(name.c_str());
data.var_value = const_cast<char*>(it->second.get_value().c_str());
data.object_ptr = host_data->object_ptr;
callback_custom_variable(
NEBCALLBACK_CUSTOM_VARIABLE_DATA,
&data);
}
}
}
else
logging::error(logging::medium) << "callbacks: host '"
<< (!h->get_name().empty() ? h->get_name() : "(unknown)")
<< "' has no ID (yet) defined";
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process host check data.
*
* This function is called by Nagios when some host check data are available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_HOST_CHECK_DATA).
* @param[in] data A pointer to a nebstruct_host_check_data
* containing the host check data.
*
* @return 0 on success.
*/
int neb::callback_host_check(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating host check event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_host_check_data const* hcdata;
std::shared_ptr<neb::host_check> host_check(new neb::host_check);
// Fill output var.
hcdata = static_cast<nebstruct_host_check_data*>(data);
engine::host* h(static_cast<engine::host*>(hcdata->object_ptr));
if (hcdata->command_line) {
host_check->active_checks_enabled = h->get_checks_enabled();
host_check->check_type = hcdata->check_type;
host_check->command_line = hcdata->command_line;
if (!hcdata->host_name)
throw (exceptions::msg() << "unnamed host");
host_check->host_id = engine::get_host_id(hcdata->host_name);
if (host_check->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< hcdata->host_name << "'");
host_check->next_check = h->get_next_check();
// Send event.
gl_publisher.write(host_check);
}
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating host check event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process host status data.
*
* This function is called by Nagios when some host status data are available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_HOST_STATUS_DATA).
* @param[in] data A pointer to a nebstruct_host_status_data
* containing the host status data.
*
* @return 0 on success.
*/
int neb::callback_host_status(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating host status event";
(void)callback_type;
try {
// In/Out variables.
engine::host const* h;
std::shared_ptr<neb::host_status> host_status(new neb::host_status);
// Fill output var.
h = static_cast<engine::host*>(
static_cast<nebstruct_host_status_data*>(data)->object_ptr);
host_status->acknowledged = h->get_problem_has_been_acknowledged();
host_status->acknowledgement_type = h->get_acknowledgement_type();
host_status->active_checks_enabled = h->get_checks_enabled();
if (!h->get_check_command().empty())
host_status->check_command = QString(h->get_check_command().c_str());
host_status->check_interval = h->get_check_interval();
if (!h->get_check_period().empty())
host_status->check_period = QString(h->get_check_period().c_str());
host_status->check_type = h->get_check_type();
host_status->current_check_attempt = h->get_current_attempt();
host_status->current_state = (h->get_has_been_checked()
? h->get_current_state()
: 4); // Pending state.
host_status->downtime_depth = h->get_scheduled_downtime_depth();
if (!h->get_event_handler().empty())
host_status->event_handler = QString(h->get_event_handler().c_str());
host_status->event_handler_enabled = h->get_event_handler_enabled();
host_status->execution_time = h->get_execution_time();
host_status->flap_detection_enabled = h->get_flap_detection_enabled();
host_status->has_been_checked = h->get_has_been_checked();
if (h->get_name().empty())
throw (exceptions::msg() << "unnamed host");
{
host_status->host_id = engine::get_host_id(h->get_name());
if (host_status->host_id == 0)
throw (exceptions::msg() << "could not find ID of host '"
<< h->get_name() << "'");
}
host_status->is_flapping = h->get_is_flapping();
host_status->last_check = h->get_last_check();
host_status->last_hard_state = h->get_last_hard_state();
host_status->last_hard_state_change = h->get_last_hard_state_change();
host_status->last_notification = h->get_last_notification();
host_status->notification_number = h->get_notification_number();
host_status->last_state_change = h->get_last_state_change();
host_status->last_time_down = h->get_last_time_down();
host_status->last_time_unreachable = h->get_last_time_unreachable();
host_status->last_time_up = h->get_last_time_up();
host_status->last_update = time(nullptr);
host_status->latency = h->get_latency();
host_status->max_check_attempts = h->get_max_attempts();
host_status->next_check = h->get_next_check();
host_status->next_notification = h->get_next_notification();
host_status->no_more_notifications = h->get_no_more_notifications();
host_status->notifications_enabled = h->get_notifications_enabled();
host_status->obsess_over = h->get_obsess_over();
if (!h->get_plugin_output().empty()) {
host_status->output = QString(h->get_plugin_output().c_str());
host_status->output.append("\n");
}
if (!h->get_long_plugin_output().empty())
host_status->output.append(QString(h->get_long_plugin_output().c_str()));
host_status->passive_checks_enabled = h->get_accept_passive_checks();
host_status->percent_state_change = h->get_percent_state_change();
if (!h->get_perf_data().empty())
host_status->perf_data = QString(h->get_perf_data().c_str());
host_status->retry_interval = h->get_retry_interval();
host_status->should_be_scheduled = h->get_should_be_scheduled();
host_status->state_type = (h->get_has_been_checked()
? h->get_state_type()
: engine::notifier::hard);
// Send event(s).
gl_publisher.write(host_status);
// Acknowledgement event.
std::map<
std::pair<unsigned int, unsigned int>,
neb::acknowledgement>::iterator
it(gl_acknowledgements.find(
std::make_pair(host_status->host_id, 0u)));
if ((it != gl_acknowledgements.end())
&& !host_status->acknowledged) {
if (!(!host_status->current_state // !(OK or (normal ack and NOK))
|| (!it->second.is_sticky
&& (host_status->current_state != it->second.state)))) {
std::shared_ptr<neb::acknowledgement>
ack(new neb::acknowledgement(it->second));
ack->deletion_time = time(nullptr);
gl_publisher.write(ack);
}
gl_acknowledgements.erase(it);
}
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating host status event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process log data.
*
* This function is called by Nagios when some log data are available.
*
* @param[in] callback_type Type of the callback (NEBCALLBACK_LOG_DATA).
* @param[in] data A pointer to a nebstruct_log_data containing the
* log data.
*
* @return 0 on success.
*/
int neb::callback_log(int callback_type, void* data) {
// Log message.
logging::info(logging::medium) << "callbacks: generating log event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_log_data const* log_data;
std::shared_ptr<neb::log_entry> le(new neb::log_entry);
// Fill output var.
log_data = static_cast<nebstruct_log_data*>(data);
le->c_time = log_data->entry_time;
le->poller_name
= config::applier::state::instance().poller_name().c_str();
if (log_data->data) {
if (log_data->data)
le->output = log_data->data;
set_log_data(*le, log_data->data);
}
// Send event.
gl_publisher.write(le);
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process module data.
*
* This function is called by Engine when some module data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_MODULE_DATA).
* @param[in] data A pointer to a nebstruct_module_data
* containing the module data.
*
* @return 0 on success.
*/
int neb::callback_module(int callback_type, void* data) {
// Log message.
logging::debug(logging::low) << "callbacks: generating module event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_module_data const* module_data;
std::shared_ptr<neb::module> me(new neb::module);
// Fill output var.
module_data = static_cast<nebstruct_module_data*>(data);
if (module_data->module) {
me->poller_id = config::applier::state::instance().poller_id();
me->filename = module_data->module;
if (module_data->args)
me->args = module_data->args;
me->loaded = !(module_data->type == NEBTYPE_MODULE_DELETE);
me->should_be_loaded = true;
// Send events.
gl_publisher.write(me);
}
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process process data.
*
* This function is called by Nagios when some process data is available.
*
* @param[in] callback_type Type of the callback (NEBCALLBACK_PROCESS_DATA).
* @param[in] data A pointer to a nebstruct_process_data containing
* the process data.
*
* @return 0 on success.
*/
int neb::callback_process(int callback_type, void *data) {
// Log message.
logging::debug(logging::low) << "callbacks: process event callback";
(void)callback_type;
try {
// Input variables.
nebstruct_process_data const* process_data;
static time_t start_time;
// Check process event type.
process_data = static_cast<nebstruct_process_data*>(data);
if (NEBTYPE_PROCESS_EVENTLOOPSTART == process_data->type) {
logging::info(logging::medium)
<< "callbacks: generating process start event";
// Register callbacks.
logging::debug(logging::high)
<< "callbacks: registering callbacks";
for (unsigned int i(0);
i < sizeof(gl_callbacks) / sizeof(*gl_callbacks);
++i)
gl_registered_callbacks.push_back(
std::shared_ptr<callback>(new neb::callback(
gl_callbacks[i].macro,
gl_mod_handle,
gl_callbacks[i].callback)));
// Register Engine-specific callbacks.
if (gl_mod_flags & NEBMODULE_ENGINE) {
for (unsigned int i(0);
i < sizeof(gl_engine_callbacks) / sizeof(*gl_engine_callbacks);
++i)
gl_registered_callbacks.push_back(
std::shared_ptr<callback>(new neb::callback(
gl_engine_callbacks[i].macro,
gl_mod_handle,
gl_engine_callbacks[i].callback)));
}
// Parse configuration file.
unsigned int statistics_interval(0);
try {
config::parser parsr;
config::state conf;
parsr.parse(gl_configuration_file, conf);
// Apply resulting configuration.
config::applier::state::instance().apply(conf);
gl_generator.set(conf);
// Set variables.
statistics_interval = gl_generator.interval();
}
catch (exceptions::msg const& e) {
logging::config(logging::high) << e.what();
return 0;
}
// Output variable.
std::shared_ptr<neb::instance> instance(new neb::instance);
instance->poller_id
= config::applier::state::instance().poller_id();
instance->engine = "Centreon Engine";
instance->is_running = true;
instance->name
= config::applier::state::instance().poller_name().c_str();
instance->pid = getpid();
instance->program_start = time(nullptr);
instance->version = get_program_version();
start_time = instance->program_start;
// Send initial event and then configuration.
gl_publisher.write(instance);
send_initial_configuration();
// Add statistics event.
if (statistics_interval) {
logging::info(logging::medium)
<< "stats: registering statistics generation event in "
<< "monitoring engine";
union {
void (* code)(void*);
void* data;
} val;
val.code = &event_statistics;
com::centreon::engine::timed_event* evt = new com::centreon::engine::timed_event(
EVENT_USER_FUNCTION,
time(nullptr) + statistics_interval,
1,
statistics_interval,
nullptr,
1,
val.data,
nullptr,
0);
evt->schedule(false);
}
}
else if (NEBTYPE_PROCESS_EVENTLOOPEND == process_data->type) {
logging::info(logging::medium)
<< "callbacks: generating process end event";
// Output variable.
std::shared_ptr<neb::instance> instance(new neb::instance);
// Fill output var.
instance->poller_id
= config::applier::state::instance().poller_id();
instance->engine = "Centreon Engine";
instance->is_running = false;
instance->name
= config::applier::state::instance().poller_name().c_str();
instance->pid = getpid();
instance->program_end = time(nullptr);
instance->program_start = start_time;
instance->version = get_program_version();
// Send event.
gl_publisher.write(instance);
}
}
// Avoid exception propagation in C code.
catch (...) {
unregister_callbacks();
}
return 0;
}
/**
* @brief Function that process instance status data.
*
* This function is called by Nagios when some instance status data are
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_PROGRAM_STATUS_DATA).
* @param[in] data A pointer to a nebstruct_program_status_data
* containing the program status data.
*
* @return 0 on success.
*/
int neb::callback_program_status(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating instance status event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_program_status_data const* program_status_data;
std::shared_ptr<neb::instance_status> is(
new neb::instance_status);
// Fill output var.
program_status_data = static_cast<nebstruct_program_status_data*>(data);
is->poller_id = config::applier::state::instance().poller_id();
is->active_host_checks_enabled
= program_status_data->active_host_checks_enabled;
is->active_service_checks_enabled
= program_status_data->active_service_checks_enabled;
is->check_hosts_freshness = check_host_freshness;
is->check_services_freshness = check_service_freshness;
is->event_handler_enabled
= program_status_data->event_handlers_enabled;
is->flap_detection_enabled
= program_status_data->flap_detection_enabled;
if (program_status_data->global_host_event_handler)
is->global_host_event_handler
= program_status_data->global_host_event_handler;
if (program_status_data->global_service_event_handler)
is->global_service_event_handler
= program_status_data->global_service_event_handler;
is->last_alive = time(nullptr);
is->last_command_check = program_status_data->last_command_check;
is->notifications_enabled
= program_status_data->notifications_enabled;
is->obsess_over_hosts
= program_status_data->obsess_over_hosts;
is->obsess_over_services
= program_status_data->obsess_over_services;
is->passive_host_checks_enabled
= program_status_data->passive_host_checks_enabled;
is->passive_service_checks_enabled
= program_status_data->passive_service_checks_enabled;
// Send event.
gl_publisher.write(is);
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process relation data.
*
* This function is called by Engine when some relation data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_RELATION_DATA).
* @param[in] data Pointer to a nebstruct_relation_data
* containing the relationship.
*
* @return 0 on success.
*/
int neb::callback_relation(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating relation event";
(void)callback_type;
try {
// Input variable.
nebstruct_relation_data const*
relation(static_cast<nebstruct_relation_data*>(data));
// Host parent.
if ((NEBTYPE_PARENT_ADD == relation->type)
|| (NEBTYPE_PARENT_DELETE == relation->type)) {
if (relation->hst
&& relation->dep_hst
&& !relation->svc
&& !relation->dep_svc) {
// Find host IDs.
int host_id;
int parent_id;
{
host_id = engine::get_host_id(relation->dep_hst->get_name());
parent_id = engine::get_host_id(relation->hst->get_name());
}
if (host_id && parent_id) {
// Generate parent event.
std::shared_ptr<host_parent> new_host_parent(new host_parent);
new_host_parent->enabled
= (relation->type != NEBTYPE_PARENT_DELETE);
new_host_parent->host_id = host_id;
new_host_parent->parent_id = parent_id;
// Send event.
logging::info(logging::low) << "callbacks: host "
<< new_host_parent->parent_id << " is parent of host "
<< new_host_parent->host_id;
neb::gl_publisher.write(
new_host_parent);
}
}
}
}
// Avoid exception propagation to C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process service data.
*
* This function is called by Engine when some service data is
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_ADAPTIVE_SERVICE_DATA).
* @param[in] data A pointer to a
* nebstruct_adaptive_service_data containing
* the service data.
*
* @return 0 on success.
*/
int neb::callback_service(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating service event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_adaptive_service_data const*
service_data(static_cast<nebstruct_adaptive_service_data*>(data));
engine::service const*
s(static_cast<engine::service*>(service_data->object_ptr));
std::shared_ptr<neb::service> my_service(new neb::service);
// Fill output var.
my_service->acknowledged = s->get_problem_has_been_acknowledged();
my_service->acknowledgement_type = s->get_acknowledgement_type();
if (!s->get_action_url().empty())
my_service->action_url = QString(s->get_action_url().c_str());
my_service->active_checks_enabled = s->get_checks_enabled();
if (!s->get_check_command().empty())
my_service->check_command = QString(s->get_check_command().c_str());
my_service->check_freshness = s->get_check_freshness();
my_service->check_interval = s->get_check_interval();
if (!s->get_check_period().empty())
my_service->check_period = QString(s->get_check_period().c_str());
my_service->check_type = s->get_check_type();
my_service->current_check_attempt = s->get_current_attempt();
my_service->current_state = (s->get_has_been_checked()
? s->get_current_state()
: 4); // Pending state.
my_service->default_active_checks_enabled = s->get_checks_enabled();
my_service->default_event_handler_enabled = s->get_event_handler_enabled();
my_service->default_flap_detection_enabled = s->get_flap_detection_enabled();
my_service->default_notifications_enabled = s->get_notifications_enabled();
my_service->default_passive_checks_enabled
= s->get_accept_passive_checks();
my_service->downtime_depth = s->get_scheduled_downtime_depth();
if (!s->get_display_name().empty())
my_service->display_name = QString(s->get_display_name().c_str());
my_service->enabled
= (service_data->type != NEBTYPE_SERVICE_DELETE);
if (!s->get_event_handler().empty())
my_service->event_handler = QString(s->get_event_handler().c_str());
my_service->event_handler_enabled = s->get_event_handler_enabled();
my_service->execution_time = s->get_execution_time();
my_service->first_notification_delay = s->get_first_notification_delay();
my_service->notification_number = s->get_notification_number();
my_service->flap_detection_enabled = s->get_flap_detection_enabled();
my_service->flap_detection_on_critical = s->get_flap_detection_on(engine::notifier::critical);
my_service->flap_detection_on_ok = s->get_flap_detection_on(engine::notifier::ok);
my_service->flap_detection_on_unknown = s->get_flap_detection_on(engine::notifier::unknown);
my_service->flap_detection_on_warning = s->get_flap_detection_on(engine::notifier::warning);
my_service->freshness_threshold = s->get_freshness_threshold();
my_service->has_been_checked = s->get_has_been_checked();
my_service->high_flap_threshold = s->get_high_flap_threshold();
if (!s->get_hostname().empty())
my_service->host_name = QString(s->get_hostname().c_str());
if (!s->get_icon_image().empty())
my_service->icon_image = QString(s->get_icon_image().c_str());
if (!s->get_icon_image_alt().empty())
my_service->icon_image_alt = QString(s->get_icon_image_alt().c_str());
my_service->is_flapping = s->get_is_flapping();
my_service->is_volatile = s->get_is_volatile();
my_service->last_check = s->get_last_check();
my_service->last_hard_state = s->get_last_hard_state();
my_service->last_hard_state_change = s->get_last_hard_state_change();
my_service->last_notification = s->get_last_notification();
my_service->last_state_change = s->get_last_state_change();
my_service->last_time_critical = s->get_last_time_critical();
my_service->last_time_ok = s->get_last_time_ok();
my_service->last_time_unknown = s->get_last_time_unknown();
my_service->last_time_warning = s->get_last_time_warning();
my_service->last_update = time(nullptr);
my_service->latency = s->get_latency();
my_service->low_flap_threshold = s->get_low_flap_threshold();
my_service->max_check_attempts = s->get_max_attempts();
my_service->next_check = s->get_next_check();
my_service->next_notification = s->get_next_notification();
my_service->no_more_notifications = s->get_no_more_notifications();
if (!s->get_notes().empty())
my_service->notes = QString(s->get_notes().c_str());
if (!s->get_notes_url().empty())
my_service->notes_url = QString(s->get_notes_url().c_str());
my_service->notifications_enabled = s->get_notifications_enabled();
my_service->notification_interval = s->get_notification_interval();
if (!s->get_notification_period().empty())
my_service->notification_period = QString(s->get_notification_period().c_str());
my_service->notify_on_critical = s->get_notify_on(engine::notifier::critical);
my_service->notify_on_downtime = s->get_notify_on(engine::notifier::downtime);
my_service->notify_on_flapping = s->get_notify_on(engine::notifier::flappingstart);
my_service->notify_on_recovery = s->get_notify_on(engine::notifier::ok);
my_service->notify_on_unknown = s->get_notify_on(engine::notifier::unknown);
my_service->notify_on_warning = s->get_notify_on(engine::notifier::warning);
my_service->obsess_over = s->get_obsess_over();
if (!s->get_plugin_output().empty()) {
my_service->output = QString(s->get_plugin_output().c_str());
my_service->output.append("\n");
}
if (!s->get_long_plugin_output().empty())
my_service->output.append(s->get_long_plugin_output().c_str());
my_service->passive_checks_enabled
= s->get_accept_passive_checks();
my_service->percent_state_change = s->get_percent_state_change();
if (!s->get_perf_data().empty())
my_service->perf_data = QString(s->get_perf_data().c_str());
my_service->retain_nonstatus_information
= s->get_retain_nonstatus_information();
my_service->retain_status_information
= s->get_retain_status_information();
my_service->retry_interval = s->get_retry_interval();
if (!s->get_description().empty())
my_service->service_description = QString(s->get_description().c_str());
my_service->should_be_scheduled = s->get_should_be_scheduled();
my_service->stalk_on_critical = s->get_stalk_on(engine::notifier::critical);
my_service->stalk_on_ok = s->get_stalk_on(engine::notifier::ok);
my_service->stalk_on_unknown = s->get_stalk_on(engine::notifier::unknown);
my_service->stalk_on_warning = s->get_stalk_on(engine::notifier::warning);
my_service->state_type = (s->get_has_been_checked()
? s->get_state_type()
: engine::notifier::hard);
// Search host ID and service ID.
std::pair<uint64_t, uint64_t> p;
p = engine::get_host_and_service_id(
s->get_hostname(),
s->get_description());
my_service->host_id = p.first;
my_service->service_id = p.second;
if (my_service->host_id && my_service->service_id) {
// Send service event.
logging::info(logging::low) << "callbacks: new service "
<< my_service->service_id << " ('"
<< my_service->service_description
<< "') on host " << my_service->host_id;
neb::gl_publisher.write(my_service);
// Generate existing custom variables.
for (com::centreon::engine::map_customvar::const_iterator
it{s->custom_variables.begin()}, end{s->custom_variables.end()};
it != end;
++it) {
if (it->second.is_sent()
&& !it->first.empty()
&& it->first != "HOST_ID"
&& it->first != "SERVICE_ID") {
nebstruct_custom_variable_data data;
memset(&data, 0, sizeof(data));
data.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD;
data.timestamp.tv_sec = service_data->timestamp.tv_sec;
data.var_name = const_cast<char*>(it->first.c_str());
data.var_value = const_cast<char*>(it->second.get_value().c_str());
data.object_ptr = service_data->object_ptr;
callback_custom_variable(
NEBCALLBACK_CUSTOM_VARIABLE_DATA,
&data);
}
}
}
else
logging::error(logging::medium)
<< "callbacks: service has no host ID or no service ID (yet) (host '"
<< (!s->get_hostname().empty() ? s->get_hostname() : "(unknown)")
<< "', service '"
<< (!s->get_description().empty() ? s->get_description() : "(unknown)")
<< "')";
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process service check data.
*
* This function is called by Nagios when some service check data are
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_SERVICE_CHECK_DATA).
* @param[in] data A pointer to a nebstruct_service_check_data
* containing the service check data.
*
* @return 0 on success.
*/
int neb::callback_service_check(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating service check event";
(void)callback_type;
try {
// In/Out variables.
nebstruct_service_check_data const* scdata;
std::shared_ptr<neb::service_check> service_check(
new neb::service_check);
// Fill output var.
scdata = static_cast<nebstruct_service_check_data*>(data);
engine::service* s{static_cast<engine::service*>(scdata->object_ptr)};
if (scdata->command_line) {
service_check->active_checks_enabled = s->get_checks_enabled();
service_check->check_type = scdata->check_type;
service_check->command_line = scdata->command_line;
if (!scdata->host_name)
throw (exceptions::msg() << "unnamed host");
if (!scdata->service_description)
throw (exceptions::msg() << "unnamed service");
std::pair<unsigned int, unsigned int> p;
p = engine::get_host_and_service_id(
scdata->host_name,
scdata->service_description);
service_check->host_id = p.first;
service_check->service_id = p.second;
if (!service_check->host_id || !service_check->service_id)
throw (exceptions::msg() << "could not find ID of service ('"
<< scdata->host_name << "', '"
<< scdata->service_description << "')");
service_check->next_check = s->get_next_check();
// Send event.
gl_publisher.write(service_check);
}
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating service check event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* @brief Function that process service status data.
*
* This function is called by Nagios when some service status data are
* available.
*
* @param[in] callback_type Type of the callback
* (NEBCALLBACK_SERVICE_STATUS_DATA).
* @param[in] data A pointer to a nebstruct_service_status_data
* containing the service status data.
*
* @return 0 on success.
*/
int neb::callback_service_status(int callback_type, void* data) {
// Log message.
logging::info(logging::medium)
<< "callbacks: generating service status event";
(void)callback_type;
try {
// In/Out variables.
std::shared_ptr<neb::service_status> service_status(
new neb::service_status);
// Fill output var.
engine::service const* s{
static_cast<engine::service*>(
static_cast<nebstruct_service_status_data*>(data)->object_ptr)};
service_status->acknowledged = s->get_problem_has_been_acknowledged();
service_status->acknowledgement_type = s->get_acknowledgement_type();
service_status->active_checks_enabled = s->get_checks_enabled();
if (!s->get_check_command().empty())
service_status->check_command = QString(s->get_check_command().c_str());
service_status->check_interval = s->get_check_interval();
if (!s->get_check_period().empty())
service_status->check_period = QString(s->get_check_period().c_str());
service_status->check_type = s->get_check_type();
service_status->current_check_attempt = s->get_current_attempt();
service_status->current_state = (s->get_has_been_checked()
? s->get_current_state()
: 4); // Pending state.
service_status->downtime_depth = s->get_scheduled_downtime_depth();
if (!s->get_event_handler().empty())
service_status->event_handler = QString(s->get_event_handler().c_str());
service_status->event_handler_enabled = s->get_event_handler_enabled();
service_status->execution_time = s->get_execution_time();
service_status->flap_detection_enabled = s->get_flap_detection_enabled();
service_status->has_been_checked = s->get_has_been_checked();
service_status->is_flapping = s->get_is_flapping();
service_status->last_check = s->get_last_check();
service_status->last_hard_state = s->get_last_hard_state();
service_status->last_hard_state_change = s->get_last_hard_state_change();
service_status->last_notification = s->get_last_notification();
service_status->notification_number = s->get_notification_number();
service_status->last_state_change = s->get_last_state_change();
service_status->last_time_critical = s->get_last_time_critical();
service_status->last_time_ok = s->get_last_time_ok();
service_status->last_time_unknown = s->get_last_time_unknown();
service_status->last_time_warning = s->get_last_time_warning();
service_status->last_update = time(nullptr);
service_status->latency = s->get_latency();
service_status->max_check_attempts = s->get_max_attempts();
service_status->next_check = s->get_next_check();
service_status->next_notification = s->get_next_notification();
service_status->no_more_notifications = s->get_no_more_notifications();
service_status->notifications_enabled = s->get_notifications_enabled();
service_status->obsess_over = s->get_obsess_over();
if (!s->get_plugin_output().empty()) {
service_status->output = QString(s->get_plugin_output().c_str());
service_status->output.append("\n");
}
if (!s->get_long_plugin_output().empty())
service_status->output.append(s->get_long_plugin_output().c_str());
service_status->passive_checks_enabled
= s->get_accept_passive_checks();
service_status->percent_state_change = s->get_percent_state_change();
if (!s->get_perf_data().empty())
service_status->perf_data = QString(s->get_perf_data().c_str());
service_status->retry_interval = s->get_retry_interval();
if (s->get_hostname().empty())
throw exceptions::msg() << "unnamed host";
if (s->get_description().empty())
throw exceptions::msg() << "unnamed service";
service_status->host_name = QString(s->get_hostname().c_str());
service_status->service_description = QString(s->get_description().c_str());
{
std::pair<uint64_t, uint64_t> p{
engine::get_host_and_service_id(s->get_hostname(), s->get_description())};
service_status->host_id = p.first;
service_status->service_id = p.second;
if (!service_status->host_id || !service_status->service_id)
throw exceptions::msg() << "could not find ID of service ('"
<< s->get_hostname() << "', '" << s->get_description() << "')";
}
service_status->should_be_scheduled = s->get_should_be_scheduled();
service_status->state_type = (s->get_has_been_checked()
? s->get_state_type()
: engine::notifier::hard);
// Send event(s).
gl_publisher.write(service_status);
// Acknowledgement event.
std::map<
std::pair<unsigned int, unsigned int>,
neb::acknowledgement>::iterator
it(gl_acknowledgements.find(std::make_pair(
service_status->host_id,
service_status->service_id)));
if ((it != gl_acknowledgements.end())
&& !service_status->acknowledged) {
if (!(!service_status->current_state // !(OK or (normal ack and NOK))
|| (!it->second.is_sticky
&& (service_status->current_state
!= it->second.state)))) {
std::shared_ptr<neb::acknowledgement>
ack(new neb::acknowledgement(it->second));
ack->deletion_time = time(nullptr);
gl_publisher.write(ack);
}
gl_acknowledgements.erase(it);
}
}
catch (std::exception const& e) {
logging::error(logging::medium) << "callbacks: error occurred while"
" generating service status event: " << e.what();
}
// Avoid exception propagation in C code.
catch (...) {}
return 0;
}
/**
* Unregister callbacks.
*/
void neb::unregister_callbacks() {
gl_registered_callbacks.clear();
}
| 39.651619 | 98 | 0.640508 | sdelafond |
eceed4c584f8276a15e8ef0f6967172637b12367 | 2,126 | cpp | C++ | engine/src/tools/logger.cpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | engine/src/tools/logger.cpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | engine/src/tools/logger.cpp | dorosch/engine | 0cd277675264f848ac141f7e5663242bd7b43438 | [
"MIT"
] | null | null | null | #include "tools/logger.hpp"
namespace Tool {
namespace Logger {
Logger::Logger(const char *name) {
this->_level = Level::info;
this->_logger = spdlog::stdout_color_mt(name);
}
Level Logger::GetLevel() {
return this->_level;
}
void Logger::SetLevel(Level level) {
switch (level) {
case Level::trace:
this->_level = Level::trace;
this->_logger->set_level(spdlog::level::trace);
break;
case Level::debug:
this->_level = Level::debug;
this->_logger->set_level(spdlog::level::debug);
break;
case Level::info:
this->_level = Level::info;
this->_logger->set_level(spdlog::level::info);
break;
case Level::warning:
this->_level = Level::warning;
this->_logger->set_level(spdlog::level::warn);
break;
case Level::error:
this->_level = Level::error;
this->_logger->set_level(spdlog::level::err);
break;
case Level::critical:
this->_level = Level::critical;
this->_logger->set_level(spdlog::level::critical);
break;
}
}
void Logger::trace(const char *message) {
this->_logger->trace(message);
}
void Logger::debug(const char *message) {
this->_logger->debug(message);
}
void Logger::info(const char *message) {
this->_logger->info(message);
}
void Logger::warning(const char *message) {
this->_logger->warn(message);
}
void Logger::error(const char *message) {
this->_logger->error(message);
}
void Logger::critical(const char *message) {
this->_logger->critical(message);
}
}
}
| 27.61039 | 70 | 0.465193 | dorosch |
ecf36f656d433f8a208c4ffdfb419da1db128921 | 1,895 | cpp | C++ | Source/Core/TornadoEngine/Features/Graphic/DialogBuilderSystem.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 27 | 2015-01-08T08:26:29.000Z | 2019-02-10T03:18:05.000Z | Source/Core/TornadoEngine/Features/Graphic/DialogBuilderSystem.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 1 | 2017-04-05T02:02:14.000Z | 2017-04-05T02:02:14.000Z | Source/Core/TornadoEngine/Features/Graphic/DialogBuilderSystem.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 17 | 2015-01-18T02:50:01.000Z | 2019-02-08T21:00:53.000Z | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [[email protected], [email protected]]
See for more information LICENSE.md.
*/
#include "DialogBuilderSystem.h"
#include <ImGuiWidgets/include/Dialog.h>
#include "Modules.h"
#include "GraphicEngineModule.h"
#include "PositionComponent.h"
#include "SizeComponent.h"
#include "TitleComponent.h"
#include "PrefabOriginalGuidComponent.h"
#include "SceneOriginalGuidComponent.h"
#include "DialogCloseEventHandlerComponent.h"
#include "HandlerLinkHelper.h"
#include "UnitBuilderHelper.h"
#include "FrameMouseClickHandlerComponent.h"
using namespace nsGraphicWrapper;
using namespace nsGuiWrapper;
void TDialogBuilderSystem::Reactive(nsECSFramework::TEntityID eid, const nsGuiWrapper::TDialogComponent* pDialogComponent)
{
auto dialogStack = nsTornadoEngine::Modules()->G()->GetDialogStack();
dialogStack->Add(pDialogComponent->value);
auto entMng = GetEntMng();
TUnitBuilderHelper::SetupWidget(entMng, eid, pDialogComponent->value);
TUnitBuilderHelper::SetupGeometry(entMng, eid, pDialogComponent->value);
auto handlerCallCollector = nsTornadoEngine::Modules()->HandlerCalls();
pDialogComponent->value->mOnShowCB.Register(pDialogComponent->value,
[entMng, handlerCallCollector, eid, pDialogComponent](bool isShown)
{
if (isShown) {
return;
}
auto handlers = THandlerLinkHelper::FindHandlers<TDialogCloseEventHandlerComponent>(entMng, eid, pDialogComponent);
for (auto& pHandler : handlers) {
handlerCallCollector->Add([pHandler, eid, pDialogComponent]()
{
pHandler->handler->Handle(eid, pDialogComponent);
});
}
});
THandlerLinkHelper::RegisterMouseKey(entMng, eid, pDialogComponent);
}
| 31.065574 | 124 | 0.709763 | RamilGauss |
ecf7e1032869cf40ecba51fdd0efa142b9ceded0 | 801 | cpp | C++ | TensorShaderAvxBackend/Quaternion/Cast/quaternion_purek.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | TensorShaderAvxBackend/Quaternion/Cast/quaternion_purek.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | TensorShaderAvxBackend/Quaternion/Cast/quaternion_purek.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | #include "../../TensorShaderAvxBackend.h"
using namespace System;
void quaternion_purek(unsigned int length, float* srck_ptr, float* dst_ptr) {
for (unsigned int i = 0, j = 0; i < length; i += 4, j++) {
dst_ptr[i + 3] = srck_ptr[j];
dst_ptr[i + 0] = dst_ptr[i + 1] = dst_ptr[i + 2] = 0;
}
}
void TensorShaderAvxBackend::Quaternion::PureK(unsigned int length, AvxArray<float>^ src_k, AvxArray<float>^ dst) {
Util::CheckDuplicateArray(src_k, dst);
if (length % 4 != 0) {
throw gcnew System::ArgumentException();
}
Util::CheckLength(length / 4, src_k);
Util::CheckLength(length, dst);
float* srck_ptr = (float*)(src_k->Ptr.ToPointer());
float* dst_ptr = (float*)(dst->Ptr.ToPointer());
quaternion_purek(length, srck_ptr, dst_ptr);
} | 29.666667 | 115 | 0.632959 | tk-yoshimura |
ecfb696972169ea210b985a5d6e8c01a0241b62e | 22,278 | hpp | C++ | libcaf_core/caf/flow/observable.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/flow/observable.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/flow/observable.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/async/consumer.hpp"
#include "caf/async/producer.hpp"
#include "caf/async/spsc_buffer.hpp"
#include "caf/cow_tuple.hpp"
#include "caf/cow_vector.hpp"
#include "caf/defaults.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/detail/unordered_flat_map.hpp"
#include "caf/disposable.hpp"
#include "caf/flow/coordinated.hpp"
#include "caf/flow/coordinator.hpp"
#include "caf/flow/fwd.hpp"
#include "caf/flow/observable_decl.hpp"
#include "caf/flow/observable_state.hpp"
#include "caf/flow/observer.hpp"
#include "caf/flow/op/base.hpp"
#include "caf/flow/op/concat.hpp"
#include "caf/flow/op/from_resource.hpp"
#include "caf/flow/op/from_steps.hpp"
#include "caf/flow/op/merge.hpp"
#include "caf/flow/op/prefetch.hpp"
#include "caf/flow/op/publish.hpp"
#include "caf/flow/step/all.hpp"
#include "caf/flow/subscription.hpp"
#include "caf/intrusive_ptr.hpp"
#include "caf/logger.hpp"
#include "caf/make_counted.hpp"
#include "caf/ref_counted.hpp"
#include "caf/sec.hpp"
#include <cstddef>
#include <functional>
#include <numeric>
#include <type_traits>
#include <vector>
namespace caf::flow {
// -- connectable --------------------------------------------------------------
/// Resembles a regular @ref observable, except that it does not begin emitting
/// items when it is subscribed to. Only after calling `connect` will the
/// `connectable` start to emit items.
template <class T>
class connectable {
public:
/// The type of emitted items.
using output_type = T;
/// The pointer-to-implementation type.
using pimpl_type = intrusive_ptr<op::publish<T>>;
explicit connectable(pimpl_type pimpl) noexcept : pimpl_(std::move(pimpl)) {
// nop
}
connectable& operator=(std::nullptr_t) noexcept {
pimpl_.reset();
return *this;
}
connectable() noexcept = default;
connectable(connectable&&) noexcept = default;
connectable(const connectable&) noexcept = default;
connectable& operator=(connectable&&) noexcept = default;
connectable& operator=(const connectable&) noexcept = default;
/// Returns an @ref observable that automatically connects to this
/// `connectable` when reaching `subscriber_threshold` subscriptions.
observable<T> auto_connect(size_t subscriber_threshold = 1) & {
auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_);
ptr->auto_connect_threshold(subscriber_threshold);
return observable<T>{ptr};
}
/// Similar to the `lvalue` overload, but converts this `connectable` directly
/// if possible, thus saving one hop on the pipeline.
observable<T> auto_connect(size_t subscriber_threshold = 1) && {
if (pimpl_->unique() && !pimpl_->connected()) {
pimpl_->auto_connect_threshold(subscriber_threshold);
return observable<T>{std::move(pimpl_)};
} else {
auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_);
ptr->auto_connect_threshold(subscriber_threshold);
return observable<T>{ptr};
}
}
/// Returns an @ref observable that automatically connects to this
/// `connectable` when reaching `subscriber_threshold` subscriptions and
/// disconnects automatically after the last subscriber canceled its
/// subscription.
/// @note The threshold only applies to the initial connect, not to any
/// re-connects.
observable<T> ref_count(size_t subscriber_threshold = 1) & {
auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_);
ptr->auto_connect_threshold(subscriber_threshold);
ptr->auto_disconnect(true);
return observable<T>{ptr};
}
/// Similar to the `lvalue` overload, but converts this `connectable` directly
/// if possible, thus saving one hop on the pipeline.
observable<T> ref_count(size_t subscriber_threshold = 1) && {
if (pimpl_->unique() && !pimpl_->connected()) {
pimpl_->auto_connect_threshold(subscriber_threshold);
pimpl_->auto_disconnect(true);
return observable<T>{std::move(pimpl_)};
} else {
auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_);
ptr->auto_connect_threshold(subscriber_threshold);
ptr->auto_disconnect(true);
return observable<T>{ptr};
}
}
/// Connects to the source @ref observable, thus starting to emit items.
disposable connect() {
return pimpl_->connect();
}
/// @copydoc observable::compose
template <class Fn>
auto compose(Fn&& fn) && {
return fn(std::move(*this));
}
template <class... Ts>
disposable subscribe(Ts&&... xs) {
return as_observable().subscribe(std::forward<Ts>(xs)...);
}
observable<T> as_observable() const& {
return observable<T>{pimpl_};
}
observable<T> as_observable() && {
return observable<T>{std::move(pimpl_)};
}
const pimpl_type& pimpl() const noexcept {
return pimpl_;
}
bool valid() const noexcept {
return pimpl_ != nullptr;
}
explicit operator bool() const noexcept {
return valid();
}
bool operator!() const noexcept {
return !valid();
}
void swap(connectable& other) {
pimpl_.swap(other.pimpl_);
}
/// @pre `valid()`
coordinator* ctx() const {
return pimpl_->ctx();
}
private:
pimpl_type pimpl_;
};
/// Captures the *definition* of an observable that has not materialized yet.
template <class Materializer, class... Steps>
class observable_def {
public:
using output_type = output_type_t<Materializer, Steps...>;
observable_def() = delete;
observable_def(const observable_def&) = delete;
observable_def& operator=(const observable_def&) = delete;
observable_def(observable_def&&) = default;
observable_def& operator=(observable_def&&) = default;
template <size_t N = sizeof...(Steps), class = std::enable_if_t<N == 0>>
explicit observable_def(Materializer&& materializer)
: materializer_(std::move(materializer)) {
// nop
}
observable_def(Materializer&& materializer, std::tuple<Steps...>&& steps)
: materializer_(std::move(materializer)), steps_(std::move(steps)) {
// nop
}
/// @copydoc observable::transform
template <class NewStep>
observable_def<Materializer, Steps..., NewStep> transform(NewStep step) && {
return add_step(std::move(step));
}
/// @copydoc observable::compose
template <class Fn>
auto compose(Fn&& fn) && {
return fn(std::move(*this));
}
/// @copydoc observable::skip
auto skip(size_t n) && {
return add_step(step::skip<output_type>{n});
}
/// @copydoc observable::take
auto take(size_t n) && {
return add_step(step::take<output_type>{n});
}
template <class Predicate>
auto filter(Predicate predicate) && {
return add_step(step::filter<Predicate>{std::move(predicate)});
}
template <class Predicate>
auto take_while(Predicate predicate) && {
return add_step(step::take_while<Predicate>{std::move(predicate)});
}
template <class Init, class Reducer>
auto reduce(Init init, Reducer reducer) && {
using val_t = output_type;
static_assert(std::is_invocable_r_v<Init, Reducer, Init&&, const val_t&>);
return add_step(step::reduce<Reducer>{std::move(init), std::move(reducer)});
}
auto sum() && {
return std::move(*this).reduce(output_type{}, std::plus<output_type>{});
}
auto to_vector() && {
using vector_type = cow_vector<output_type>;
auto append = [](vector_type&& xs, const output_type& x) {
xs.unshared().push_back(x);
return xs;
};
return std::move(*this)
.reduce(vector_type{}, append)
.filter([](const vector_type& xs) { return !xs.empty(); });
}
auto distinct() && {
return add_step(step::distinct<output_type>{});
}
template <class F>
auto map(F f) && {
return add_step(step::map<F>{std::move(f)});
}
template <class F>
auto do_on_next(F f) && {
return add_step(step::do_on_next<F>{std::move(f)});
}
template <class F>
auto do_on_complete(F f) && {
return add_step(step::do_on_complete<output_type, F>{std::move(f)});
}
template <class F>
auto do_on_error(F f) && {
return add_step(step::do_on_error<output_type, F>{std::move(f)});
}
template <class F>
auto do_finally(F f) && {
return add_step(step::do_finally<output_type, F>{std::move(f)});
}
auto on_error_complete() {
return add_step(step::on_error_complete<output_type>{});
}
/// Materializes the @ref observable.
observable<output_type> as_observable() && {
return materialize();
}
/// @copydoc observable::for_each
template <class OnNext>
auto for_each(OnNext on_next) && {
return materialize().for_each(std::move(on_next));
}
/// @copydoc observable::merge
template <class... Inputs>
auto merge(Inputs&&... xs) && {
return materialize().merge(std::forward<Inputs>(xs)...);
}
/// @copydoc observable::concat
template <class... Inputs>
auto concat(Inputs&&... xs) && {
return materialize().concat(std::forward<Inputs>(xs)...);
}
/// @copydoc observable::flat_map
template <class F>
auto flat_map(F f) && {
return materialize().flat_map(std::move(f));
}
/// @copydoc observable::concat_map
template <class F>
auto concat_map(F f) && {
return materialize().concat_map(std::move(f));
}
/// @copydoc observable::publish
auto publish() && {
return materialize().publish();
}
/// @copydoc observable::share
auto share(size_t subscriber_threshold = 1) && {
return materialize().share(subscriber_threshold);
}
/// @copydoc observable::prefix_and_tail
observable<cow_tuple<cow_vector<output_type>, observable<output_type>>>
prefix_and_tail(size_t prefix_size) && {
return materialize().prefix_and_tail(prefix_size);
}
/// @copydoc observable::head_and_tail
observable<cow_tuple<output_type, observable<output_type>>>
head_and_tail() && {
return materialize().head_and_tail();
}
/// @copydoc observable::subscribe
template <class Out>
disposable subscribe(Out&& out) && {
return materialize().subscribe(std::forward<Out>(out));
}
/// @copydoc observable::to_resource
async::consumer_resource<output_type> to_resource() && {
return materialize().to_resource();
}
/// @copydoc observable::to_resource
async::consumer_resource<output_type>
to_resource(size_t buffer_size, size_t min_request_size) && {
return materialize().to_resource(buffer_size, min_request_size);
}
/// @copydoc observable::observe_on
observable<output_type> observe_on(coordinator* other) && {
return materialize().observe_on(other);
}
/// @copydoc observable::observe_on
observable<output_type> observe_on(coordinator* other, size_t buffer_size,
size_t min_request_size) && {
return materialize().observe_on(other, buffer_size, min_request_size);
}
bool valid() const noexcept {
return materializer_.valid();
}
private:
template <class NewStep>
observable_def<Materializer, Steps..., NewStep> add_step(NewStep step) {
static_assert(std::is_same_v<output_type, typename NewStep::input_type>);
return {std::move(materializer_),
std::tuple_cat(std::move(steps_),
std::make_tuple(std::move(step)))};
}
observable<output_type> materialize() {
return std::move(materializer_).materialize(std::move(steps_));
}
/// Encapsulates logic for allocating a flow operator.
Materializer materializer_;
/// Stores processing steps that the materializer fuses into a single flow
/// operator.
std::tuple<Steps...> steps_;
};
// -- transformation -----------------------------------------------------------
/// Materializes an @ref observable from a source @ref observable and one or
/// more processing steps.
template <class Input>
class transformation_materializer {
public:
using output_type = Input;
explicit transformation_materializer(observable<Input> source)
: source_(std::move(source).pimpl()) {
// nop
}
explicit transformation_materializer(intrusive_ptr<op::base<Input>> source)
: source_(std::move(source)) {
// nop
}
transformation_materializer() = delete;
transformation_materializer(const transformation_materializer&) = delete;
transformation_materializer& operator=(const transformation_materializer&)
= delete;
transformation_materializer(transformation_materializer&&) = default;
transformation_materializer& operator=(transformation_materializer&&)
= default;
bool valid() const noexcept {
return source_ != nullptr;
}
coordinator* ctx() {
return source_->ctx();
}
template <class Step, class... Steps>
auto materialize(std::tuple<Step, Steps...>&& steps) && {
using impl_t = op::from_steps<Input, Step, Steps...>;
return make_observable<impl_t>(ctx(), source_, std::move(steps));
}
private:
intrusive_ptr<op::base<Input>> source_;
};
// -- observable: subscribing --------------------------------------------------
template <class T>
disposable observable<T>::subscribe(observer<T> what) {
if (pimpl_) {
return pimpl_->subscribe(std::move(what));
} else {
what.on_error(make_error(sec::invalid_observable));
return disposable{};
}
}
template <class T>
disposable observable<T>::subscribe(async::producer_resource<T> resource) {
using buffer_type = typename async::consumer_resource<T>::buffer_type;
using adapter_type = buffer_writer_impl<buffer_type>;
if (auto buf = resource.try_open()) {
CAF_LOG_DEBUG("subscribe producer resource to flow");
auto adapter = make_counted<adapter_type>(pimpl_->ctx(), buf);
buf->set_producer(adapter);
auto obs = adapter->as_observer();
auto sub = subscribe(std::move(obs));
pimpl_->ctx()->watch(sub);
return sub;
} else {
CAF_LOG_DEBUG("failed to open producer resource");
return {};
}
}
template <class T>
template <class OnNext>
disposable observable<T>::for_each(OnNext on_next) {
return subscribe(make_observer(std::move(on_next)));
}
// -- observable: transforming -------------------------------------------------
template <class T>
template <class Step>
transformation<Step> observable<T>::transform(Step step) {
static_assert(std::is_same_v<typename Step::input_type, T>,
"step object does not match the input type");
return {transformation_materializer<T>{pimpl()}, std::move(step)};
}
template <class T>
template <class U>
transformation<step::distinct<U>> observable<T>::distinct() {
static_assert(detail::is_complete<std::hash<U>>,
"distinct uses a hash set and thus requires std::hash<T>");
return transform(step::distinct<U>{});
}
template <class T>
template <class F>
transformation<step::do_finally<T, F>> observable<T>::do_finally(F fn) {
return transform(step::do_finally<T, F>{std::move(fn)});
}
template <class T>
template <class F>
transformation<step::do_on_complete<T, F>> observable<T>::do_on_complete(F fn) {
return transform(step::do_on_complete<T, F>{std::move(fn)});
}
template <class T>
template <class F>
transformation<step::do_on_error<T, F>> observable<T>::do_on_error(F fn) {
return transform(step::do_on_error<T, F>{std::move(fn)});
}
template <class T>
template <class F>
transformation<step::do_on_next<F>> observable<T>::do_on_next(F fn) {
return transform(step::do_on_next<F>{std::move(fn)});
}
template <class T>
template <class Predicate>
transformation<step::filter<Predicate>>
observable<T>::filter(Predicate predicate) {
return transform(step::filter{std::move(predicate)});
}
template <class T>
template <class F>
transformation<step::map<F>> observable<T>::map(F f) {
return transform(step::map(std::move(f)));
}
template <class T>
transformation<step::on_error_complete<T>> observable<T>::on_error_complete() {
return transform(step::on_error_complete<T>{});
}
template <class T>
template <class Init, class Reducer>
transformation<step::reduce<Reducer>>
observable<T>::reduce(Init init, Reducer reducer) {
static_assert(std::is_invocable_r_v<Init, Reducer, Init&&, const T&>);
return transform(step::reduce<Reducer>{std::move(init), std::move(reducer)});
}
template <class T>
transformation<step::skip<T>> observable<T>::skip(size_t n) {
return transform(step::skip<T>{n});
}
template <class T>
transformation<step::take<T>> observable<T>::take(size_t n) {
return transform(step::take<T>{n});
}
template <class T>
template <class Predicate>
transformation<step::take_while<Predicate>>
observable<T>::take_while(Predicate predicate) {
return transform(step::take_while{std::move(predicate)});
}
// -- observable: combining ----------------------------------------------------
template <class T>
template <class Out, class... Inputs>
auto observable<T>::merge(Inputs&&... xs) {
if constexpr (is_observable_v<Out>) {
using value_t = output_type_t<Out>;
using impl_t = op::merge<value_t>;
return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...);
} else {
static_assert(
sizeof...(Inputs) > 0,
"merge without arguments expects this observable to emit observables");
using impl_t = op::merge<Out>;
return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...);
}
}
template <class T>
template <class Out, class... Inputs>
auto observable<T>::concat(Inputs&&... xs) {
if constexpr (is_observable_v<Out>) {
using value_t = output_type_t<Out>;
using impl_t = op::concat<value_t>;
return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...);
} else {
static_assert(
sizeof...(Inputs) > 0,
"merge without arguments expects this observable to emit observables");
using impl_t = op::concat<Out>;
return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...);
}
}
template <class T>
template <class Out, class F>
auto observable<T>::flat_map(F f) {
using res_t = decltype(f(std::declval<const Out&>()));
if constexpr (is_observable_v<res_t>) {
return map([fn = std::move(f)](const Out& x) mutable {
return fn(x).as_observable();
})
.merge();
} else if constexpr (detail::is_optional_v<res_t>) {
return map([fn = std::move(f)](const Out& x) mutable { return fn(x); })
.filter([](const res_t& x) { return x.has_value(); })
.map([](const res_t& x) { return *x; });
} else {
// Here, we dispatch to concat() instead of merging the containers. Merged
// output is probably not what anyone would expect and since the values are
// all available immediately, there is no good reason to mess up the emitted
// order of values.
static_assert(detail::is_iterable_v<res_t>);
return map([cptr = ctx(), fn = std::move(f)](const Out& x) mutable {
return cptr->make_observable().from_container(fn(x));
})
.concat();
}
}
template <class T>
template <class Out, class F>
auto observable<T>::concat_map(F f) {
using res_t = decltype(f(std::declval<const Out&>()));
if constexpr (is_observable_v<res_t>) {
return map([fn = std::move(f)](const Out& x) mutable {
return fn(x).as_observable();
})
.concat();
} else if constexpr (detail::is_optional_v<res_t>) {
return map([fn = std::move(f)](const Out& x) mutable { return fn(x); })
.filter([](const res_t& x) { return x.has_value(); })
.map([](const res_t& x) { return *x; });
} else {
static_assert(detail::is_iterable_v<res_t>);
return map([cptr = ctx(), fn = std::move(f)](const Out& x) mutable {
return cptr->make_observable().from_container(fn(x));
})
.concat();
}
}
// -- observable: splitting ----------------------------------------------------
template <class T>
observable<cow_tuple<cow_vector<T>, observable<T>>>
observable<T>::prefix_and_tail(size_t n) {
using vector_t = cow_vector<T>;
CAF_ASSERT(n > 0);
auto do_prefetch = [](auto in) {
auto ptr = op::prefetch<T>::apply(std::move(in).as_observable().pimpl());
return observable<T>{std::move(ptr)};
};
auto split = share(2);
auto tail = split.skip(n).compose(do_prefetch);
return split //
.take(n)
.to_vector()
.filter([n](const vector_t& xs) { return xs.size() == n; })
.map([tail](const vector_t& xs) { return make_cow_tuple(xs, tail); })
.as_observable();
}
template <class T>
observable<cow_tuple<T, observable<T>>> observable<T>::head_and_tail() {
auto do_prefetch = [](auto in) {
auto ptr = op::prefetch<T>::apply(std::move(in).as_observable().pimpl());
return observable<T>{std::move(ptr)};
};
auto split = share(2);
auto tail = split.skip(1).compose(do_prefetch);
return split //
.take(1)
.map([tail](const T& x) { return make_cow_tuple(x, tail); })
.as_observable();
}
// -- observable: multicasting -------------------------------------------------
template <class T>
connectable<T> observable<T>::publish() {
return connectable<T>{make_counted<op::publish<T>>(ctx(), pimpl_)};
}
template <class T>
observable<T> observable<T>::share(size_t subscriber_threshold) {
return publish().ref_count(subscriber_threshold);
}
// -- observable: observing ----------------------------------------------------
template <class T>
observable<T> observable<T>::observe_on(coordinator* other, size_t buffer_size,
size_t min_request_size) {
auto [pull, push] = async::make_spsc_buffer_resource<T>(buffer_size,
min_request_size);
subscribe(push);
return make_observable<op::from_resource<T>>(other, std::move(pull));
}
// -- observable: converting ---------------------------------------------------
template <class T>
async::consumer_resource<T>
observable<T>::to_resource(size_t buffer_size, size_t min_request_size) {
using buffer_type = async::spsc_buffer<T>;
auto buf = make_counted<buffer_type>(buffer_size, min_request_size);
auto up = make_counted<buffer_writer_impl<buffer_type>>(pimpl_->ctx(), buf);
buf->set_producer(up);
subscribe(up->as_observer());
return async::consumer_resource<T>{std::move(buf)};
}
} // namespace caf::flow
| 31.027855 | 80 | 0.665589 | seewpx |
a6043bb22bd8a9000356a8292538a3e938df606c | 2,230 | cpp | C++ | daemon/src/win/win_main.cpp | realrasengan/desktop | 41213ed9efd70955bdd5872c68425868040afae2 | [
"Apache-2.0"
] | 1 | 2020-09-08T00:41:27.000Z | 2020-09-08T00:41:27.000Z | daemon/src/win/win_main.cpp | realrasengan/desktop | 41213ed9efd70955bdd5872c68425868040afae2 | [
"Apache-2.0"
] | null | null | null | daemon/src/win/win_main.cpp | realrasengan/desktop | 41213ed9efd70955bdd5872c68425868040afae2 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 London Trust Media Incorporated
//
// This file is part of the Private Internet Access Desktop Client.
//
// The Private Internet Access Desktop Client 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.
//
// The Private Internet Access Desktop Client 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 the Private Internet Access Desktop Client. If not, see
// <https://www.gnu.org/licenses/>.
#include "common.h"
#line SOURCE_FILE("win/win_main.cpp")
#if defined(PIA_CLIENT) || defined(UNIT_TEST)
// Entry point shouldn't be included for these projects
void dummyWinMain() {}
#else
#include "win_console.h"
#include "win_service.h"
#include "path.h"
#include "win.h"
#include <QTextStream>
int main(int argc, char** argv)
{
setUtf8LocaleCodec();
Logger::initialize(true);
FUNCTION_LOGGING_CATEGORY("win.main");
if (HRESULT error = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED))
qFatal("CoInitializeEx failed with error 0x%08x.", error);
if (HRESULT error = ::CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL))
qFatal("CoInitializeSecurity failed with error 0x%08x.", error);
switch (WinService::tryRun())
{
case WinService::SuccessfullyLaunched:
return 0;
case WinService::AlreadyRunning:
qCritical("Service is already running");
return 1;
case WinService::RunningAsConsole:
try
{
Path::initializePreApp();
QCoreApplication app(argc, argv);
Path::initializePostApp();
return WinConsole().run();
}
catch (const Error& error)
{
qCritical(error);
return 1;
}
}
}
#endif
| 30.135135 | 144 | 0.687444 | realrasengan |
a60656126010290ba54d6e86f35a8bb5a4879b24 | 1,232 | cpp | C++ | Math.cpp | Trofimm/SimpleFunctionRender | d1f81f4ce41c7c19f2caaabf602f96cc113774d5 | [
"MIT"
] | null | null | null | Math.cpp | Trofimm/SimpleFunctionRender | d1f81f4ce41c7c19f2caaabf602f96cc113774d5 | [
"MIT"
] | null | null | null | Math.cpp | Trofimm/SimpleFunctionRender | d1f81f4ce41c7c19f2caaabf602f96cc113774d5 | [
"MIT"
] | null | null | null | #include "Math.h"
//////////////////////////////////////////////////
float Distance(point2 a, point2 b)
{
const float x = b.x - a.x;
const float y = b.y - a.y;
const float result = sqrtf(x * x + y * y);
return result;
}
void SimpleCompress(float3 &outColor)
{
outColor.x /= (1.0f + outColor.x);
outColor.y /= (1.0f + outColor.y);
outColor.z /= (1.0f + outColor.z);
}
void Clamp(float3 & outColor)
{
if (outColor.x > 1.0f) outColor.x = 1.0f;
if (outColor.y > 1.0f) outColor.y = 1.0f;
if (outColor.z > 1.0f) outColor.z = 1.0f;
}
void ClampMinMax(float & a)
{
if (a > 1.0f) a = 1.0f;
else if (a < 0.0f) a = 0.0f;
}
inline vec3 rotate_x(vec3 v, float sin_ang, float cos_ang)
{
return vec3(
v.x,
(v.y * cos_ang) + (v.z * sin_ang),
(v.z * cos_ang) - (v.y * sin_ang)
);
}
inline vec3 rotate_y(vec3 v, float sin_ang, float cos_ang)
{
return vec3(
(v.x * cos_ang) + (v.z * sin_ang),
v.y,
(v.z * cos_ang) - (v.x * sin_ang)
);
}
float dot(const vec2 & u, const vec2 & v) { return { u.x*v.x + u.y*v.y }; }
vec2 VectorFromPoint(const point2 & a, const point2 & b) { return { a.x - b.x, a.y - b.y }; }
vec2 NormalToVect(const vec2 & a) { return { a.y * (-1.0f), a.x }; }
| 21.241379 | 94 | 0.54789 | Trofimm |
a619762b9d75c219320ef47e604702d07c1bab2f | 1,584 | cpp | C++ | examples/io.cpp | fdimushka/async_runtime | 964e6904c18739c67beab9a241a792467af7988b | [
"MIT"
] | 3 | 2022-03-28T07:40:37.000Z | 2022-03-30T06:48:35.000Z | examples/io.cpp | fdimushka/async_runtime | 964e6904c18739c67beab9a241a792467af7988b | [
"MIT"
] | 2 | 2022-03-28T10:37:30.000Z | 2022-03-31T10:47:40.000Z | examples/io.cpp | fdimushka/async_runtime | 964e6904c18739c67beab9a241a792467af7988b | [
"MIT"
] | null | null | null | #include "ar/ar.hpp"
using namespace AsyncRuntime;
void async_io(CoroutineHandler* handler, YieldVoid & yield) {
//make input stream
auto in_stream = MakeStream();
int res = 0;
int fd = 0;
yield();
//async open file
if( (res = Await(AsyncFsOpen("../../examples/io.cpp"), handler)) < 0 ) {
std::cerr << "Error open file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl;
return;
}
fd = res;
//async read file
if( (res = Await(AsyncFsRead(fd, in_stream), handler)) != IO_SUCCESS ) {
std::cerr << "Error read file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl;
return;
}
//async close file
Await(AsyncFsClose(fd), handler);
//make output stream with data from input stream
auto out_stream = MakeStream(in_stream->GetBuffer(), in_stream->GetBufferSize());
//async open file
if( (res = Await(AsyncFsOpen("tmp"), handler)) < 0 ) {
std::cerr << "Error open file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl;
return;
}
fd = res;
//async write to file
if( (res = Await(AsyncFsWrite(fd, out_stream), handler)) != IO_SUCCESS ) {
std::cerr << "Error write to file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl;
return;
}
//async close file
Await(AsyncFsClose(fd), handler);
}
int main() {
SetupRuntime();
Coroutine coro = MakeCoroutine(&async_io);
while (coro.Valid()) {
Await(Async(coro));
}
Terminate();
return 0;
}
| 23.294118 | 104 | 0.572601 | fdimushka |
a61c497aa31071e7d4a31b89ffa845dfc93555f6 | 1,222 | cpp | C++ | 3. Insertion in Singly Linked List/main.cpp | PriyanshuSaxena2612/Linked-List-Cpp | 759d97c6240fe70dbd8dd7b6e520bb7c86a231e5 | [
"MIT"
] | 5 | 2021-12-09T07:41:41.000Z | 2021-12-09T20:39:38.000Z | 3. Insertion in Singly Linked List/main.cpp | PriyanshuSaxena2612/Linked-List-Cpp | 759d97c6240fe70dbd8dd7b6e520bb7c86a231e5 | [
"MIT"
] | null | null | null | 3. Insertion in Singly Linked List/main.cpp | PriyanshuSaxena2612/Linked-List-Cpp | 759d97c6240fe70dbd8dd7b6e520bb7c86a231e5 | [
"MIT"
] | null | null | null | #include "../node.cpp"
void insertAtHead(Node **head, int data)
{
Node *newNode = new Node(data);
if (*head == NULL)
{
*head = newNode;
return;
}
newNode->next = *head;
*head = newNode;
}
void insertNode(Node **head, int data)
{
Node *newNode = new Node(data);
if (*head == NULL)
{
*head = newNode;
return;
}
Node *temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
void insertAtPosition(Node **head, int data, int pos)
{
Node *newNode = new Node(data);
int count = 1;
Node *temp = *head;
while (count < pos - 1)
{
temp = temp->next;
count++;
}
newNode->next = temp->next;
temp->next = newNode;
}
void recursiveTraversal(Node *head)
{
if (head == NULL)
{
return;
}
Node *temp = head;
cout << temp->data << "->";
recursiveTraversal(temp->next);
}
int main()
{
Node *head = new Node(1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
insertAtPosition(&head, 10, 5);
recursiveTraversal(head);
return 0;
} | 18.238806 | 53 | 0.531097 | PriyanshuSaxena2612 |
a61f7faa633d56942d20c3584a6699c32407f8b2 | 5,042 | cpp | C++ | Server/dep/g3dlite/G3D/Image1.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | 42 | 2015-01-05T10:00:07.000Z | 2022-02-18T14:51:33.000Z | Server/dep/g3dlite/G3D/Image1.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | 20 | 2017-04-10T18:41:58.000Z | 2017-04-10T19:01:12.000Z | Server/dep/g3dlite/G3D/Image1.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | 31 | 2015-01-09T02:04:29.000Z | 2021-09-01T13:20:20.000Z | /**
@file Image1.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2007-01-31
@edited 2007-01-31
*/
#include "G3D/Image1.h"
#include "G3D/Image1uint8.h"
#include "G3D/GImage.h"
#include "G3D/Color4.h"
#include "G3D/Color4uint8.h"
#include "G3D/Color1.h"
#include "G3D/Color1uint8.h"
#include "G3D/ImageFormat.h"
namespace G3D {
Image1::Image1(int w, int h, WrapMode wrap) : Map2D<Color1, Color1>(w, h, wrap) {
setAll(Color1(0.0f));
}
Image1::Ref Image1::fromGImage(const GImage& im, WrapMode wrap) {
switch (im.channels()) {
case 1:
return fromArray(im.pixel1(), im.width(), im.height(), wrap);
case 3:
return fromArray(im.pixel3(), im.width(), im.height(), wrap);
case 4:
return fromArray(im.pixel4(), im.width(), im.height(), wrap);
default:
debugAssertM(false, "Input GImage must have 1, 3, or 4 channels.");
return NULL;
}
}
Image1::Ref Image1::fromImage1uint8(const ReferenceCountedPointer<Image1uint8>& im) {
Ref out = createEmpty(static_cast<WrapMode>(im->wrapMode()));
out->resize(im->width(), im->height());
int N = im->width() * im->height();
const Color1uint8* src = reinterpret_cast<Color1uint8*>(im->getCArray());
for (int i = 0; i < N; ++i) {
out->data[i] = Color1(src[i]);
}
return out;
}
Image1::Ref Image1::createEmpty(int width, int height, WrapMode wrap) {
return new Type(width, height, wrap);
}
Image1::Ref Image1::createEmpty(WrapMode wrap) {
return createEmpty(0, 0, wrap);
}
Image1::Ref Image1::fromFile(const std::string& filename, WrapMode wrap, GImage::Format fmt) {
Ref out = createEmpty(wrap);
out->load(filename, fmt);
return out;
}
void Image1::load(const std::string& filename, GImage::Format fmt) {
copyGImage(GImage(filename, fmt));
setChanged(true);
}
Image1::Ref Image1::fromArray(const class Color3uint8* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
Image1::Ref Image1::fromArray(const class Color1* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
Image1::Ref Image1::fromArray(const class Color1uint8* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
Image1::Ref Image1::fromArray(const class Color3* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
Image1::Ref Image1::fromArray(const class Color4uint8* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
Image1::Ref Image1::fromArray(const class Color4* ptr, int w, int h, WrapMode wrap) {
Ref out = createEmpty(wrap);
out->copyArray(ptr, w, h);
return out;
}
void Image1::copyGImage(const GImage& im) {
switch (im.channels()) {
case 1:
copyArray(im.pixel1(), im.width(), im.height());
break;
case 3:
copyArray(im.pixel3(), im.width(), im.height());
break;
case 4:
copyArray(im.pixel4(), im.width(), im.height());
break;
}
}
void Image1::copyArray(const Color3uint8* src, int w, int h) {
resize(w, h);
int N = w * h;
Color1* dst = data.getCArray();
// Convert int8 -> float
for (int i = 0; i < N; ++i) {
dst[i] = Color1(Color3(src[i]).average());
}
}
void Image1::copyArray(const Color4uint8* src, int w, int h) {
resize(w, h);
int N = w * h;
Color1* dst = data.getCArray();
// Strip alpha and convert
for (int i = 0; i < N; ++i) {
dst[i] = Color1(Color3(src[i].rgb()).average());
}
}
void Image1::copyArray(const Color1* src, int w, int h) {
resize(w, h);
System::memcpy(getCArray(), src, w * h * sizeof(Color1));
}
void Image1::copyArray(const Color4* src, int w, int h) {
resize(w, h);
int N = w * h;
Color1* dst = data.getCArray();
// Strip alpha
for (int i = 0; i < N; ++i) {
dst[i] = Color1(src[i].rgb().average());
}
}
void Image1::copyArray(const Color1uint8* src, int w, int h) {
resize(w, h);
int N = w * h;
Color1* dst = getCArray();
for (int i = 0; i < N; ++i) {
dst[i]= Color1(src[i]);
}
}
void Image1::copyArray(const Color3* src, int w, int h) {
resize(w, h);
int N = w * h;
Color1* dst = getCArray();
for (int i = 0; i < N; ++i) {
dst[i] = Color1(src[i].average());
}
}
/** Saves in any of the formats supported by G3D::GImage. */
void Image1::save(const std::string& filename, GImage::Format fmt) {
GImage im(width(), height(), 1);
int N = im.width() * im.height();
Color1uint8* dst = im.pixel1();
for (int i = 0; i < N; ++i) {
dst[i] = Color1uint8(data[i]);
}
im.save(filename, fmt);
}
const ImageFormat* Image1::format() const {
return ImageFormat::L32F();
}
} // G3D
| 22.408889 | 94 | 0.598374 | ZON3DEV |
a621261f1c66ceafc64c96a4684ba870eae74337 | 46,870 | hpp | C++ | core/algorithms/techmapping/techmapping.hpp | LNIS-Projects/IDEA | 431ec3f30210bb901950f64c74efe480beca9f58 | [
"MIT"
] | 37 | 2018-08-12T11:25:57.000Z | 2020-11-30T16:09:41.000Z | core/algorithms/techmapping/techmapping.hpp | LNIS-Projects/IDEA | 431ec3f30210bb901950f64c74efe480beca9f58 | [
"MIT"
] | 9 | 2019-05-31T19:59:00.000Z | 2020-10-25T01:49:42.000Z | core/algorithms/techmapping/techmapping.hpp | LNIS-Projects/IDEA | 431ec3f30210bb901950f64c74efe480beca9f58 | [
"MIT"
] | 5 | 2019-01-10T19:38:54.000Z | 2020-06-09T11:38:08.000Z | /* LSOracle: A learning based Oracle for Logic Synthesis
* Copyright 2021 Laboratory for Nano Integrated Systems (LNIS)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <assert.h>
#include <algorithm>
#include <iterator>
#include <numeric>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <variant>
#include <vector>
#include <kitty/kitty.hpp>
#include <mockturtle/mockturtle.hpp>
namespace oracle
{
namespace techmap
{
struct cut {
explicit cut(size_t node) :
inputs{std::vector<size_t>{node}}, output{node}
{
}
explicit cut(std::vector<size_t> _inputs, size_t _output, kitty::dynamic_truth_table _truth_table) :
inputs{std::move(_inputs)}, output{_output}, truth_table{std::move(_truth_table)}
{
std::sort(inputs.begin(), inputs.end());
}
cut merge(cut const& rhs, size_t new_output) const
{
std::vector<size_t> new_inputs;
/*std::cout << "Merging [";
for (size_t input : inputs) {
std::cout << input << ", ";
}
std::cout << "] with [";
for (size_t input : rhs.inputs) {
std::cout << input << ", ";
}
std::cout << "] => [";*/
std::set_union(inputs.begin(), inputs.end(), rhs.inputs.begin(), rhs.inputs.end(), std::back_inserter(new_inputs));
/*for (size_t input : new_inputs) {
std::cout << input << ", ";
}
std::cout << "]\n";*/
return cut(std::move(new_inputs), new_output, kitty::dynamic_truth_table{});
}
int input_count() const
{
size_t input_count = inputs.size();
if (std::find(inputs.begin(), inputs.end(), 0) != inputs.end()) {
input_count -= 1;
}
if (std::find(inputs.begin(), inputs.end(), 1) != inputs.end()) {
input_count -= 1;
}
return input_count;
}
bool is_trivial() const
{
return inputs.size() == 1 && inputs[0] == output;
}
bool operator==(cut const& rhs) const {
return output == rhs.output && inputs == rhs.inputs;
}
std::vector<size_t> inputs;
size_t output;
kitty::dynamic_truth_table truth_table;
};
struct cell {
explicit cell(size_t _index, std::vector<kitty::dynamic_truth_table> _truth_table) :
index{_index}, truth_table{std::move(_truth_table)}
{
}
explicit cell(std::vector<kitty::dynamic_truth_table> _truth_table) :
index{}, truth_table{std::move(_truth_table)}
{
}
size_t index;
std::vector<kitty::dynamic_truth_table> truth_table;
};
struct lut {
explicit lut(kitty::dynamic_truth_table _truth_table) :
truth_table{std::move(_truth_table)}
{
}
kitty::dynamic_truth_table truth_table;
};
struct constant_zero {};
struct constant_one {};
struct primary_input {
explicit primary_input(size_t index) :
index{index}
{
}
size_t index;
};
struct primary_output {
explicit primary_output(size_t index) :
index{index}
{
}
size_t index;
};
struct connection {
explicit connection(size_t from, size_t to, size_t index) :
from{from}, to{to}, index{index}
{
}
size_t from;
size_t to;
size_t index;
};
template<class cell_type>
struct graph {
size_t add_constant_zero()
{
assert(!frozen);
size_t index = nodes.size();
nodes.push_back(constant_zero{});
return index;
}
size_t add_constant_one()
{
assert(!frozen);
size_t index = nodes.size();
nodes.push_back(constant_one{});
return index;
}
bool is_constant(size_t index) const
{
return std::holds_alternative<constant_zero>(nodes[index]) || std::holds_alternative<constant_one>(nodes[index]);
}
size_t add_primary_input()
{
assert(!frozen);
size_t index = nodes.size();
nodes.push_back(primary_input{index});
primary_inputs.push_back(index);
return index;
}
bool is_primary_input(size_t index) const
{
return std::holds_alternative<primary_input>(nodes[index]);
}
size_t add_primary_output()
{
assert(!frozen);
size_t index = nodes.size();
nodes.push_back(primary_output{index});
primary_outputs.push_back(index);
return index;
}
bool is_primary_output(size_t index) const
{
return std::holds_alternative<primary_output>(nodes[index]);
}
size_t add_cell(cell_type const& c)
{
assert(!frozen);
size_t index = nodes.size();
nodes.push_back(c);
return index;
}
size_t add_connection(size_t from, size_t to)
{
assert(!frozen);
auto index = connections.size();
connections.push_back(connection(from, to, index));
return index;
}
void remove_connection(size_t index)
{
assert(!frozen && "Attempted to remove connection from frozen graph");
connections[index].reset();
}
void freeze()
{
std::cout << "freezing graph...";
fflush(stdout);
node_fanin_nodes = std::vector<std::vector<size_t>>{nodes.size()};
node_fanout_nodes = std::vector<std::vector<size_t>>{nodes.size()};
// Populate the caches by computing topological orderings.
compute_topological_ordering();
compute_reverse_topological_ordering();
frozen = true;
std::cout << "done\n";
}
void unfreeze()
{
frozen = false;
}
void dump_to_stdout() const
{
std::cout << "digraph {\n";
// TODO: assuming constant drivers are always first two nodes is probably not smart.
assert(std::holds_alternative<constant_zero>(nodes[0]));
assert(std::holds_alternative<constant_one>(nodes[1]));
std::cout << "0 [shape=box label=\"Zero\"]\n";
std::cout << "1 [shape=box label=\"One\"]\n";
for (size_t pi : primary_inputs) {
std::cout << pi << " [shape=box label=\"PI " << std::get<primary_input>(nodes[pi]).index << "\"]\n";
}
for (size_t po : primary_outputs) {
std::cout << po << " [shape=box label=\"PO " << std::get<primary_output>(nodes[po]).index << "\"]\n";
}
for (size_t node = 0; node < nodes.size(); node++) {
if constexpr (std::is_same_v<cell_type, cell>) {
if (std::holds_alternative<cell>(nodes[node])) {
std::cout << node << " [label=\"Node " << node << " 0x";
kitty::print_hex(std::get<cell>(nodes[node]).truth_table[0]);
std::cout << "\"]\n";
}
} else if constexpr (std::is_same_v<cell_type, lut>) {
if (std::holds_alternative<lut>(nodes[node])) {
std::cout << node << " [label=\"Node " << node << " 0x";
kitty::print_hex(std::get<lut>(nodes[node]).truth_table);
std::cout << "\"]\n";
}
}
}
for (std::optional<connection> conn : connections) {
if (conn.has_value()) {
std::cout << conn->from << " -> " << conn->to << '\n';
}
}
std::cout << "}\n";
}
std::vector<connection> compute_node_fanin_connections(size_t node) const
{
std::vector<connection> fanin;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->to == node) {
fanin.push_back(*conn);
}
}
return fanin;
}
std::vector<size_t> compute_node_fanin_nodes(size_t node)
{
if (frozen && !node_fanin_nodes[node].empty()) {
return node_fanin_nodes[node];
}
std::vector<size_t> fanin;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->to == node) {
fanin.push_back(conn->from);
}
}
if (frozen) {
node_fanin_nodes[node] = fanin;
}
return fanin;
}
std::vector<size_t> compute_node_fanin_nodes(size_t node) const
{
if (frozen && !node_fanin_nodes[node].empty()) {
return node_fanin_nodes[node];
}
std::vector<size_t> fanin;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->to == node) {
fanin.push_back(conn->from);
}
}
return fanin;
}
std::vector<connection> compute_node_fanout_connections(size_t node) const
{
std::vector<connection> fanout;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->from == node) {
fanout.push_back(*conn);
}
}
return fanout;
}
std::vector<size_t> compute_node_fanout_nodes(size_t node)
{
if (frozen && !node_fanout_nodes[node].empty()) {
return node_fanout_nodes[node];
}
std::vector<size_t> fanout;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->from == node) {
fanout.push_back(conn->to);
}
}
if (frozen) {
node_fanout_nodes[node] = fanout;
}
return fanout;
}
std::vector<size_t> compute_node_fanout_nodes(size_t node) const
{
if (frozen && !node_fanout_nodes[node].empty()) {
return node_fanout_nodes[node];
}
std::vector<size_t> fanout;
for (std::optional<connection> const& conn : connections) {
if (conn && conn->from == node) {
fanout.push_back(conn->to);
}
}
return fanout;
}
std::vector<size_t> compute_topological_ordering()
{
if (frozen && !forward_topological_ordering.empty()) {
return forward_topological_ordering;
}
std::vector<size_t> ordering;
std::vector<size_t> no_incoming{primary_inputs};
graph g{*this};
g.unfreeze();
no_incoming.push_back(0);
no_incoming.push_back(1);
while (!no_incoming.empty()) {
size_t node = no_incoming.back();
ordering.push_back(node);
no_incoming.pop_back();
for (connection conn : g.compute_node_fanout_connections(node)) {
g.remove_connection(conn.index);
if (g.compute_node_fanin_connections(conn.to).empty()) {
no_incoming.push_back(conn.to);
}
}
}
// If `g` still has edges this is a cyclic graph, which cannot be topologically ordered.
bool remaining_edges = false;
for (std::optional<connection> const& conn : g.connections) {
if (conn) {
remaining_edges = true;
std::cout << conn->from << " -> " << conn->to << '\n';
}
}
if (remaining_edges) {
throw std::logic_error{"input graph is cyclic or has nodes not reachable from primary inputs"};
}
if (frozen) {
forward_topological_ordering = ordering;
}
return ordering;
}
std::vector<size_t> compute_topological_ordering() const
{
if (frozen && !forward_topological_ordering.empty()) {
return forward_topological_ordering;
}
std::vector<size_t> ordering;
std::vector<size_t> no_incoming{primary_inputs};
graph g{*this};
g.unfreeze();
no_incoming.push_back(0);
no_incoming.push_back(1);
while (!no_incoming.empty()) {
size_t node = no_incoming.back();
ordering.push_back(node);
no_incoming.pop_back();
for (connection conn : g.compute_node_fanout_connections(node)) {
g.remove_connection(conn.index);
if (g.compute_node_fanin_connections(conn.to).empty()) {
no_incoming.push_back(conn.to);
}
}
}
// If `g` still has edges this is a cyclic graph, which cannot be topologically ordered.
bool remaining_edges = false;
for (std::optional<connection> const& conn : g.connections) {
if (conn) {
remaining_edges = true;
std::cout << conn->from << " -> " << conn->to << '\n';
}
}
if (remaining_edges) {
throw std::logic_error("input graph is cyclic or has nodes not reachable from primary inputs");
}
return ordering;
}
std::vector<size_t> compute_reverse_topological_ordering()
{
if (frozen && !reverse_topological_ordering.empty()) {
return reverse_topological_ordering;
}
std::vector<size_t> ordering;
std::vector<size_t> no_outgoing{primary_outputs};
graph g{*this};
g.unfreeze();
while (!no_outgoing.empty()) {
size_t node = no_outgoing.back();
ordering.push_back(node);
no_outgoing.pop_back();
for (connection conn : g.compute_node_fanin_connections(node)) {
g.remove_connection(conn.index);
if (g.compute_node_fanout_connections(conn.from).empty()) {
no_outgoing.push_back(conn.from);
}
}
}
// If `g` still has edges this is a cyclic graph, which cannot be topologically ordered.
bool remaining_edges = false;
for (std::optional<connection> const& conn : g.connections) {
if (conn) {
remaining_edges = true;
std::cout << conn->from << " -> " << conn->to << '\n';
}
}
if (remaining_edges) {
throw std::logic_error("input graph is cyclic or has nodes not reachable from primary inputs");
}
if (frozen) {
reverse_topological_ordering = ordering;
}
return ordering;
}
std::vector<size_t> nodes_in_cut(cut const& c) const
{
// Perform a reverse topological ordering to discover nodes in the cut
// and then a forward topological ordering to produce useful output.
std::vector<size_t> ordering;
std::vector<size_t> no_outgoing{c.output};
graph g{*this};
g.unfreeze();
while (!no_outgoing.empty()) {
size_t node = no_outgoing.back();
no_outgoing.pop_back();
if (std::find(c.inputs.begin(), c.inputs.end(), node) == c.inputs.end()) {
ordering.push_back(node);
for (connection conn : g.compute_node_fanin_connections(node)) {
no_outgoing.push_back(conn.from);
}
}
}
// ordering now contains a reverse topological order of the nodes.
// TODO: does this actually produce a forward topological order?
std::reverse(ordering.begin(), ordering.end());
return ordering;
}
kitty::dynamic_truth_table simulate(cut const& c) const
{
const std::vector<size_t> cut_nodes{nodes_in_cut(c)};
kitty::dynamic_truth_table result{static_cast<uint32_t>(c.inputs.size())};
// TODO: skip constant drivers when found.
const int limit = 1 << c.inputs.size();
for (unsigned int mask = 0; mask < limit; mask++) {
std::unordered_map<size_t, bool> values{};
// Constant drivers.
values.insert({0, false});
values.insert({1, true});
for (int input = 0; input < c.inputs.size(); input++) {
values.insert({c.inputs[input], ((1 << input) & mask) != 0});
}
for (size_t node : cut_nodes) {
if (std::holds_alternative<cell>(nodes[node])) {
cell const& n = std::get<cell>(nodes[node]);
std::vector<size_t> fanin = compute_node_fanin_nodes(node);
uint64_t node_mask = 0;
for (unsigned int fanin_node = 0; fanin_node < fanin.size(); fanin_node++) {
if (values.find(fanin[fanin_node]) == values.end()) {
std::cout << "while simulating cut [";
for (size_t input : c.inputs) {
std::cout << input << ", ";
}
std::cout << "] -> " << c.output << ":\n";
std::cout << "at node " << fanin[fanin_node] << ":\n";
throw std::logic_error{"fanin node not in simulation values"};
}
node_mask |= int{values.at(fanin[fanin_node])} << fanin_node;
}
// TODO: assumes cell has a single output.
values.insert({node, kitty::get_bit(n.truth_table[0], node_mask)});
} else if (is_constant(node)) {
continue;
}
}
if (values.at(c.output)) {
kitty::set_bit(result, mask);
}
}
return result;
}
std::vector<size_t> primary_inputs;
std::vector<size_t> primary_outputs;
std::vector<std::variant<constant_zero, constant_one, primary_input, primary_output, cell_type>> nodes;
std::vector<std::optional<connection>> connections;
bool frozen;
std::vector<size_t> forward_topological_ordering;
std::vector<size_t> reverse_topological_ordering;
std::vector<std::vector<size_t>> node_fanin_nodes;
std::vector<std::vector<size_t>> node_fanout_nodes;
};
struct mapping_settings {
unsigned int cut_input_limit;
unsigned int node_cut_count;
unsigned int lut_area[8];
unsigned int lut_delay[8];
unsigned int wire_delay;
};
struct mapping_info {
std::optional<cut> selected_cut;
std::optional<kitty::dynamic_truth_table> truth_table;
unsigned int depth;
int references; // Signed to detect underflow.
float area_flow;
unsigned int required;
};
struct frontier_info {
explicit frontier_info(size_t node) :
cuts{std::vector<cut>{cut{node}}}
{
}
explicit frontier_info(std::vector<cut> _cuts) :
cuts{std::move(_cuts)}
{
}
std::vector<cut> cuts;
};
class mapper {
public:
explicit mapper(graph<cell> _g, mapping_settings _settings) :
g{std::move(_g)}, info{g.nodes.size()}, settings{_settings}
{
assert(settings.cut_input_limit >= 2 && "invalid argument: mapping for less than 2 inputs is impossible");
assert(settings.node_cut_count >= 1 && "invalid argument: must store at least one cut per node");
// For now:
std::fill(settings.lut_area, settings.lut_area + 9, 1);
settings.lut_area[5] = 2;
settings.lut_area[6] = 4;
settings.lut_area[7] = 8;
settings.lut_area[8] = 16;
std::fill(settings.lut_delay, settings.lut_delay + 9, 1);
settings.lut_delay[1] = 141;
settings.lut_delay[2] = 275;
settings.lut_delay[3] = 379;
settings.lut_delay[4] = 379;
settings.lut_delay[5] = 477;
settings.lut_delay[6] = 618;
settings.lut_delay[7] = 759;
settings.wire_delay = 300;
std::fill(info.begin(), info.end(), mapping_info{});
}
graph<lut> map()
{
g.freeze();
std::cout << "Input graph has " << g.nodes.size() << " nodes and " << g.connections.size() << " edges.\n";
std::cout << "Mapping phase 1: prioritise depth.\n";
enumerate_cuts(false, false);
// After depth mapping, recalculate node slacks.
recalculate_slack();
//derive_mapping();
std::cout << "Mapping phase 2: prioritise global area.\n";
enumerate_cuts(true, false);
//derive_mapping();
enumerate_cuts(true, false);
//derive_mapping();
std::cout << "Mapping phase 3: prioritise local area.\n";
enumerate_cuts(true, true);
//derive_mapping();
enumerate_cuts(true, true);
print_stats();
std::cout << "Deriving the final mapping of the network.\n";
return derive_mapping(true);
}
private:
void enumerate_cuts(bool area_optimisation, bool local_area)
{
std::unordered_map<size_t, frontier_info> frontier;
// TODO: ABC computes the graph crosscut to pre-allocate frontier memory.
// Initialise frontier with the trivial cuts of primary inputs.
frontier.insert({0, frontier_info{0}});
frontier.insert({1, frontier_info{1}});
for (size_t pi : g.primary_inputs) {
frontier.insert({pi, frontier_info{pi}});
}
for (size_t node : g.compute_topological_ordering()) {
// Skip primary inputs, primary outputs, and constants.
if (g.is_primary_input(node) || g.is_primary_output(node) || g.is_constant(node)) {
continue;
}
// Find the node cut set.
std::vector<cut> cut_set = node_cut_set(node, frontier);
// Sort the cuts by desired characteristics.
if (!area_optimisation) {
std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) {
return cut_depth(a, info) < cut_depth(b, info) ||
(cut_depth(a, info) == cut_depth(b, info) && cut_input_count(a, info) < cut_input_count(b, info)) ||
(cut_depth(a, info) == cut_depth(b, info) && cut_input_count(a, info) == cut_input_count(b, info) && cut_area_flow(a, info) < cut_area_flow(b, info));
});
} else if (!local_area) {
std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) {
return cut_area_flow(a, info) < cut_area_flow(b, info) ||
(cut_area_flow(a, info) == cut_area_flow(b, info) && cut_fanin_refs(a, info) < cut_fanin_refs(b, info)) ||
(cut_area_flow(a, info) == cut_area_flow(b, info) && cut_fanin_refs(a, info) == cut_fanin_refs(b, info) && cut_depth(a, info) < cut_depth(b, info));
});
} else {
std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) {
return cut_exact_area(a) < cut_exact_area(b) ||
(cut_exact_area(a) == cut_exact_area(b) && cut_fanin_refs(a, info) < cut_fanin_refs(b, info)) ||
(cut_exact_area(a) == cut_exact_area(b) && cut_fanin_refs(a, info) == cut_fanin_refs(b, info) && cut_depth(a, info) < cut_depth(b, info));
});
}
// Deduplicate cuts to ensure diversity.
cut_set.erase(std::unique(cut_set.begin(), cut_set.end()), cut_set.end());
// Prune cuts which exceed the node slack in area optimisation mode.
if (area_optimisation) {
if (std::all_of(cut_set.begin(), cut_set.end(), [&](cut const& c) {
return cut_depth(c, info) > info[node].required;
})) {
std::cout << "Required time of node " << node << " is " << info[node].required << '\n';
std::cout << "Depth of cuts:\n";
for (cut const& c : cut_set) {
std::cout << "[";
for (size_t input : c.inputs) {
std::cout << input << " @ " << cut_depth(*info[input].selected_cut, info) << ", ";
}
std::cout << "] -> " << c.output << " = " << cut_depth(c, info) << '\n';
}
fflush(stdout);
}
cut_set.erase(std::remove_if(cut_set.begin(), cut_set.end(), [&](cut const& c) {
return cut_depth(c, info) > info[node].required;
}), cut_set.end());
// Because the previous cut is included in the set and must meet required times
// we must have at least one cut left from this.
if (cut_set.empty()) {
throw std::logic_error{"bug: no cuts meet node required time"};
}
}
// Keep only the specified good cuts.
if (cut_set.size() > settings.node_cut_count) {
cut_set.erase(cut_set.begin()+settings.node_cut_count, cut_set.end());
}
// We should have at least one cut provided by the trivial cut.
if (cut_set.empty()) {
throw std::logic_error{"bug: node has no cuts"};// TODO: maybe this is redundant given the assert in area_optimisation?
}
// If there's a representative cut for this node already, decrement its references first.
if (info[node].selected_cut.has_value()) {
cut_deref(*info[node].selected_cut);
}
// Choose the best cut as the representative cut for this node.
cut_ref(cut_set[0]);
// Add the cut set of this node to the frontier.
info[node].selected_cut = std::make_optional(cut_set[0]);
info[node].depth = cut_depth(cut_set[0], info);
info[node].area_flow = cut_area_flow(cut_set[0], info);
frontier.insert({node, frontier_info{std::move(cut_set)}});
// Erase fan-in nodes that have their fan-out completely mapped as they will never be used again.
for (size_t fanin_node : g.compute_node_fanin_nodes(node)) {
std::vector<size_t> node_fanout{g.compute_node_fanout_nodes(fanin_node)};
if (std::all_of(node_fanout.begin(), node_fanout.end(), [&](size_t node) {
return info[node].selected_cut.has_value();
})) {
//frontier.erase(fanin_node);
}
}
}
}
void recalculate_slack()
{
// First find the maximum depth of the mapping.
unsigned int max_depth = 0;
for (size_t node = 0; node < g.nodes.size(); node++) {
if (std::holds_alternative<cell>(g.nodes[node])) {
if (info[node].depth > max_depth) {
max_depth = info[node].depth;
}
}
}
std::cout << "Maximum depth of network is " << max_depth << '\n';
std::cout << "Propagating arrival times...";
fflush(stdout);
// Next, initialise the node required times.
for (mapping_info& node : info) {
node.required = max_depth;
}
// Then work from PO to PI, propagating required times.
for (size_t node : g.compute_reverse_topological_ordering()) {
if (g.is_primary_output(node)) {
info[node].required = max_depth;
} else if (std::holds_alternative<cell>(g.nodes[node])) {
if (!info[node].selected_cut.has_value()) {
throw std::logic_error{"bug: cell has no selected cut"};
}
unsigned int required = info[node].required - settings.lut_delay[info[node].selected_cut->input_count()];
for (size_t cut_input : info[node].selected_cut->inputs) {
//std::cout << "Setting required time of node " << cut_input << " to " << std::min(info[cut_input].required, required) << '\n';
info[cut_input].required = std::min(info[cut_input].required, required);
if (info[cut_input].required >= info[node].required) {
throw std::logic_error{"bug: cut input has greater required time than cut output"};
}
// If we end up with a negative required time, we have a bug. For instance, this might fire if:
// - the maximum depth isn't actually the maximum depth
// - the graph has a loop
if (info[cut_input].required < 0) {
throw std::logic_error{"bug: node has negative required time"};
}
}
}
}
std::cout << "done\n";
}
void print_stats() const
{
// The mapping frontier is the list of all nodes which do not have selected cuts.
// We start with the primary outputs and work downwards.
std::vector<size_t> frontier;
std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) {
return po;
});
std::unordered_map<size_t, bool> gate_graph_to_lut_graph;
// Populate the LUT graph with the primary inputs and outputs of the gate graph.
gate_graph_to_lut_graph.insert({0, true});
gate_graph_to_lut_graph.insert({1, true});
for (size_t pi : g.primary_inputs) {
gate_graph_to_lut_graph.insert({pi, true});
}
for (size_t po : g.primary_outputs) {
gate_graph_to_lut_graph.insert({po, true});
}
std::vector<size_t> lut_stats;
for (int i = 0; i <= settings.cut_input_limit; i++) {
lut_stats.push_back(0);
}
// While there are still nodes to be mapped:
while (!frontier.empty()) {
// Pop a node from the mapping frontier.
size_t node = frontier.back();
frontier.pop_back();
// Add the node to the mapping graph.
if (!g.is_primary_input(node) && !g.is_primary_output(node)) {
gate_graph_to_lut_graph.insert({node, true});
lut_stats[info[node].selected_cut->input_count()]++;
}
// Add all the inputs in that cut which are not primary inputs or already-discovered nodes to the mapping frontier.
if (g.is_primary_output(node)) {
for (size_t input : g.compute_node_fanin_nodes(node)) {
frontier.push_back(input);
break;
}
}
for (size_t input : info[node].selected_cut->inputs) {
if (!g.is_primary_input(input) && !gate_graph_to_lut_graph.count(input)) {
frontier.push_back(input);
}
}
}
size_t total_luts = 0;
for (int lut_size = 1; lut_size <= settings.cut_input_limit; lut_size++) {
std::cout << "LUT" << lut_size << ": " << lut_stats[lut_size] << '\n';
total_luts += lut_stats[lut_size];
}
std::cout << "LUTs: " << total_luts << '\n';
}
graph<lut> derive_mapping(bool simulate) const
{
// The mapping frontier is the list of all nodes which do not have selected cuts.
// We start with the primary outputs and work downwards.
std::vector<size_t> frontier;
std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) {
return po;
});
std::unordered_map<size_t, size_t> gate_graph_to_lut_graph;
graph<lut> mapping;
// Populate the LUT graph with the primary inputs and outputs of the gate graph.
gate_graph_to_lut_graph.insert({0, mapping.add_constant_zero()});
gate_graph_to_lut_graph.insert({1, mapping.add_constant_one()});
for (size_t pi : g.primary_inputs) {
size_t index = mapping.add_primary_input();
gate_graph_to_lut_graph.insert({pi, index});
}
for (size_t po : g.primary_outputs) {
size_t index = mapping.add_primary_output();
gate_graph_to_lut_graph.insert({po, index});
}
// While there are still nodes to be mapped:
while (!frontier.empty()) {
// Pop a node from the mapping frontier.
size_t node = frontier.back();
frontier.pop_back();
// Add the node to the mapping graph.
if (!g.is_primary_input(node) && !g.is_primary_output(node)) {
kitty::dynamic_truth_table tt{};
if (simulate) {
tt = g.simulate(*info[node].selected_cut);
}
size_t index = mapping.add_cell(lut{tt});
gate_graph_to_lut_graph.insert({node, index});
}
// Add all the inputs in that cut which are not primary inputs or already-discovered nodes to the mapping frontier.
if (g.is_primary_output(node)) {
for (size_t input : g.compute_node_fanin_nodes(node)) {
frontier.push_back(input);
break;
}
}
for (size_t input : info[node].selected_cut->inputs) {
if (!g.is_primary_input(input) && !gate_graph_to_lut_graph.count(input)) {
frontier.push_back(input);
}
}
}
// Walk the frontier again, but this time populating the graph with connections.
std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) {
return po;
});
std::unordered_set<size_t> visited;
while (!frontier.empty()) {
// Pop a node from the mapping frontier.
size_t node = frontier.back();
frontier.pop_back();
visited.insert(node);
if (g.is_primary_output(node)) {
for (size_t input : g.compute_node_fanin_nodes(node)) {
frontier.push_back(input);
mapping.add_connection(gate_graph_to_lut_graph.at(input), gate_graph_to_lut_graph.at(node));
break;
}
} else {
for (size_t input : info[node].selected_cut->inputs) {
if (!g.is_primary_input(input) && !visited.count(input)) {
frontier.push_back(input);
}
mapping.add_connection(gate_graph_to_lut_graph.at(input), gate_graph_to_lut_graph.at(node));
}
}
}
return mapping;
}
std::vector<cut> node_cut_set(size_t node, std::unordered_map<size_t, frontier_info> const& frontier) const
{
assert(std::holds_alternative<cell>(g.nodes[node]));
assert(std::get<cell>(g.nodes[node]).truth_table.size() == 1 && "not implemented: multiple output gates");
std::vector<size_t> node_inputs{g.compute_node_fanin_nodes(node)};
// To calculate the cut set of a node, we need to compute the cartesian product of its child cuts.
// This is implemented as performing a 2-way cartesian product N times.
// Start with the cut set of input zero.
if (node_inputs.empty()) {
std::cout << "node: " << node << '\n';
throw std::logic_error{"node_cut_set called on node without fanin"};
}
std::vector<cut> cut_set{frontier.at(node_inputs[0]).cuts};
// Append the trivial cut of input zero.
cut_set.push_back(cut{node_inputs[0]});
// For each other input:
if (node_inputs.size() > 1) {
std::for_each(node_inputs.begin()+1, node_inputs.end(), [&](size_t node_input) {
if (frontier.find(node_input) == frontier.end()) {
throw std::logic_error("bug: mapping frontier does not contain node");
}
std::vector<cut> new_cuts;
// Merge the present cut set with the cuts of this input.
for (cut const& c : cut_set) {
for (int input_cut = 0; input_cut < frontier.at(node_input).cuts.size(); input_cut++) {
new_cuts.push_back(c.merge(frontier.at(node_input).cuts[input_cut], node));
new_cuts.push_back(c.merge(cut{node_input}, node));
}
}
// Filter out cuts which exceed the cut input limit.
new_cuts.erase(std::remove_if(new_cuts.begin(), new_cuts.end(), [=](cut const& candidate) {
return candidate.input_count() > settings.cut_input_limit;
}), new_cuts.end());
// TODO: is it sound to keep a running total of the N best cuts and prune cuts that are worse than the limit?
// Or does that negatively affect cut quality?
// Replace the present cut set with the new one.
cut_set = std::move(new_cuts);
});
} else {
// When we have only a single input, we end up with the cut set of that input.
// We need to patch the cut set to set the cut outputs as this node.
for (cut& c : cut_set) {
c.output = node;
}
}
// Also include the previous-best cut in the cut set, if it exists, to avoid forgetting good cuts.
if (info[node].selected_cut.has_value()) {
cut_set.push_back(*info[node].selected_cut);
}
return cut_set;
}
// Ordering by cut depth is vital to find the best possible mapping for a network.
unsigned int cut_depth(cut const& c, std::vector<mapping_info> const& info)
{
unsigned int depth = 0;
for (size_t input : c.inputs) {
if (info.at(input).depth > depth) {
depth = info.at(input).depth;
}
}
return depth + settings.lut_delay[c.input_count()];
}
// It is better to prefer smaller cuts over bigger cuts because it allows more cuts to be mapped
// for the same network depth.
unsigned int cut_input_count(cut const& c, std::vector<mapping_info> const& info)
{
(void)info;
return c.input_count();
}
// Preferring cuts with lower fanin references aims to reduce mapping duplication
// where a node is covered by multiple mappings at the same time.
float cut_fanin_refs(cut const& c, std::vector<mapping_info> const& info)
{
float references = 0.0;
for (size_t input : c.inputs) {
references += float(info.at(input).references);
}
return references / float(c.input_count());
}
// Area flow estimates how much this cone of logic is shared within the current mapping.
float cut_area_flow(cut const& c, std::vector<mapping_info> const& info)
{
float sum_area_flow = float(settings.lut_area[c.input_count()]);
for (size_t input : c.inputs) {
sum_area_flow += info.at(input).area_flow;
}
return sum_area_flow / std::max(1.0f, float(info.at(c.output).references));
}
// Exact area calculates the number of LUTs that would be added to the mapping if this cut was selected.
unsigned int cut_exact_area(cut const& c)
{
if (info.at(c.output).selected_cut.has_value()) {
if (c == *info.at(c.output).selected_cut) {
auto area2 = exact_area_ref(c);
auto area1 = exact_area_deref(c);
if (area1 != area2) {
throw std::logic_error("bug: mismatch between number of nodes referenced and dereferenced");
}
return area1;
}
}
auto area2 = exact_area_ref(c);
auto area1 = exact_area_deref(c);
if (area1 != area2) {
throw std::logic_error("bug: mismatch between number of nodes referenced and dereferenced");
}
return area1;
}
unsigned int exact_area_deref(cut const& c)
{
unsigned int area = settings.lut_area[c.input_count()];
for (size_t cut_input : c.inputs) {
if (std::holds_alternative<cell>(g.nodes[cut_input])) {
if (info.at(cut_input).references <= 0) {
std::cout << "At node " << cut_input << ":\n";
fflush(stdout);
throw std::logic_error{"exact_area_deref: bug: decremented node reference below zero"};
}
info.at(cut_input).references--;
if (info.at(cut_input).references == 0) {
area += exact_area_deref(*info.at(cut_input).selected_cut);
}
}
}
return area;
}
unsigned int exact_area_ref(cut const& c)
{
unsigned int area = settings.lut_area[c.input_count()];
for (size_t cut_input : c.inputs) {
if (std::holds_alternative<cell>(g.nodes[cut_input])) {
if (info.at(cut_input).references == 0) {
area += exact_area_ref(*info.at(cut_input).selected_cut);
}
info.at(cut_input).references++;
}
}
return area;
}
void cut_deref(cut const& c)
{
for (size_t cut_input : c.inputs) {
if (std::holds_alternative<cell>(g.nodes[cut_input])) {
if (info.at(cut_input).references <= 0) {
std::cout << "At node " << cut_input << ":\n";
fflush(stdout);
throw std::logic_error{"cut_deref: bug: decremented node reference below zero"};
}
info.at(cut_input).references--;
info.at(cut_input).area_flow = cut_area_flow(*info.at(cut_input).selected_cut, info);
if (info.at(cut_input).references == 0) {
cut_deref(*info.at(cut_input).selected_cut);
}
}
}
}
void cut_ref(cut const& c)
{
for (size_t cut_input : c.inputs) {
if (std::holds_alternative<cell>(g.nodes[cut_input])) {
if (info.at(cut_input).references == 0) {
cut_ref(*info.at(cut_input).selected_cut);
}
info.at(cut_input).references++;
info.at(cut_input).area_flow = cut_area_flow(*info.at(cut_input).selected_cut, info);
}
}
}
graph<cell> g;
std::vector<mapping_info> info;
mapping_settings settings;
};
template<class Ntk>
graph<cell> mockturtle_to_lut_graph(Ntk const& input_ntk)
{
static_assert(mockturtle::is_network_type_v<Ntk>);
static_assert(mockturtle::has_foreach_pi_v<Ntk>);
static_assert(mockturtle::has_foreach_po_v<Ntk>);
static_assert(mockturtle::has_foreach_node_v<Ntk>);
static_assert(mockturtle::has_cell_function_v<Ntk>);
mockturtle::klut_network ntk = mockturtle::gates_to_nodes<mockturtle::klut_network, Ntk>(input_ntk);
graph<cell> g{};
std::unordered_map<mockturtle::klut_network::node, size_t> mockturtle_to_node{};
mockturtle_to_node.insert({ntk.get_node(ntk.get_constant(false)), g.add_constant_zero()});
mockturtle_to_node.insert({ntk.get_node(ntk.get_constant(true)), g.add_constant_one()});
ntk.foreach_pi([&](mockturtle::klut_network::node const& node, uint32_t index) -> void {
size_t pi = g.add_primary_input();
mockturtle_to_node.insert({node, pi});
});
ntk.foreach_node([&](mockturtle::klut_network::node const& node) -> void {
if (!ntk.is_constant(node)) {
std::vector<kitty::dynamic_truth_table> truth_table{};
truth_table.push_back(ntk.node_function(node));
size_t c = g.add_cell(cell{truth_table});
mockturtle_to_node.insert({node, c});
ntk.foreach_fanin(node, [&](mockturtle::klut_network::signal const& fanin) -> void {
g.add_connection(mockturtle_to_node.at(ntk.get_node(fanin)), mockturtle_to_node.at(node));
});
}
});
ntk.foreach_po([&](mockturtle::klut_network::signal const& signal, uint32_t index) -> void {
size_t po = g.add_primary_output();
g.add_connection(mockturtle_to_node.at(ntk.get_node(signal)), po);
});
mockturtle::write_blif(ntk, "c432.before.blif");
//g.dump_to_stdout();
return g;
}
mockturtle::klut_network lut_graph_to_mockturtle(graph<lut> const& g)
{
mockturtle::klut_network ntk{};
std::unordered_map<size_t, mockturtle::klut_network::signal> node_to_mockturtle{};
//g.dump_to_stdout();
node_to_mockturtle.insert({0, ntk.get_constant(0)});
node_to_mockturtle.insert({1, ntk.get_constant(1)});
for (size_t pi : g.primary_inputs) {
node_to_mockturtle.insert({pi, ntk.create_pi()});
}
for (size_t node : g.compute_topological_ordering()) {
std::vector<mockturtle::klut_network::signal> children{};
for (size_t input : g.compute_node_fanin_nodes(node)) {
children.push_back(node_to_mockturtle.at(input));
}
if (!g.is_primary_input(node) && !g.is_primary_output(node) && !g.is_constant(node)) {
node_to_mockturtle.insert({node, ntk.create_node(children, std::get<lut>(g.nodes[node]).truth_table)});
}
}
for (size_t po : g.primary_outputs) {
for (size_t fanin : g.compute_node_fanin_nodes(po)) {
if (node_to_mockturtle.find(fanin) == node_to_mockturtle.end()) {
std::cout << "Node " << fanin << " not in node_to_mockturtle\n";
}
node_to_mockturtle.insert({po, ntk.create_po(node_to_mockturtle.at(fanin))});
break;
}
}
mockturtle::write_blif(ntk, "c432.after.blif");
return ntk;
}
} // namespace techmap
} // namespace oracle
| 34.847584 | 174 | 0.564199 | LNIS-Projects |
a625a8582b06e40e65e7d416fab4d823d349b2a6 | 830 | hpp | C++ | includes/metrisca/profilers/profiler.hpp | mirjanastojilovic/MetriSCA | a0a13a17d66324088114a1d4ab96afc0da487bf7 | [
"BSD-3-Clause"
] | 2 | 2022-02-18T12:11:28.000Z | 2022-03-01T19:23:26.000Z | includes/metrisca/profilers/profiler.hpp | mirjanastojilovic/MetriSCA | a0a13a17d66324088114a1d4ab96afc0da487bf7 | [
"BSD-3-Clause"
] | 1 | 2022-03-06T13:32:58.000Z | 2022-03-06T15:38:16.000Z | includes/metrisca/profilers/profiler.hpp | mirjanastojilovic/MetriSCA | a0a13a17d66324088114a1d4ab96afc0da487bf7 | [
"BSD-3-Clause"
] | 1 | 2022-03-18T11:55:36.000Z | 2022-03-18T11:55:36.000Z | /**
* MetriSCA - A side-channel analysis library
* Copyright 2021, School of Computer and Communication Sciences, EPFL.
*
* All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE.md file.
*/
#pragma once
#include "metrisca/forward.hpp"
#include "metrisca/core/plugin.hpp"
namespace metrisca {
class ProfilerPlugin : public Plugin {
public:
ProfilerPlugin()
: Plugin(PluginType::Profiler)
{}
virtual ~ProfilerPlugin() = default;
virtual Result<void, Error> Init(const ArgumentList& args) override;
virtual Result<Matrix<double>, Error> Profile() = 0;
protected:
std::shared_ptr<TraceDataset> m_Dataset{ nullptr };
uint8_t m_KnownKey{};
uint32_t m_ByteIndex{};
};
}
| 24.411765 | 76 | 0.662651 | mirjanastojilovic |
98b54c286fdc116585c460370cfcd126e9256d6a | 1,396 | cpp | C++ | libs/optional/test/optional_test_tie.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/optional/test/optional_test_tie.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/optional/test/optional_test_tie.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Copyright (C) 2003, Fernando Luis Cacciola Carballal.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/lib/optional for documentation.
//
// You are welcome to contact the author at:
// [email protected]
//
#include<iostream>
#include<stdexcept>
#include<string>
#define BOOST_ENABLE_ASSERT_HANDLER
#include "boost/optional.hpp"
#include "boost/tuple/tuple.hpp"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "boost/test/minimal.hpp"
#include "optional_test_common.cpp"
// Test boost::tie() interoperabiliy.
int test_main( int, char* [] )
{
typedef X T ;
try
{
TRACE( std::endl << BOOST_CURRENT_FUNCTION );
T z(0);
T a(1);
T b(2);
optional<T> oa, ob ;
// T::T( T const& x ) is used
set_pending_dtor( ARG(T) ) ;
set_pending_copy( ARG(T) ) ;
boost::tie(oa,ob) = std::make_pair(a,b) ;
check_is_not_pending_dtor( ARG(T) ) ;
check_is_not_pending_copy( ARG(T) ) ;
check_initialized(oa);
check_initialized(ob);
check_value(oa,a,z);
check_value(ob,b,z);
}
catch ( ... )
{
BOOST_ERROR("Unexpected Exception caught!");
}
return 0;
}
| 21.476923 | 75 | 0.627507 | zyiacas |
98b9bee187d895e3efca00fe3cef3ec1b520b195 | 7,901 | hpp | C++ | include/LIV/SDK/Unity/SDKControllerState.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/LIV/SDK/Unity/SDKControllerState.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/LIV/SDK/Unity/SDKControllerState.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: LIV.SDK.Unity.SDKVector3
#include "LIV/SDK/Unity/SDKVector3.hpp"
// Including type: LIV.SDK.Unity.SDKQuaternion
#include "LIV/SDK/Unity/SDKQuaternion.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Type namespace: LIV.SDK.Unity
namespace LIV::SDK::Unity {
// Forward declaring type: SDKControllerState
struct SDKControllerState;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::LIV::SDK::Unity::SDKControllerState, "LIV.SDK.Unity", "SDKControllerState");
// Type namespace: LIV.SDK.Unity
namespace LIV::SDK::Unity {
// Size: 0x8C
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: LIV.SDK.Unity.SDKControllerState
// [TokenAttribute] Offset: FFFFFFFF
struct SDKControllerState/*, public ::System::ValueType*/ {
public:
public:
// public LIV.SDK.Unity.SDKVector3 hmdposition
// Size: 0xC
// Offset: 0x0
::LIV::SDK::Unity::SDKVector3 hmdposition;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC);
// public LIV.SDK.Unity.SDKQuaternion hmdrotation
// Size: 0x10
// Offset: 0xC
::LIV::SDK::Unity::SDKQuaternion hmdrotation;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10);
// public LIV.SDK.Unity.SDKVector3 calibrationcameraposition
// Size: 0xC
// Offset: 0x1C
::LIV::SDK::Unity::SDKVector3 calibrationcameraposition;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC);
// public LIV.SDK.Unity.SDKQuaternion calibrationcamerarotation
// Size: 0x10
// Offset: 0x28
::LIV::SDK::Unity::SDKQuaternion calibrationcamerarotation;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10);
// public LIV.SDK.Unity.SDKVector3 cameraposition
// Size: 0xC
// Offset: 0x38
::LIV::SDK::Unity::SDKVector3 cameraposition;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC);
// public LIV.SDK.Unity.SDKQuaternion camerarotation
// Size: 0x10
// Offset: 0x44
::LIV::SDK::Unity::SDKQuaternion camerarotation;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10);
// public LIV.SDK.Unity.SDKVector3 leftposition
// Size: 0xC
// Offset: 0x54
::LIV::SDK::Unity::SDKVector3 leftposition;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC);
// public LIV.SDK.Unity.SDKQuaternion leftrotation
// Size: 0x10
// Offset: 0x60
::LIV::SDK::Unity::SDKQuaternion leftrotation;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10);
// public LIV.SDK.Unity.SDKVector3 rightposition
// Size: 0xC
// Offset: 0x70
::LIV::SDK::Unity::SDKVector3 rightposition;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC);
// public LIV.SDK.Unity.SDKQuaternion rightrotation
// Size: 0x10
// Offset: 0x7C
::LIV::SDK::Unity::SDKQuaternion rightrotation;
// Field size check
static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10);
public:
// Creating value type constructor for type: SDKControllerState
constexpr SDKControllerState(::LIV::SDK::Unity::SDKVector3 hmdposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion hmdrotation_ = {}, ::LIV::SDK::Unity::SDKVector3 calibrationcameraposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion calibrationcamerarotation_ = {}, ::LIV::SDK::Unity::SDKVector3 cameraposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion camerarotation_ = {}, ::LIV::SDK::Unity::SDKVector3 leftposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion leftrotation_ = {}, ::LIV::SDK::Unity::SDKVector3 rightposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion rightrotation_ = {}) noexcept : hmdposition{hmdposition_}, hmdrotation{hmdrotation_}, calibrationcameraposition{calibrationcameraposition_}, calibrationcamerarotation{calibrationcamerarotation_}, cameraposition{cameraposition_}, camerarotation{camerarotation_}, leftposition{leftposition_}, leftrotation{leftrotation_}, rightposition{rightposition_}, rightrotation{rightrotation_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Get instance field reference: public LIV.SDK.Unity.SDKVector3 hmdposition
::LIV::SDK::Unity::SDKVector3& dyn_hmdposition();
// Get instance field reference: public LIV.SDK.Unity.SDKQuaternion hmdrotation
::LIV::SDK::Unity::SDKQuaternion& dyn_hmdrotation();
// Get instance field reference: public LIV.SDK.Unity.SDKVector3 calibrationcameraposition
::LIV::SDK::Unity::SDKVector3& dyn_calibrationcameraposition();
// Get instance field reference: public LIV.SDK.Unity.SDKQuaternion calibrationcamerarotation
::LIV::SDK::Unity::SDKQuaternion& dyn_calibrationcamerarotation();
// Get instance field reference: public LIV.SDK.Unity.SDKVector3 cameraposition
::LIV::SDK::Unity::SDKVector3& dyn_cameraposition();
// Get instance field reference: public LIV.SDK.Unity.SDKQuaternion camerarotation
::LIV::SDK::Unity::SDKQuaternion& dyn_camerarotation();
// Get instance field reference: public LIV.SDK.Unity.SDKVector3 leftposition
::LIV::SDK::Unity::SDKVector3& dyn_leftposition();
// Get instance field reference: public LIV.SDK.Unity.SDKQuaternion leftrotation
::LIV::SDK::Unity::SDKQuaternion& dyn_leftrotation();
// Get instance field reference: public LIV.SDK.Unity.SDKVector3 rightposition
::LIV::SDK::Unity::SDKVector3& dyn_rightposition();
// Get instance field reference: public LIV.SDK.Unity.SDKQuaternion rightrotation
::LIV::SDK::Unity::SDKQuaternion& dyn_rightrotation();
// static public LIV.SDK.Unity.SDKControllerState get_empty()
// Offset: 0x29FBB10
static ::LIV::SDK::Unity::SDKControllerState get_empty();
// public override System.String ToString()
// Offset: 0x29FBB80
// Implemented from: System.ValueType
// Base method: System.String ValueType::ToString()
::StringW ToString();
}; // LIV.SDK.Unity.SDKControllerState
#pragma pack(pop)
static check_size<sizeof(SDKControllerState), 124 + sizeof(::LIV::SDK::Unity::SDKQuaternion)> __LIV_SDK_Unity_SDKControllerStateSizeCheck;
static_assert(sizeof(SDKControllerState) == 0x8C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: LIV::SDK::Unity::SDKControllerState::get_empty
// Il2CppName: get_empty
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::LIV::SDK::Unity::SDKControllerState (*)()>(&LIV::SDK::Unity::SDKControllerState::get_empty)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(LIV::SDK::Unity::SDKControllerState), "get_empty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: LIV::SDK::Unity::SDKControllerState::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (LIV::SDK::Unity::SDKControllerState::*)()>(&LIV::SDK::Unity::SDKControllerState::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(LIV::SDK::Unity::SDKControllerState), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 53.026846 | 940 | 0.717124 | RedBrumbler |
98bd94332c950a4fd85be76b84addd3b2b18e6f3 | 4,935 | cpp | C++ | hooks/hooks/hooked_overrideview.cpp | PhoenixAceVFX/Illenium | 61408a9d26c7f2ee8f852a73e037d8bb4761575d | [
"Unlicense"
] | 3 | 2021-04-27T18:45:45.000Z | 2022-01-04T07:44:28.000Z | hooks/hooks/hooked_overrideview.cpp | PhoenixAceVFX/Illenium | 61408a9d26c7f2ee8f852a73e037d8bb4761575d | [
"Unlicense"
] | 1 | 2021-05-03T20:39:28.000Z | 2021-05-03T20:39:28.000Z | hooks/hooks/hooked_overrideview.cpp | PhoenixAceVFX/Illenium | 61408a9d26c7f2ee8f852a73e037d8bb4761575d | [
"Unlicense"
] | 4 | 2021-03-25T21:32:51.000Z | 2021-12-14T04:30:05.000Z | // This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include "..\hooks.hpp"
#include "..\..\cheats\visuals\GrenadePrediction.h"
#include "..\..\cheats\misc\fakelag.h"
#include "..\..\cheats\lagcompensation\local_animations.h"
using OverrideView_t = void(__stdcall*)(CViewSetup*);
void thirdperson(bool fakeducking);
void __stdcall hooks::hooked_overrideview(CViewSetup* viewsetup)
{
static auto original_fn = clientmode_hook->get_func_address <OverrideView_t> (18);
g_ctx.local((player_t*)m_entitylist()->GetClientEntity(m_engine()->GetLocalPlayer()), true);
if (!viewsetup)
return original_fn(viewsetup);
if (g_ctx.local())
{
static auto fakeducking = false;
if (!fakeducking && g_ctx.globals.fakeducking)
fakeducking = true;
else if (fakeducking && !g_ctx.globals.fakeducking && (!g_ctx.local()->get_animation_state()->m_fDuckAmount || g_ctx.local()->get_animation_state()->m_fDuckAmount == 1.0f)) //-V550
fakeducking = false;
if (!g_ctx.local()->is_alive()) //-V807
fakeducking = false;
auto weapon = g_ctx.local()->m_hActiveWeapon().Get();
if (weapon)
{
if (!g_ctx.local()->m_bIsScoped() && g_cfg.player.enable)
viewsetup->fov += g_cfg.esp.fov;
else if (g_cfg.esp.removals[REMOVALS_ZOOM] && g_cfg.player.enable)
{
if (weapon->m_zoomLevel() == 1)
viewsetup->fov = 90.0f + (float)g_cfg.esp.fov;
else
viewsetup->fov += (float)g_cfg.esp.fov;
}
}
else if (g_cfg.player.enable)
viewsetup->fov += g_cfg.esp.fov;
if (weapon)
{
auto viewmodel = (entity_t*)m_entitylist()->GetClientEntityFromHandle(g_ctx.local()->m_hViewModel());
if (viewmodel)
{
auto eyeAng = viewsetup->angles;
eyeAng.z -= (float)g_cfg.esp.viewmodel_roll;
viewmodel->set_abs_angles(eyeAng);
}
if (weapon->is_grenade() && g_cfg.esp.grenade_prediction && g_cfg.player.enable)
GrenadePrediction::get().View(viewsetup, weapon);
}
if (g_cfg.player.enable && (g_cfg.misc.thirdperson_toggle.key > KEY_NONE && g_cfg.misc.thirdperson_toggle.key < KEY_MAX || g_cfg.misc.thirdperson_when_spectating))
thirdperson(fakeducking);
else
{
g_ctx.globals.in_thirdperson = false;
m_input()->m_fCameraInThirdPerson = false;
}
original_fn(viewsetup);
if (fakeducking)
{
viewsetup->origin = g_ctx.local()->GetAbsOrigin() + Vector(0.0f, 0.0f, m_gamemovement()->GetPlayerViewOffset(false).z + 0.064f);
if (m_input()->m_fCameraInThirdPerson)
{
auto camera_angles = Vector(m_input()->m_vecCameraOffset.x, m_input()->m_vecCameraOffset.y, 0.0f); //-V807
auto camera_forward = ZERO;
math::angle_vectors(camera_angles, camera_forward);
math::VectorMA(viewsetup->origin, -m_input()->m_vecCameraOffset.z, camera_forward, viewsetup->origin);
}
}
}
else
return original_fn(viewsetup);
}
void thirdperson(bool fakeducking)
{
static auto current_fraction = 0.0f;
static auto in_thirdperson = false;
if (!in_thirdperson && g_ctx.globals.in_thirdperson)
{
current_fraction = 0.0f;
in_thirdperson = true;
}
else if (in_thirdperson && !g_ctx.globals.in_thirdperson)
in_thirdperson = false;
if (g_ctx.local()->is_alive() && in_thirdperson) //-V807
{
auto distance = (float)g_cfg.misc.thirdperson_distance;
Vector angles;
m_engine()->GetViewAngles(angles);
Vector inverse_angles;
m_engine()->GetViewAngles(inverse_angles);
inverse_angles.z = distance;
Vector forward, right, up;
math::angle_vectors(inverse_angles, &forward, &right, &up);
Ray_t ray;
CTraceFilterWorldAndPropsOnly filter;
trace_t trace;
auto eye_pos = fakeducking ? g_ctx.local()->GetAbsOrigin() + m_gamemovement()->GetPlayerViewOffset(false) : g_ctx.local()->GetAbsOrigin() + g_ctx.local()->m_vecViewOffset();
auto offset = eye_pos + forward * -distance + right + up;
ray.Init(eye_pos, offset, Vector(-16.0f, -16.0f, -16.0f), Vector(16.0f, 16.0f, 16.0f));
m_trace()->TraceRay(ray, MASK_SHOT_HULL, &filter, &trace);
if (current_fraction > trace.fraction)
current_fraction = trace.fraction;
else if (current_fraction > 0.9999f)
current_fraction = 1.0f;
current_fraction = math::interpolate(current_fraction, trace.fraction, m_globals()->m_frametime * 10.0f);
angles.z = distance * current_fraction;
m_input()->m_fCameraInThirdPerson = current_fraction > 0.1f;
m_input()->m_vecCameraOffset = angles;
}
else if (m_input()->m_fCameraInThirdPerson)
{
g_ctx.globals.in_thirdperson = false;
m_input()->m_fCameraInThirdPerson = false;
}
static auto require_reset = false;
if (g_ctx.local()->is_alive())
{
require_reset = false;
return;
}
if (g_cfg.misc.thirdperson_when_spectating)
{
if (require_reset)
g_ctx.local()->m_iObserverMode() = OBS_MODE_CHASE;
if (g_ctx.local()->m_iObserverMode() == OBS_MODE_IN_EYE)
require_reset = true;
}
} | 29.909091 | 182 | 0.707194 | PhoenixAceVFX |
98c77cd91f764222e7ebbdca46cc3b8a3daf2741 | 3,225 | cpp | C++ | Plugins/org.commontk.eventbus/Testing/Cpp/ctkNetworkConnectorZeroMQTest.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 515 | 2015-01-13T05:42:10.000Z | 2022-03-29T03:10:01.000Z | Plugins/org.commontk.eventbus/Testing/Cpp/ctkNetworkConnectorZeroMQTest.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 425 | 2015-01-06T05:28:38.000Z | 2022-03-08T19:42:18.000Z | Plugins/org.commontk.eventbus/Testing/Cpp/ctkNetworkConnectorZeroMQTest.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 341 | 2015-01-08T06:18:17.000Z | 2022-03-29T21:47:49.000Z | /*
* ctkNetworkConnectorZeroMQTest.cpp
* ctkNetworkConnectorZeroMQTest
*
* Created by Daniele Giunchi on 27/03/09.
* Copyright 2009 B3C. All rights reserved.
*
* See Licence at: http://tiny.cc/QXJ4D
*
*/
#include "ctkTestSuite.h"
#include <ctkNetworkConnectorZeroMQ.h>
#include <ctkEventBusManager.h>
#include <QApplication>
using namespace ctkEventBus;
//-------------------------------------------------------------------------
/**
Class name: ctkObjectCustom
Custom object needed for testing.
*/
class testObjectCustomForNetworkConnectorZeroMQ : public QObject {
Q_OBJECT
public:
/// constructor.
testObjectCustomForNetworkConnectorZeroMQ();
/// Return tha var's value.
int var() {return m_Var;}
public Q_SLOTS:
/// Test slot that will increment the value of m_Var when an UPDATE_OBJECT event is raised.
void updateObject();
void setObjectValue(int v);
Q_SIGNALS:
void valueModified(int v);
void objectModified();
private:
int m_Var; ///< Test var.
};
testObjectCustomForNetworkConnectorZeroMQ::testObjectCustomForNetworkConnectorZeroMQ() : m_Var(0) {
}
void testObjectCustomForNetworkConnectorZeroMQ::updateObject() {
m_Var++;
}
void testObjectCustomForNetworkConnectorZeroMQ::setObjectValue(int v) {
m_Var = v;
}
/**
Class name: ctkNetworkConnectorZeroMQTest
This class implements the test suite for ctkNetworkConnectorZeroMQ.
*/
//! <title>
//ctkNetworkConnectorZeroMQ
//! </title>
//! <description>
//ctkNetworkConnectorZeroMQ provides the connection with 0MQ library.
//It has been used qxmlrpc library.
//! </description>
class ctkNetworkConnectorZeroMQTest : public QObject {
Q_OBJECT
private Q_SLOTS:
/// Initialize test variables
void initTestCase() {
m_EventBus = ctkEventBusManager::instance();
m_NetWorkConnectorZeroMQ = new ctkEventBus::ctkNetworkConnectorZeroMQ();
m_ObjectTest = new testObjectCustomForNetworkConnectorZeroMQ();
}
/// Cleanup tes variables memory allocation.
void cleanupTestCase() {
if(m_ObjectTest) {
delete m_ObjectTest;
m_ObjectTest = NULL;
}
delete m_NetWorkConnectorZeroMQ;
m_EventBus->shutdown();
}
/// Check the existence of the ctkNetworkConnectorZeroMQe singletone creation.
void ctkNetworkConnectorZeroMQConstructorTest();
/// Check the existence of the ctkNetworkConnectorZeroMQe singletone creation.
void ctkNetworkConnectorZeroMQCommunictionTest();
private:
ctkEventBusManager *m_EventBus; ///< event bus instance
ctkNetworkConnectorZeroMQ *m_NetWorkConnectorZeroMQ; ///< EventBus test variable instance.
testObjectCustomForNetworkConnectorZeroMQ *m_ObjectTest;
};
void ctkNetworkConnectorZeroMQTest::ctkNetworkConnectorZeroMQConstructorTest() {
QVERIFY(m_NetWorkConnectorZeroMQ != NULL);
}
void ctkNetworkConnectorZeroMQTest::ctkNetworkConnectorZeroMQCommunictionTest() {
QTime dieTime = QTime::currentTime().addSecs(3);
while(QTime::currentTime() < dieTime) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 3);
}
}
CTK_REGISTER_TEST(ctkNetworkConnectorZeroMQTest);
#include "ctkNetworkConnectorZeroMQTest.moc"
| 26.652893 | 99 | 0.724031 | kraehlit |
98c8fb9b3509b30fa60bbda6d5a094502ce89d79 | 2,814 | cpp | C++ | src/models/bookquotesmodel.cpp | Maledictus/harbour-sailreads | 2c58aa266ef2dacb790b857c3b6aced937da5c0e | [
"MIT"
] | 3 | 2019-01-05T09:54:19.000Z | 2019-02-26T09:20:23.000Z | src/models/bookquotesmodel.cpp | Maledictus/harbour-sailreads | 2c58aa266ef2dacb790b857c3b6aced937da5c0e | [
"MIT"
] | 1 | 2019-01-03T10:02:01.000Z | 2019-01-03T14:08:16.000Z | src/models/bookquotesmodel.cpp | Maledictus/harbour-sailreads | 2c58aa266ef2dacb790b857c3b6aced937da5c0e | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018-2019 Oleg Linkin <[email protected]>
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 "bookquotesmodel.h"
#include "../sailreadsmanager.h"
namespace Sailreads
{
BookQuotesModel::BookQuotesModel(QObject *parent)
: QuotesBaseModel(parent)
, m_WorkId(0)
{
}
void BookQuotesModel::classBegin()
{
auto sm = SailreadsManager::Instance();
connect(sm, &SailreadsManager::gotBookQuotes,
this, &BookQuotesModel::handleGotBookQuotes);
}
void BookQuotesModel::componentComplete()
{
}
quint64 BookQuotesModel::GetWorkId() const
{
return m_WorkId;
}
void BookQuotesModel::SetWorkId(quint64 workId)
{
if (m_WorkId != workId) {
m_WorkId = workId;
m_CurrentPage = 1;
SetHasMore(true);
emit workIdChanged();
}
}
void BookQuotesModel::fetchMoreContent()
{
if (!m_WorkId) {
return;
}
SailreadsManager::Instance()->loadBookQuotes(this, m_WorkId, m_CurrentPage);
SetFetching(true);
}
void BookQuotesModel::loadBookQuotes()
{
if (!m_WorkId) {
return;
}
Clear();
m_HasMore = true;
m_CurrentPage = 1;
SailreadsManager::Instance()->loadBookQuotes(this, m_WorkId, m_CurrentPage, false);
SetFetching(true);
}
void BookQuotesModel::handleGotBookQuotes(quint64 workId, const PageCountedItems<Quote>& quotes)
{
if (m_WorkId != workId || !quotes.m_Items.count()) {
return;
}
if (!quotes.m_Page && !quotes.m_PagesCount)
{
Clear();
}
else if (quotes.m_Page == 1) {
m_CurrentPage = quotes.m_Page;
SetItems(quotes.m_Items);
}
else {
AddItems(quotes.m_Items);
}
SetHasMore(quotes.m_Page != quotes.m_PagesCount);
if (m_HasMore) {
++m_CurrentPage;
}
SetFetching(false);
}
} // namespace Sailreads
| 26.055556 | 96 | 0.708955 | Maledictus |
98c90718ad31be5421555a16fedface158e6d1dd | 1,616 | cpp | C++ | test/chapter_08_design_patterns/problem_071_observable_vector_container.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | test/chapter_08_design_patterns/problem_071_observable_vector_container.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | test/chapter_08_design_patterns/problem_071_observable_vector_container.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "chapter_08_design_patterns/problem_071_observable_vector_container.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sstream> // ostringstream
TEST(problem_71_main, DISABLED_output) {
std::ostringstream oss{};
problem_71_main(oss);
EXPECT_THAT(oss.str(), ::testing::HasSubstr(
"Creating the observable vectors:\n"
"\tov_0: []\n"
"\tov_1: [0, 3.14, 6.28, 9.42, 12.56]\n"
"\tov_2: [1.5, 1.5, 1.5]\n"
"\tov_3: ['o', ',', ' ', 'u']\n"
"\tov_4: []\n"
"\n"
"Pushing back to ov_0:\n"
"\t[observer 0] received notification: <id : 0, type : push_back(0)>\n"
"\t[observer 0] observable vector 0: [\"Tush! Never tell me;\"]\n"
"\t[observer 0] received notification: <id : 1, type : push_back(1)>\n"
"\t[observer 0] observable vector 0: [\"Tush! Never tell me;\", \"I take it much unkindly.\"]\n"
"\n"
"Copy assigning from ov_3:\n"
"Popping back from the copied-to vector:\n"
"\n"
"Move assigning from ov_1:\n"
"Pushing back to the moved-to vector:\n"
"\n"
"Copy assigning to ov_3:\n"
"\t[observer 3] received notification: <id : 2, type : copy_assignment()>\n"
"\t[observer 3] observable vector 3: ['o', ',', ' ']\n"
"\n"
"Move assigning to ov_4:\n"
"\t[observer 4] received notification: <id : 3, type : move_assignment()>\n"
"\t[observer 4] sum of elements of observable vector 4: 12\n"
"\n"
"Detaching from ov_0:\n"
"Pushing back to ov_0:\n"
));
}
| 36.727273 | 104 | 0.5625 | rturrado |
98caafef16943f7eaff318b0253bdb2f739eac59 | 11,357 | cpp | C++ | tagwire/thailand_client.cpp | pshoben/devutils | c655d0f88a359c8e3db7f5dd3a69ff2fc9bd7db2 | [
"MIT"
] | null | null | null | tagwire/thailand_client.cpp | pshoben/devutils | c655d0f88a359c8e3db7f5dd3a69ff2fc9bd7db2 | [
"MIT"
] | null | null | null | tagwire/thailand_client.cpp | pshoben/devutils | c655d0f88a359c8e3db7f5dd3a69ff2fc9bd7db2 | [
"MIT"
] | null | null | null | /*
* ref: https://github.com/onestraw/epoll-example
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
//#include <sys/epoll.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
#include <time.h>
#include <fcntl.h>
#include "emapi.h"
#include <sstream>
#include <cstring>
#include "EmapiTagwireWrapper.h"
using namespace emapi;
using std::string;
using std::stringstream;
using std::cout;
EmapiTagwireWrapper tpl_req;
#define DEFAULT_PORT 6565 // 8080
#define DEFAULT_HOST "127.0.0.1"
//#define MAX_CONN 16
//#define MAX_EVENTS 32
//#define BUF_SIZE 16
#define MAX_LINE 512
bool g_interactive = true;
unsigned short g_port= DEFAULT_PORT;
char g_host[HOST_NAME_MAX]=DEFAULT_HOST;
char g_send_string[MAX_LINE-1]="test send";
int g_send_repeats = 1 ; // default -1 = send once
struct timespec g_send_wait;
void print_twstring(char * s)
{
if( !s ) {
printf("null string\n");
return;
}
char * copy = strdup(s);
string tpl_str{copy};
try {
cout << "got tagwire string before: \"" << tpl_str << "\"\n";
TagwireDecoder decoder{ (const unsigned char *)tpl_str.c_str(),
0,(unsigned int) tpl_str.size()};
//cout << "got tagwire string : \"" << tpl_str << "\"\n";
tpl_req.unpack(decoder);
cout << "unpacked:\n" << tpl_req.to_string("");
} catch ( std::exception e )
{
printf("Tagwire Decode failed\n");
}
free(copy);
}
void test_tpl()
{
stringstream ss;
ss << EmapiMessageType_EmapiTaxPreLogonReq << "=["
<< "1=T"
<< "|2=member"
<< "|3=user"
<< "|4=1"
<< "|5=2"
<< "|6=3"
<< "]";
string tpl_str{ss.str()};
TagwireDecoder decoder{ (const unsigned char *)tpl_str.c_str(),
0,(unsigned int) tpl_str.size()};
cout << "test string : \"" << tpl_str << "\"\n";
tpl_req.unpack(decoder);
cout << "wrapper\n" << tpl_req.to_string("");
TagwireEncoder encoder(tpl_req.getMessageType());
tpl_req.pack(encoder);
cout << "packed: " << encoder.getBuffer() << "\n";
}
/** Returns true on success, or false if there was an error */
bool set_socket_blocking(int fd, bool blocking)
{
if (fd < 0) return false;
#ifdef _WIN32
unsigned long mode = blocking ? 0 : 1;
return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return false;
flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}
static void set_sockaddr(struct sockaddr_in *addr)
{
bzero((char *)addr, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = INADDR_ANY;
addr->sin_port = htons(g_port);
}
void print_menu_options()
{
printf("options:\n*1 send taxprelogonreq\n");
printf("options:\n*2 send taxconnnectorentry\n");
printf("options:\n*3 send taxprelogonrsp\n");
printf("options:\n*4 send abstractmeevent\n");
printf("options:\n*5 send proteusrefdatamessage\n");
printf("options:\n*6 send requestmessage\n");
printf("options:\n*7 send simpleresponse\n");
printf("options:\n*8 send responsemessage\n");
printf("options:\n*9 send msg_publicmulticastaddress\n");
printf("options:\n*a send msg_publicmulticastpartition\n");
printf("options:\n*b send msg_publicmulticastcontent\n");
printf("options:\n*c send msg_taxlogonreq\n");
printf("options:\n*d send msg_taxlogonrsp\n");
}
void client_run()
{
int n;
int c;
int sockfd;
char buf[MAX_LINE];
struct sockaddr_in srv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
set_sockaddr(&srv_addr);
bool success = set_socket_blocking( sockfd, false );
printf("set socket non-blocking returned %d\n",success );
success = connect(sockfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
//while( errno == EINPROGRESS ){
printf("waiting to connect...\n");
usleep(1000000);
//}
// perror("connect()");
// exit(1);
//}
printf("connected\n");
char msg_abstractmeevent[]="238=[1=1|2=2|3=timeofevent|4=T]";
char msg_proteusrefdatamessage[]="236=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=F]";
char msg_taxprelogonreq[]="66=[1=T|2=member|3=user|4=1|5=2|6=3]";
string msg_taxconnectorentry= "68=[1=1|2=ipaddress|3=3|4=[4|4]|5=[5|5]]";
string tce = msg_taxconnectorentry;
string msg_taxprelogonrsp="64=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=address|7=7|8=8|"
"9=[" + tce + "|" + tce + "]|10=messagref]";
char msg_requestmessage[]="237=[1=T]";
char msg_simpleresp[]="231=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=messagereference]";
char msg_responsemessage[]="230=[1=1|2=message|3=[3|3]|4=requestid|5=messagereference]";
string msg_publicmulticastaddress = "110=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmcaddress|8=8|9=pmcsourceaddress|10=pmcpartitionid|11=F]";
string pma = msg_publicmulticastaddress;
string msg_publicmulticastpartition =
"109=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmcpartitionid|8=payloadcontenttype|10=10|11=11|12=12|13=pmccontentid|14=[" + pma + "|" + pma + "]|15=F]";
string pmp = msg_publicmulticastpartition;
string msg_publicmulticastcontent = "108=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmccontentid|8=flowidlist"
"|9=subscriptiongrouplist|10=[" + pmp + "|" + pmp + "]|11=F]";
string pmc = msg_publicmulticastcontent;
string msg_taxlogonreq="63=[1=T|2=member|3=user|4=password|5=5|6=6|7=7|8=8|9=9]";
string msg_taxlogonrsp="64=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=T|7=7|8=T|"
"9=systemname|10=10|11=11|12=12|13=[" + pmc + "|" + pmc + "]|14=messagref]";
if( g_interactive ) {
printf("Interactive mode.\n"
"Enter q[+newline] to quit\n");
char copy_recv_buffer[MAX_LINE+1];
char send_buffer[MAX_LINE+1];
for (;;) {
memset( send_buffer, 0 , MAX_LINE+1 );
memset( copy_recv_buffer, 0 , MAX_LINE+1 );
char * p = copy_recv_buffer;
printf("> ");
fgets(buf, sizeof(buf), stdin);
if( buf[0]=='q') {
break;
} else if (buf[0]=='*') {
if( buf[1]=='?' ) {
print_menu_options();
continue;
} else if ( buf[1]=='1' ) {
strcpy( send_buffer, msg_taxprelogonreq );
//c = strlen( send_buffer );
} else if ( buf[1]=='2' ) {
strcpy( send_buffer, msg_taxconnectorentry.c_str());
//c = strlen( send_buffer );
} else if ( buf[1]=='3' ) {
strcpy( send_buffer, msg_taxprelogonrsp.c_str());
} else if ( buf[1]=='4' ) {
strcpy( send_buffer,msg_abstractmeevent );
} else if ( buf[1]=='5' ) {
strcpy( send_buffer, msg_proteusrefdatamessage );
} else if ( buf[1]=='6' ) {
strcpy( send_buffer, msg_requestmessage );
} else if ( buf[1]=='7' ) {
strcpy( send_buffer, msg_simpleresp );
} else if ( buf[1]=='8' ) {
strcpy( send_buffer, msg_responsemessage );
} else if ( buf[1]=='9' ) {
strcpy( send_buffer, msg_publicmulticastaddress.c_str());
} else if ( buf[1]=='a' ) {
strcpy( send_buffer, msg_publicmulticastpartition.c_str());
} else if ( buf[1]=='b' ) {
strcpy( send_buffer, msg_publicmulticastcontent.c_str());
} else if ( buf[1]=='c' ) {
strcpy( send_buffer, msg_taxlogonreq.c_str());
} else if ( buf[1]=='d' ) {
strcpy( send_buffer, msg_taxlogonrsp.c_str());
} else {
printf("unrecognised option\n");
print_menu_options();
continue;
}
} else {
strcpy( send_buffer, buf ) ;
c = strlen( send_buffer ) - 1;
send_buffer[c] = '\0';
}
printf("sending message: \"%s\"\n", send_buffer );
print_twstring( send_buffer );
write(sockfd, send_buffer, strlen(send_buffer) + 1);
int countdown = 1000;
bzero(buf, sizeof(buf));
do {
n = read(sockfd, buf, sizeof(buf));
if(n>1) {
printf("recv %d bytes: %s\n", n, buf);
memcpy( p, buf, n);
p+= n;
bzero(buf, sizeof(buf));
}
usleep(1000);
//c -= n;
//if (c <= 0) {
// break;
//}
} while( errno == EWOULDBLOCK && ( n<1 ) && countdown-->0 );
*p=0; // add null terminator
printf("recv message:\"%s\"\n",copy_recv_buffer);
print_twstring( copy_recv_buffer );
}
} else {
const char * send_array[17];
int i=0;
send_array[i++]=msg_abstractmeevent;
send_array[i++]=msg_proteusrefdatamessage;
send_array[i++]=msg_taxprelogonreq;
send_array[i++]= msg_requestmessage;
send_array[i++]= msg_simpleresp;
send_array[i++]= msg_responsemessage;
send_array[i++]= msg_taxconnectorentry.c_str();
//send_array[i++]= msg_taxconnectorentry.c_str();
send_array[i++]= msg_publicmulticastaddress.c_str();
//send_array[i++]= msg_publicmulticastaddress.c_str();
//send_array[i++]= msg_publicmulticastpartition.c_str();
//send_array[i++]= msg_publicmulticastpartition.c_str();
//send_array[i++]= msg_publicmulticastcontent.c_str();
//send_array[i++]= msg_publicmulticastcontent.c_str();
send_array[i++]= msg_taxlogonreq.c_str();
//send_array[i++]= msg_taxlogonrsp.c_str();
send_array[i++]= msg_taxprelogonrsp.c_str();
int last_index = i;
char copy_recv_buffer[MAX_LINE+1];
for( i = 0 ; i <= last_index ; i++ ) {
strcpy( g_send_string, send_array[i]);
int sent_count = 0 ;
while( g_send_repeats == -1 || sent_count < g_send_repeats ) {
printf("\n============================================================\n");
//print_twstring( g_send_string );
printf("sending message: \"%s\"\n", g_send_string );
strncpy(buf, g_send_string, sizeof(buf)-1);
c = strlen(buf) - 1;
write(sockfd, buf, c + 1);
memset( copy_recv_buffer, 0 , MAX_LINE+1 );
char * p = copy_recv_buffer;
int countdown = 1000;
bzero(buf, sizeof(buf));
do {
n = read(sockfd, buf, sizeof(buf));
if(n>1) {
printf("recv %d bytes: %s\n", n, buf);
memcpy( p, buf, n);
p+= n;
bzero(buf, sizeof(buf));
}
usleep(1000);
//c -= n;
//if (c <= 0) {
// break;
//}
} while( errno == EWOULDBLOCK && ( n<1 ) && countdown-->0 );
*p=0; // add null terminator
printf("recv message:\"%s\"\n",copy_recv_buffer);
//print_twstring( copy_recv_buffer );
nanosleep( &g_send_wait, 0 );
sent_count++;
}
}
printf("exiting batch mode ... ok\n");
}
close(sockfd);
}
int main(int argc, char *argv[])
{
test_tpl();
g_send_wait.tv_sec=0;
g_send_wait.tv_nsec=999999999;
int opt;
while ((opt = getopt(argc, argv, "bih:p:s:r:w:")) != -1) {
switch (opt) {
case 'b':
g_interactive = false;
break;
case 'i':
g_interactive = true;
break;
case 'h':
strcpy(g_host,optarg);
break;
case 'p':
g_port = atoi(optarg);
break;
case 's':
memset(g_send_string, 0, sizeof(g_send_string));
strncpy(g_send_string,optarg,sizeof(g_send_string)-1);
break;
case 'r':
g_send_repeats = atoi(optarg);
break;
case 'w':
g_send_wait.tv_nsec = atol(optarg);
if( g_send_wait.tv_nsec > 999999999 )
g_send_wait.tv_nsec = 999999999;
break;
default:
printf("usage: %s [-s send-string] [-w wait time (nanos)]\n"
"[-r repeats (number of repeats)] [-i (interactive)]\n"
"[h HOST] -p PORT\n", argv[0]);
exit(1);
}
}
printf("client using host %s port %hu %s\n",g_host,g_port, g_interactive?"(interactive mode)":"(batch mode)");
client_run();
return 0;
}
| 28.679293 | 168 | 0.633442 | pshoben |
98ccb274c19c2cf7090cbb07aad453c94b549b7c | 2,417 | cpp | C++ | src/sqlite/savepoint.cpp | cornerstone-solutions/vsqlite-- | 29abd3b221e0f09a3115079d91fca230ec85523c | [
"BSD-3-Clause"
] | 21 | 2015-02-28T08:42:03.000Z | 2021-12-29T02:04:37.000Z | src/sqlite/savepoint.cpp | cornerstone-solutions/vsqlite-- | 29abd3b221e0f09a3115079d91fca230ec85523c | [
"BSD-3-Clause"
] | 14 | 2015-02-07T10:41:13.000Z | 2022-02-04T12:56:12.000Z | src/sqlite/savepoint.cpp | cornerstone-solutions/vsqlite-- | 29abd3b221e0f09a3115079d91fca230ec85523c | [
"BSD-3-Clause"
] | 18 | 2015-02-09T11:15:50.000Z | 2020-11-11T10:08:21.000Z | /*##############################################################################
VSQLite++ - virtuosic bytes SQLite3 C++ wrapper
Copyright (c) 2014 mickey [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of virtuosic bytes nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
##############################################################################*/
#include <sqlite/connection.hpp>
#include <sqlite/savepoint.hpp>
#include <sqlite/execute.hpp>
namespace sqlite{
savepoint::savepoint(connection & con, std::string const & name)
: m_con(con)
, m_name(name){
exec("SAVEPOINT " + m_name);
m_isActive = true;
}
savepoint::~savepoint(){
if (m_isActive) release();
}
void savepoint::release(){
exec("RELEASE SAVEPOINT " + m_name);
m_isActive = false;
}
void savepoint::rollback() {
exec("ROLLBACK TRANSACTION TO SAVEPOINT " + m_name);
}
void savepoint::exec(std::string const & cmd){
execute(m_con,cmd,true);
}
}
| 39.622951 | 81 | 0.686388 | cornerstone-solutions |
98cf2e0b13eee452176baff98a53eed0272cd6cb | 22,148 | cpp | C++ | src/cpp/src/batch.cpp | AnzeXie/marius | db2cf14fdfcae469889fb3c8b2e92c4289463ea3 | [
"Apache-2.0"
] | 81 | 2021-03-25T08:34:54.000Z | 2022-03-04T15:56:05.000Z | src/cpp/src/batch.cpp | AnzeXie/marius | db2cf14fdfcae469889fb3c8b2e92c4289463ea3 | [
"Apache-2.0"
] | 45 | 2021-03-25T18:04:43.000Z | 2021-12-14T18:41:47.000Z | src/cpp/src/batch.cpp | rachit173/marius | c981482af29e6038e2477e634d46fd7cc4de4961 | [
"Apache-2.0"
] | 20 | 2021-03-31T04:37:31.000Z | 2022-02-25T21:36:05.000Z | //
// Created by Jason Mohoney on 7/9/20.
//
#include "batch.h"
#include "config.h"
using std::get;
Batch::Batch(bool train) : device_transfer_(0), host_transfer_(0), timer_(false) {
status_ = BatchStatus::Waiting;
train_ = train;
device_id_ = -1;
}
void Batch::localSample() {
int num_deg;
if (train_) {
num_deg = (int) (marius_options.training.negatives * marius_options.training.degree_fraction);
} else {
num_deg = (int) (marius_options.evaluation.negatives * marius_options.evaluation.degree_fraction);
if (marius_options.evaluation.negative_sampling_access == NegativeSamplingAccess::All) {
// no need to sample by degree when using all nodes for sampling negatives
src_all_neg_embeddings_ = src_global_neg_embeddings_;
dst_all_neg_embeddings_ = dst_global_neg_embeddings_;
return;
}
}
if (num_deg == 0) {
src_all_neg_embeddings_ = src_global_neg_embeddings_;
dst_all_neg_embeddings_ = dst_global_neg_embeddings_;
return;
}
int num_chunks = src_global_neg_embeddings_.size(0);
int num_per_chunk = (int) ceil((float) batch_size_ / num_chunks);
// Sample for src and update filter
int src_neg_size = src_global_neg_embeddings_.size(1);
Indices src_sample = torch::randint(0, batch_size_, {num_chunks, num_deg}, src_global_neg_embeddings_.device()).to(torch::kInt64);
auto chunk_ids = (src_sample.floor_divide(num_per_chunk)).view({num_chunks, -1});
auto inv_mask = chunk_ids - torch::arange(0, num_chunks, src_global_neg_embeddings_.device()).view({num_chunks, -1});
auto mask = (inv_mask == 0);
auto temp_idx = torch::nonzero(mask);
auto id_offset = src_sample.flatten(0, 1).index_select(0, (temp_idx.select(1, 0) * num_deg + temp_idx.select(1, 1)));
auto sample_offset = temp_idx.select(1, 1);
src_all_neg_embeddings_ = torch::cat({src_global_neg_embeddings_, src_pos_embeddings_.index_select(0, src_sample.flatten(0, 1)).view({num_chunks, num_deg, -1})}, 1);
src_neg_filter_ = id_offset * src_all_neg_embeddings_.size(1) + (src_neg_size + sample_offset);
// Sample for dst and update filter
int dst_neg_size = dst_global_neg_embeddings_.size(1);
Indices dst_sample = torch::randint(0, batch_size_, {num_chunks, num_deg}, dst_global_neg_embeddings_.device()).to(torch::kInt64);
chunk_ids = (dst_sample.floor_divide(num_per_chunk)).view({num_chunks, -1});
inv_mask = chunk_ids - torch::arange(0, num_chunks, dst_global_neg_embeddings_.device()).view({num_chunks, -1});
mask = (inv_mask == 0);
temp_idx = torch::nonzero(mask);
id_offset = dst_sample.flatten(0, 1).index_select(0, (temp_idx.select(1, 0) * num_deg + temp_idx.select(1, 1)));
sample_offset = temp_idx.select(1, 1);
dst_all_neg_embeddings_ = torch::cat({dst_global_neg_embeddings_, dst_pos_embeddings_.index_select(0, dst_sample.flatten(0, 1)).view({num_chunks, num_deg, -1})}, 1);
dst_neg_filter_ = id_offset * dst_all_neg_embeddings_.size(1) + (dst_neg_size + sample_offset);
}
void Batch::accumulateUniqueIndices() {
Indices emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_, src_neg_indices_, dst_neg_indices_});
auto unique_tup = torch::_unique2(emb_idx, true, true, false);
unique_node_indices_ = get<0>(unique_tup);
Indices emb_mapping = get<1>(unique_tup);
int64_t curr = 0;
int64_t size = batch_size_;
src_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
dst_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
size = src_neg_indices_.size(0);
src_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
dst_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size);
SPDLOG_TRACE("Batch: {} Accumulated {} unique embeddings", batch_id_, unique_node_indices_.size(0));
if (marius_options.general.num_relations > 1) {
auto rel_unique_tup = torch::_unique2(rel_indices_, true, true, false);
unique_relation_indices_ = get<0>(rel_unique_tup);
rel_indices_mapping_ = get<1>(rel_unique_tup);
SPDLOG_TRACE("Batch: {} Accumulated {} unique relations", batch_id_, unique_relation_indices_.size(0));
}
status_ = BatchStatus::AccumulatedIndices;
}
void Batch::embeddingsToDevice(int device_id) {
device_id_ = device_id;
if (marius_options.general.device == torch::kCUDA) {
device_transfer_ = CudaEvent(device_id);
host_transfer_ = CudaEvent(device_id);
string device_string = "cuda:" + std::to_string(device_id);
src_pos_indices_mapping_ = src_pos_indices_mapping_.to(device_string);
dst_pos_indices_mapping_ = dst_pos_indices_mapping_.to(device_string);
src_neg_indices_mapping_ = src_neg_indices_mapping_.to(device_string);
dst_neg_indices_mapping_ = dst_neg_indices_mapping_.to(device_string);
SPDLOG_TRACE("Batch: {} Indices sent to device", batch_id_);
if (marius_options.storage.embeddings != BackendType::DeviceMemory) {
unique_node_embeddings_ = unique_node_embeddings_.to(device_string);
SPDLOG_TRACE("Batch: {} Embeddings sent to device", batch_id_);
if (train_) {
unique_node_embeddings_state_ = unique_node_embeddings_state_.to(device_string);
SPDLOG_TRACE("Batch: {} Node State sent to device", batch_id_);
}
}
if (marius_options.general.num_relations > 1) {
if (marius_options.storage.relations != BackendType::DeviceMemory) {
unique_relation_embeddings_ = unique_relation_embeddings_.to(device_string);
rel_indices_mapping_ = rel_indices_mapping_.to(device_string);
SPDLOG_TRACE("Batch: {} Relations sent to device", batch_id_);
if (train_) {
unique_relation_embeddings_state_ = unique_relation_embeddings_state_.to(device_string);
SPDLOG_TRACE("Batch: {} Relation State sent to device", batch_id_);
}
} else {
unique_relation_indices_ = unique_relation_indices_.to(device_string);
rel_indices_mapping_ = rel_indices_mapping_.to(device_string);
}
}
}
device_transfer_.record();
status_ = BatchStatus::TransferredToDevice;
}
void Batch::prepareBatch() {
device_transfer_.synchronize();
int64_t num_chunks = 0;
int64_t negatives = 0;
if (train_) {
num_chunks = marius_options.training.number_of_chunks;
negatives = marius_options.training.negatives * (1 - marius_options.training.degree_fraction);
} else {
num_chunks = marius_options.evaluation.number_of_chunks;
negatives = marius_options.evaluation.negatives * (1 - marius_options.evaluation.degree_fraction);
if (marius_options.evaluation.negative_sampling_access == NegativeSamplingAccess::All) {
num_chunks = 1;
negatives = marius_options.general.num_nodes;
}
}
src_pos_embeddings_ = unique_node_embeddings_.index_select(0, src_pos_indices_mapping_);
dst_pos_embeddings_ = unique_node_embeddings_.index_select(0, dst_pos_indices_mapping_);
src_global_neg_embeddings_ = unique_node_embeddings_.index_select(0, src_neg_indices_mapping_).reshape({num_chunks, negatives, marius_options.model.embedding_size});
dst_global_neg_embeddings_ = unique_node_embeddings_.index_select(0, dst_neg_indices_mapping_).reshape({num_chunks, negatives, marius_options.model.embedding_size});
if (marius_options.general.num_relations > 1) {
src_relation_emebeddings_ = unique_relation_embeddings_.index_select(1, rel_indices_mapping_).select(0, 0);
dst_relation_emebeddings_ = unique_relation_embeddings_.index_select(1, rel_indices_mapping_).select(0, 1);
}
if (train_) {
src_pos_embeddings_.requires_grad_();
dst_pos_embeddings_.requires_grad_();
src_global_neg_embeddings_.requires_grad_();
dst_global_neg_embeddings_.requires_grad_();
if (marius_options.general.num_relations > 1) {
src_relation_emebeddings_.requires_grad_();
dst_relation_emebeddings_.requires_grad_();
}
}
SPDLOG_TRACE("Batch: {} prepared for compute", batch_id_);
status_ = BatchStatus::PreparedForCompute;
}
void Batch::accumulateGradients() {
auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(src_pos_embeddings_.device());
unique_node_gradients_ = torch::zeros({unique_node_indices_.size(0), marius_options.model.embedding_size}, grad_opts);
unique_node_gradients_.index_add_(0, src_pos_indices_mapping_, src_pos_embeddings_.grad());
unique_node_gradients_.index_add_(0, src_neg_indices_mapping_, src_global_neg_embeddings_.grad().flatten(0, 1));
unique_node_gradients_.index_add_(0, dst_pos_indices_mapping_, dst_pos_embeddings_.grad());
unique_node_gradients_.index_add_(0, dst_neg_indices_mapping_, dst_global_neg_embeddings_.grad().flatten(0, 1));
SPDLOG_TRACE("Batch: {} accumulated node gradients", batch_id_);
if (marius_options.general.num_relations > 1) {
unique_relation_gradients_ = torch::zeros({2, unique_relation_indices_.size(0), marius_options.model.embedding_size}, grad_opts);
unique_relation_gradients_.index_add_(1, rel_indices_mapping_, torch::stack({src_relation_emebeddings_.grad(), dst_relation_emebeddings_.grad()}));
SPDLOG_TRACE("Batch: {} accumulated relation gradients", batch_id_);
unique_relation_gradients2_ = unique_relation_gradients_.pow(2);
unique_relation_embeddings_state_.add_(unique_relation_gradients2_);
unique_relation_gradients_ = -marius_options.training.learning_rate * (unique_relation_gradients_ / ((unique_relation_embeddings_state_).sqrt().add_(1e-9)));
}
unique_node_gradients2_ = unique_node_gradients_.pow(2);
unique_node_embeddings_state_.add_(unique_node_gradients2_);
unique_node_gradients_ = -marius_options.training.learning_rate * (unique_node_gradients_ / ((unique_node_embeddings_state_).sqrt().add_(1e-9)));
SPDLOG_TRACE("Batch: {} adjusted gradients", batch_id_);
src_pos_embeddings_ = torch::Tensor();
dst_pos_embeddings_ = torch::Tensor();
src_global_neg_embeddings_ = torch::Tensor();
dst_global_neg_embeddings_ = torch::Tensor();
src_all_neg_embeddings_ = torch::Tensor();
dst_all_neg_embeddings_ = torch::Tensor();
src_relation_emebeddings_ = torch::Tensor();
dst_relation_emebeddings_ = torch::Tensor();
unique_node_embeddings_state_ = torch::Tensor();
unique_relation_embeddings_state_ = torch::Tensor();
src_neg_filter_ = torch::Tensor();
dst_neg_filter_ = torch::Tensor();
SPDLOG_TRACE("Batch: {} cleared gpu embeddings and gradients", batch_id_);
status_ = BatchStatus::AccumulatedGradients;
}
void Batch::embeddingsToHost() {
torch::DeviceType emb_device = torch::kCPU;
if (marius_options.storage.embeddings == BackendType::DeviceMemory) {
// only single gpu setup
SPDLOG_TRACE("Batch: {} embedding storage on device", batch_id_);
emb_device = marius_options.general.device;
}
if (emb_device == torch::kCPU && unique_node_gradients_.device().type() == torch::kCUDA) {
auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).pinned_memory(true);
Gradients temp_grads = torch::empty(unique_node_gradients_.sizes(), grad_opts);
temp_grads.copy_(unique_node_gradients_, true);
Gradients temp_grads2 = torch::empty(unique_node_gradients2_.sizes(), grad_opts);
temp_grads2.copy_(unique_node_gradients2_, true);
unique_node_gradients_ = temp_grads;
unique_node_gradients2_ = temp_grads2;
SPDLOG_TRACE("Batch: {} transferred node embeddings to host", batch_id_);
}
if (marius_options.general.num_relations > 1) {
torch::DeviceType rel_device = torch::kCPU;
if (marius_options.storage.relations == BackendType::DeviceMemory) {
SPDLOG_TRACE("Batch: {} relation storage on device", batch_id_);
rel_device = marius_options.general.device;
}
if (rel_device == torch::kCPU && unique_relation_gradients_.device().type() == torch::kCUDA) {
auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).pinned_memory(true);
Gradients temp_grads = torch::empty(unique_relation_gradients_.sizes(), grad_opts);
temp_grads.copy_(unique_relation_gradients_, true);
Gradients temp_grads2 = torch::empty(unique_relation_gradients2_.sizes(), grad_opts);
temp_grads2.copy_(unique_relation_gradients2_, true);
unique_relation_gradients_ = temp_grads;
unique_relation_gradients2_ = temp_grads2;
SPDLOG_TRACE("Batch: {} transferred relation embeddings to host", batch_id_);
}
}
host_transfer_.record();
host_transfer_.synchronize();
status_ = BatchStatus::TransferredToHost;
}
void Batch::clear() {
unique_node_indices_ = torch::Tensor();
unique_node_embeddings_ = torch::Tensor();
unique_node_gradients_ = torch::Tensor();
unique_node_gradients2_ = torch::Tensor();
unique_node_embeddings_state_ = torch::Tensor();
unique_relation_indices_ = torch::Tensor();
unique_relation_embeddings_ = torch::Tensor();
unique_relation_gradients_ = torch::Tensor();
unique_relation_gradients2_ = torch::Tensor();
unique_relation_embeddings_state_ = torch::Tensor();
src_pos_indices_mapping_ = torch::Tensor();
dst_pos_indices_mapping_ = torch::Tensor();
rel_indices_mapping_ = torch::Tensor();
src_neg_indices_mapping_ = torch::Tensor();
dst_neg_indices_mapping_ = torch::Tensor();
src_pos_indices_ = torch::Tensor();
dst_pos_indices_ = torch::Tensor();
rel_indices_ = torch::Tensor();
src_neg_indices_ = torch::Tensor();
dst_neg_indices_ = torch::Tensor();
src_pos_embeddings_ = torch::Tensor();
dst_pos_embeddings_ = torch::Tensor();
src_relation_emebeddings_ = torch::Tensor();
dst_relation_emebeddings_ = torch::Tensor();
src_global_neg_embeddings_ = torch::Tensor();
dst_global_neg_embeddings_ = torch::Tensor();
src_all_neg_embeddings_ = torch::Tensor();
dst_all_neg_embeddings_ = torch::Tensor();
src_neg_filter_ = torch::Tensor();
dst_neg_filter_ = torch::Tensor();
SPDLOG_TRACE("Batch: {} cleared", batch_id_);
status_ = BatchStatus::Done;
}
PartitionBatch::PartitionBatch(bool train) : Batch(train) {}
// TODO optionally keep unique index data around so it doesn't need to be recomputed in future epochs
void PartitionBatch::clear() {
Batch::clear();
pos_uniques_idx_ = torch::Tensor();
src_pos_uniques_idx_ = torch::Tensor();
dst_pos_uniques_idx_ = torch::Tensor();
neg_uniques_idx_ = torch::Tensor();
}
void PartitionBatch::accumulateUniqueIndices() {
NegativeSamplingAccess negative_sampling_access = marius_options.training.negative_sampling_access;
if (!train_) {
negative_sampling_access = marius_options.evaluation.negative_sampling_access;
}
if (negative_sampling_access == NegativeSamplingAccess::Uniform) {
if (src_partition_idx_ == dst_partition_idx_) {
Indices emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_, src_neg_indices_, dst_neg_indices_});
auto unique_tup = torch::_unique2(emb_idx, true, true, false);
unique_node_indices_ = get<0>(unique_tup);
Indices emb_mapping = get<1>(unique_tup);
int64_t curr = 0;
int64_t size = batch_size_;
src_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
dst_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
size = src_neg_indices_.size(0);
src_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size);
curr += size;
dst_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size);
} else {
Indices src_emb_idx = torch::cat({src_pos_indices_, src_neg_indices_});
auto src_pos_unique_tup = torch::_unique2(src_emb_idx, true, true, false);
auto src_pos_uniques_idx = get<0>(src_pos_unique_tup);
auto src_emb_mapping = get<1>(src_pos_unique_tup);
int64_t curr = 0;
int64_t size = batch_size_;
src_pos_indices_mapping_ = src_emb_mapping.narrow(0, curr, size);
curr += size;
size = src_neg_indices_.size(0);
src_neg_indices_mapping_ = src_emb_mapping.narrow(0, curr, size);
Indices dst_emb_idx = torch::cat({dst_pos_indices_, dst_neg_indices_});
auto dst_pos_unique_tup = torch::_unique2(dst_emb_idx, true, true, false);
auto dst_pos_uniques_idx = get<0>(dst_pos_unique_tup);
auto dst_emb_mapping = get<1>(dst_pos_unique_tup) + src_pos_uniques_idx.size(0);
curr = 0;
size = batch_size_;
dst_pos_indices_mapping_ = dst_emb_mapping.narrow(0, curr, size);
curr += size;
size = dst_neg_indices_.size(0);
dst_neg_indices_mapping_ = dst_emb_mapping.narrow(0, curr, size);
unique_node_indices_ = torch::cat({src_pos_uniques_idx, dst_pos_uniques_idx});
pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0));
src_pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0));
dst_pos_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0), dst_pos_uniques_idx.size(0));
}
} else {
if (src_partition_idx_ == dst_partition_idx_) {
// calculate uniques for positives
Indices pos_emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_});
auto pos_unique_tup = torch::_unique2(pos_emb_idx, true, true, false);
auto pos_uniques_idx = get<0>(pos_unique_tup);
Indices pos_emb_mapping = get<1>(pos_unique_tup);
int64_t curr = 0;
int64_t size = batch_size_;
src_pos_indices_mapping_ = pos_emb_mapping.narrow(0, curr, size);
curr += size;
dst_pos_indices_mapping_ = pos_emb_mapping.narrow(0, curr, size);
// calculate uniques for negatives
Indices neg_uniques_idx;
Indices neg_emb_idx = torch::cat({src_neg_indices_, dst_neg_indices_});
auto neg_unique_tup = torch::_unique2(neg_emb_idx, true, true, false);
neg_uniques_idx = get<0>(neg_unique_tup);
Indices neg_emb_mapping = get<1>(neg_unique_tup);
curr = 0;
size = src_neg_indices_.size(0);
src_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size);
curr += size;
dst_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size);
// add offset to negative mapping to account for the torch::cat
src_neg_indices_mapping_ += pos_uniques_idx.size(0);
dst_neg_indices_mapping_ += pos_uniques_idx.size(0);
unique_node_indices_ = torch::cat({pos_uniques_idx, neg_uniques_idx});
pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, pos_uniques_idx.size(0));
neg_uniques_idx_ = unique_node_indices_.narrow(0, pos_uniques_idx.size(0), neg_uniques_idx.size(0));
} else {
auto src_pos_unique_tup = torch::_unique2(src_pos_indices_, true, true, false);
auto src_pos_uniques_idx = get<0>(src_pos_unique_tup);
src_pos_indices_mapping_ = get<1>(src_pos_unique_tup);
auto dst_pos_unique_tup = torch::_unique2(dst_pos_indices_, true, true, false);
auto dst_pos_uniques_idx = get<0>(dst_pos_unique_tup);
dst_pos_indices_mapping_ = get<1>(dst_pos_unique_tup) + src_pos_uniques_idx.size(0);
Indices neg_uniques_idx;
int64_t size;
int64_t curr;
Indices neg_emb_idx = torch::cat({src_neg_indices_, dst_neg_indices_});
auto neg_unique_tup = torch::_unique2(neg_emb_idx, true, true, false);
neg_uniques_idx = get<0>(neg_unique_tup);
Indices neg_emb_mapping = get<1>(neg_unique_tup);
curr = 0;
size = src_neg_indices_.size(0);
src_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size);
curr += size;
dst_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size);
// add offset to negative mapping to account for the torch::cat
src_neg_indices_mapping_ += src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0);
dst_neg_indices_mapping_ += src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0);
unique_node_indices_ = torch::cat({src_pos_uniques_idx, dst_pos_uniques_idx, neg_uniques_idx});
pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0));
src_pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0));
dst_pos_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0), dst_pos_uniques_idx.size(0));
neg_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0), neg_uniques_idx.size(0));
}
}
rel_indices_mapping_ = torch::zeros({1}, torch::kInt64);
unique_relation_indices_ = torch::zeros({1}, torch::kInt64);
if (marius_options.general.num_relations > 1) {
auto rel_unique_tup = torch::_unique2(rel_indices_, true, true, false);
unique_relation_indices_ = get<0>(rel_unique_tup);
rel_indices_mapping_ = get<1>(rel_unique_tup);
}
status_ = BatchStatus::AccumulatedIndices;
}
| 48.570175 | 169 | 0.696858 | AnzeXie |
98dddbe2db5c4a9eb71634f1d3ba3e1e28b72bbe | 2,668 | cpp | C++ | ssdb/src/util/io_cache.cpp | taihedeveloper/SSDB-Cluster | b8279dc42af24f8a244842f4d5191b3d1894ce88 | [
"Apache-2.0"
] | 6 | 2017-06-14T03:57:52.000Z | 2017-06-14T06:54:01.000Z | ssdb/src/util/io_cache.cpp | taihedeveloper/SSDB-Cluster | b8279dc42af24f8a244842f4d5191b3d1894ce88 | [
"Apache-2.0"
] | null | null | null | ssdb/src/util/io_cache.cpp | taihedeveloper/SSDB-Cluster | b8279dc42af24f8a244842f4d5191b3d1894ce88 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2012-2014 The SSDB 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 <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "io_cache.h"
int WriteCache::append(const char *data, int size) {
// flush cache to file
if (space() < size && flush_to_file() != 0) {
return -1;
}
// write file directly
if (size > cap) {
int writebytes = writen(fd, data, size);
if (writebytes != size)
return -1;
return 0;
}
// append to cache
memcpy(end, data, size);
end += size;
return 0;
}
int WriteCache::append(const std::string &s) {
return append(s.data(), s.size());
}
int WriteCache::flush_to_file() {
int len = data_len();
int ret = writen(fd, buf, len);
if (ret != len)
return -1;
reset();
return 0;
}
int WriteCache::sync_file() {
int ret = fsync(fd);
return ret;
}
int WriteCache::writen(int fd, const char *buf, size_t n) {
int left = n;
int err = 0;
while (left > 0) {
int ret = write(fd, buf+n-left, left);
if (ret < 0 && (err = errno) == EINTR)
continue;
if (ret < 0) {
return ret;
}
left -= ret;
}
return (int)(n - left);
}
int ReadCache::readn(char *dst, int n) {
assert (n > 0);
if (this->left() >= n) {
memcpy(dst, cur, n);
cur += n;
return n;
}
int left = n;
if (this->left() > 0) {
memcpy(dst, cur, this->left());
left -= this->left();
}
offset += (uint64_t)(end-buf);
reset();
int ret = 0;
if (left > cap / 2) { // decrease data copy
ret = readn(fd, dst+n-left, left);
if (ret < 0) {
return ret;
}
left -= ret;
offset += ret;
} else {
ret = readn(fd, buf, cap);
if (ret < 0) {
return ret;
}
if (ret > 0) {
cur = buf;
end = cur + ret;
int bytes2read = left < this->left() ? left : this->left();
memcpy(dst+n-left, cur, bytes2read);
cur += bytes2read;
left -= bytes2read;
}
}
return n - left;
}
int ReadCache::readn(int fd, char *buf, int n) {
int err = 0;
int left = n;
while (left > 0) {
int ret = read(fd, buf+n-left, left);
if (ret < 0 && (err=errno) == EINTR)
continue;
if (ret < 0) {
return -1;
}
if (ret == 0) //EOF
break;
left -= ret;
}
return n - left;
}
int ReadCache::seek(uint64_t pos) {
if (pos < offset) {
return -1;
}
while (offset+(uint64_t)(end-buf) < pos) {
offset += (uint64_t)(end-buf);
reset();
int ret = readn(fd, buf, cap);
if (ret < 0) {
return -1;
}
if (ret == 0) break;
if (ret > 0) {
end += ret;
}
}
if (offset+(uint64_t)(end-buf) < pos) {
return -1;
}
cur += (pos - offset) - (cur - buf);
assert (cur <= end);
return 0;
}
| 16.886076 | 70 | 0.566342 | taihedeveloper |
98df469bb052f9bf20c3cac05f4cc987a6cea995 | 9,467 | cpp | C++ | drivers/CoreLED/tests/CoreLED_test_setColor.cpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreLED/tests/CoreLED_test_setColor.cpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreLED/tests/CoreLED_test_setColor.cpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | // Leka - LekaOS
// Copyright 2022 APF France handicap
// SPDX-License-Identifier: Apache-2.0
#include "CoreLED.h"
#include "CoreSPI.h"
#include "gtest/gtest.h"
#include "mocks/leka/SPI.h"
using namespace leka;
class CoreLedSetColorTest : public ::testing::Test
{
protected:
CoreLedSetColorTest() = default;
// void SetUp() override {}
// void TearDown() override {}
static constexpr int number_of_leds = 20;
std::array<RGB, number_of_leds> expected_colors {};
CoreSPI spi {NC, NC, NC, NC};
CoreLED<number_of_leds> leds {spi};
};
TEST_F(CoreLedSetColorTest, setColorPredefinedForAll)
{
auto color = RGB::pure_red;
std::fill(expected_colors.begin(), expected_colors.end(), color);
leds.setColor(color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorUserDefinedForAll)
{
auto color = RGB {120, 12, 56};
std::fill(expected_colors.begin(), expected_colors.end(), color);
leds.setColor(color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexFirst)
{
auto index = 0;
auto color = RGB::pure_green;
expected_colors.at(index) = color;
leds.setColorAtIndex(index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexMiddle)
{
auto index = number_of_leds / 2 - 1;
auto color = RGB::pure_green;
expected_colors.at(index) = color;
leds.setColorAtIndex(index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexLast)
{
auto index = number_of_leds - 1;
auto color = RGB::pure_green;
expected_colors.at(index) = color;
leds.setColorAtIndex(index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexEqualNumberOfLeds)
{
auto index = number_of_leds;
auto color = RGB::pure_green;
leds.setColorAtIndex(index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexHigherThanNumberOfLeds)
{
auto index = number_of_leds + 100;
auto color = RGB::pure_green;
leds.setColorAtIndex(index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorAtIndexFirstMiddleEnd)
{
auto first_index = 0;
auto middle_index = number_of_leds / 2 - 1;
auto end_index = number_of_leds - 1;
auto first_color = RGB::pure_red;
auto middle_color = RGB::pure_green;
auto end_color = RGB::pure_blue;
expected_colors.at(first_index) = first_color;
expected_colors.at(middle_index) = middle_color;
expected_colors.at(end_index) = end_color;
leds.setColorAtIndex(first_index, first_color);
leds.setColorAtIndex(middle_index, middle_color);
leds.setColorAtIndex(end_index, end_color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorFromArray)
{
auto expected_colors = std::to_array<RGB>(
{RGB::pure_blue, RGB::pure_green, RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta,
RGB::pure_green, RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta, RGB::pure_green,
RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta, RGB::black});
leds.setColorWithArray(expected_colors);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRange)
{
RGB color = RGB::pure_green;
int range_begin_index = 2;
int range_end_index = 5;
for (auto i = range_begin_index; i <= range_end_index; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeFirstLast)
{
RGB color = RGB::pure_green;
int range_begin_index = 0;
int range_end_index = number_of_leds - 1;
for (auto i = range_begin_index; i <= range_end_index; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeFirstMiddle)
{
RGB color = RGB::pure_green;
int range_begin_index = 0;
int range_end_index = number_of_leds / 2 - 1;
for (auto i = range_begin_index; i <= range_end_index; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeMiddleLast)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds / 2 - 1;
int range_end_index = number_of_leds - 1;
for (auto i = range_begin_index; i <= range_end_index; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeMiddleLastEqualNumberOfLeds)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds / 2 - 1;
int range_end_index = number_of_leds;
for (auto i = range_begin_index; i < number_of_leds; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeMiddleLastHigherThanNumberOfLeds)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds / 2 - 1;
int range_end_index = number_of_leds + 100;
for (auto i = range_begin_index; i < number_of_leds; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeInverted)
{
RGB color = RGB::pure_green;
int range_begin_index = 3;
int range_end_index = 0;
for (auto i = range_end_index; i <= range_begin_index; ++i) {
expected_colors.at(i) = color;
}
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndFirst)
{
RGB color = RGB::pure_green;
int range_begin_index = 0;
int range_end_index = 0;
expected_colors.at(range_begin_index) = color;
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndMiddle)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds / 2 - 1;
int range_end_index = number_of_leds / 2 - 1;
expected_colors.at(range_begin_index) = color;
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLast)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds - 1;
int range_end_index = number_of_leds - 1;
expected_colors.at(range_begin_index) = color;
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLastEqualNumberOfLeds)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds;
int range_end_index = number_of_leds;
// nothing to do for this test
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLastHigherThanNumberOfLeds)
{
RGB color = RGB::pure_green;
int range_begin_index = number_of_leds + 100;
int range_end_index = number_of_leds + 100;
// nothing to do for this test
leds.setColorRange(range_begin_index, range_end_index, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
TEST_F(CoreLedSetColorTest, setColorRangeUpperLimite)
{
RGB color = RGB::pure_green;
// nothing to do for this test
leds.setColorRange(20, 20, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
leds.setColorRange(21, 20, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
leds.setColorRange(20, 21, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
leds.setColorRange(21, 21, color);
EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin()));
}
| 28.601208 | 111 | 0.745115 | MMyster |
98e1a3140d600d971c7c2fd6881eb4a479c25273 | 52 | cpp | C++ | src/mos/io/keyboard.cpp | morganbengtsson/mo | c719ff6b35478b068988901d0bf7253cb672e87a | [
"MIT"
] | 230 | 2016-02-15T20:46:01.000Z | 2022-03-07T11:56:12.000Z | src/mos/io/keyboard.cpp | morganbengtsson/mo | c719ff6b35478b068988901d0bf7253cb672e87a | [
"MIT"
] | 79 | 2016-02-07T11:37:04.000Z | 2021-09-29T09:14:27.000Z | src/mos/io/keyboard.cpp | morganbengtsson/mo | c719ff6b35478b068988901d0bf7253cb672e87a | [
"MIT"
] | 14 | 2018-05-16T13:10:22.000Z | 2021-09-28T10:23:31.000Z | #include <mos/io/keyboard.hpp>
namespace mos::io{
}
| 13 | 30 | 0.711538 | morganbengtsson |
98e4d0f16b7d118ebb317dd7d354e1fd103ead5f | 851 | cpp | C++ | cppPrime/function_c07/test_08.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/function_c07/test_08.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/function_c07/test_08.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
> File Name: test_08.cpp
> Author: @Yoghourt->ilvcr, Cn,Sx,Ty
> Mail: [email protected] || [email protected]
> Created Time: 2018年06月27日 星期三 21时25分24秒
> Description:
************************************************************************/
#include<iostream>
using namespace std;
int min( int*, int* );
int (*pf)(int*, int) = min;
const int iaSize = 5;
int ia[ iaSize ] = {7, 4, 9, 2, 5};
int main(){
cout << " Direct call: min: "
<< min( ia, iaSize ) << endl;
cout << "Indirect call: min: "
<< pf( ia, iaSize ) << endl;
return 0;
}
int min( int* ia, int sz ){
int minVal = ia[ 0 ];
for( int ix = 1; ix < sz; ++ix ){
if( minVal > ia[ ix ] ){
minVal = iz[ ix ];
}
}
return minVal;
}
| 21.275 | 74 | 0.434783 | ilvcr |
98e71f3c82ba79d2a67cc38a31c241fe80ef5b2a | 620 | hpp | C++ | lib/include/tinytmxWangTile.hpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | 2 | 2022-01-10T07:53:48.000Z | 2022-03-22T11:25:50.000Z | lib/include/tinytmxWangTile.hpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | null | null | null | lib/include/tinytmxWangTile.hpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | null | null | null | #ifndef TINYTMX_TINYTMXWANGTILE_HPP
#define TINYTMX_TINYTMXWANGTILE_HPP
#include <vector>
namespace tinyxml2 {
class XMLElement;
}
namespace tinytmx {
class WangTile {
public:
WangTile();
void Parse(tinyxml2::XMLElement const *wangTileElement);
/// Get the tile ID.
[[nodiscard]] uint32_t GetTileId() const { return tileID; }
/// Get the wang ID.
[[nodiscard]] std::vector<uint32_t> const &GetWangID() const { return wangID; }
private:
uint32_t tileID;
std::vector<uint32_t> wangID;
};
}
#endif //TINYTMX_TINYTMXWANGTILE_HPP
| 18.787879 | 87 | 0.646774 | KaseyJenkins |
98ee51c1b20c72bc9cf591da5dd99957cc9359ae | 5,688 | cpp | C++ | src/fft/fft_driver.cpp | lucyundead/athena--fork | 04a4027299145f61bdc08528548e0b1b398ba0a6 | [
"BSD-3-Clause"
] | 174 | 2016-11-30T01:20:14.000Z | 2022-02-22T16:23:55.000Z | src/fft/fft_driver.cpp | lucyundead/athena--fork | 04a4027299145f61bdc08528548e0b1b398ba0a6 | [
"BSD-3-Clause"
] | 74 | 2017-01-30T22:37:33.000Z | 2021-05-10T17:20:33.000Z | src/fft/fft_driver.cpp | lucyundead/athena--fork | 04a4027299145f61bdc08528548e0b1b398ba0a6 | [
"BSD-3-Clause"
] | 126 | 2016-12-08T14:03:22.000Z | 2022-03-31T06:01:59.000Z | //========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <[email protected]> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file fft_driver.cpp
// \brief implementation of functions in class FFTDriver
// C headers
// C++ headers
#include <cmath>
#include <iostream> // endl
#include <sstream> // sstream
#include <stdexcept> // runtime_error
#include <string> // c_str()
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../coordinates/coordinates.hpp"
#include "../mesh/mesh.hpp"
#include "../parameter_input.hpp"
#include "athena_fft.hpp"
#ifdef MPI_PARALLEL
#include <mpi.h>
#endif
// constructor, initializes data structures and parameters
FFTDriver::FFTDriver(Mesh *pm, ParameterInput *pin) : nranks_(Globals::nranks),
pmy_mesh_(pm), dim_(pm->ndim) {
if (!(pm->use_uniform_meshgen_fn_[X1DIR])
|| !(pm->use_uniform_meshgen_fn_[X2DIR])
|| !(pm->use_uniform_meshgen_fn_[X3DIR])) {
std::stringstream msg;
msg << "### FATAL ERROR in FFTDriver::FFTDriver" << std::endl
<< "Non-uniform mesh spacing is not supported." << std::endl;
ATHENA_ERROR(msg);
return;
}
// Setting up the MPI information
// *** this part should be modified when dedicate processes are allocated ***
// *** we also need to construct another neighbor list for Multigrid ***
ranklist_ = new int[pm->nbtotal];
for (int n=0; n<pm->nbtotal; n++)
ranklist_[n] = pm->ranklist[n];
nslist_ = new int[nranks_];
nblist_ = new int[nranks_];
#ifdef MPI_PARALLEL
MPI_Comm_dup(MPI_COMM_WORLD, &MPI_COMM_FFT);
#endif
for (int n=0; n<nranks_; n++) {
nslist_[n] = pm->nslist[n];
nblist_[n] = pm->nblist[n];
}
int ns = nslist_[Globals::my_rank];
int ne = ns + nblist_[Globals::my_rank];
std::int64_t &lx1min = pm->loclist[ns].lx1;
std::int64_t &lx2min = pm->loclist[ns].lx2;
std::int64_t &lx3min = pm->loclist[ns].lx3;
std::int64_t lx1max = lx1min;
std::int64_t lx2max = lx2min;
std::int64_t lx3max = lx3min;
int current_level = pm->root_level;
for (int n=ns; n<ne; n++) {
std::int64_t &lx1 = pm->loclist[n].lx1;
std::int64_t &lx2 = pm->loclist[n].lx2;
std::int64_t &lx3 = pm->loclist[n].lx3;
lx1min = lx1min < lx1 ? lx1min : lx1;
lx2min = lx2min < lx2 ? lx2min : lx2;
lx3min = lx3min < lx3 ? lx3min : lx3;
lx1max = lx1max > lx1 ? lx1min : lx1;
lx2max = lx2max > lx2 ? lx2min : lx2;
lx3max = lx3max > lx3 ? lx3min : lx3;
if(pm->loclist[n].level > current_level) current_level = pm->loclist[n].level;
}
int ref_lev = current_level - pm->root_level;
// KGF: possible underflow from std::int64_t
int nbx1 = static_cast<int>(lx1max-lx1min+1);
int nbx2 = static_cast<int>(lx2max-lx2min+1);
int nbx3 = static_cast<int>(lx3max-lx3min+1);
nmb = nbx1*nbx2*nbx3; // number of MeshBlock to be loaded to the FFT block
if (pm->nbtotal/nmb != nranks_) {
// this restriction (to a single cuboid FFTBlock that covers the union of all
// MeshBlocks owned by an MPI rank) should be relaxed in the future
std::stringstream msg;
msg << "### FATAL ERROR in FFTDriver::FFTDriver" << std::endl
<< nmb << " MeshBlocks will be loaded to the FFT block." << std::endl
<< "Number of FFT blocks " << pm->nbtotal/nmb << " are not matched with "
<< "Number of processors " << nranks_ << std::endl;
ATHENA_ERROR(msg);
return;
}
// There should be only one FFTBlock per processor.
// MeshBlocks in the same processor will be gathered into FFTBlock of the processor.
fft_loclist_ = new LogicalLocation[nranks_];
for (int n=0; n<nranks_; n++) {
int ns_inner = nslist_[n];
fft_loclist_[n] = pm->loclist[ns_inner];
fft_loclist_[n].lx1 = fft_loclist_[n].lx1/nbx1;
fft_loclist_[n].lx2 = fft_loclist_[n].lx2/nbx2;
fft_loclist_[n].lx3 = fft_loclist_[n].lx3/nbx3;
}
npx1 = (pm->nrbx1*(1 << ref_lev))/nbx1;
npx2 = (pm->nrbx2*(1 << ref_lev))/nbx2;
npx3 = (pm->nrbx3*(1 << ref_lev))/nbx3;
fft_mesh_size_ = pm->mesh_size;
fft_mesh_size_.nx1 = pm->mesh_size.nx1*(1<<ref_lev);
fft_mesh_size_.nx2 = pm->mesh_size.nx2*(1<<ref_lev);
fft_mesh_size_.nx3 = pm->mesh_size.nx3*(1<<ref_lev);
fft_block_size_.nx1 = fft_mesh_size_.nx1/npx1;
fft_block_size_.nx2 = fft_mesh_size_.nx2/npx2;
fft_block_size_.nx3 = fft_mesh_size_.nx3/npx3;
gcnt_ = fft_mesh_size_.nx1*fft_mesh_size_.nx2*fft_mesh_size_.nx3;
#ifdef MPI_PARALLEL
decomp_ = 0; pdim_ = 0;
if (npx1 > 1) {
decomp_ = decomp_ | DecompositionNames::x_decomp;
pdim_++;
}
if (npx2 > 1) {
decomp_ = decomp_ | DecompositionNames::y_decomp;
pdim_++;
}
if (npx3 > 1) {
decomp_ = decomp_ | DecompositionNames::z_decomp;
pdim_++;
}
#endif
}
// destructor
FFTDriver::~FFTDriver() {
delete [] ranklist_;
delete [] nslist_;
delete [] nblist_;
delete [] fft_loclist_;
delete pmy_fb;
}
void FFTDriver::InitializeFFTBlock(bool set_norm) {
int igid = Globals::my_rank;
pmy_fb = new FFTBlock(this, fft_loclist_[igid], igid, fft_mesh_size_, fft_block_size_);
if (set_norm) pmy_fb->SetNormFactor(1./gcnt_);
}
void FFTDriver::QuickCreatePlan() {
pmy_fb->fplan_ = pmy_fb->QuickCreatePlan(
pmy_fb->in_, FFTBlock::AthenaFFTDirection::forward);
pmy_fb->bplan_ = pmy_fb->QuickCreatePlan(
pmy_fb->in_, FFTBlock::AthenaFFTDirection::backward);
return;
}
| 32.878613 | 90 | 0.640647 | lucyundead |
98f97725c5341d694b3a924a2113c4ded7ad2dbb | 1,054 | hpp | C++ | loggingDaemon/main/LoggingClientInterface/DomainSocket/ClientConnector/ClientConnectorThread.hpp | grobbles/linux-logging-daemon | da082225fcd037a5c91849702cf96de5805c816a | [
"MIT"
] | null | null | null | loggingDaemon/main/LoggingClientInterface/DomainSocket/ClientConnector/ClientConnectorThread.hpp | grobbles/linux-logging-daemon | da082225fcd037a5c91849702cf96de5805c816a | [
"MIT"
] | null | null | null | loggingDaemon/main/LoggingClientInterface/DomainSocket/ClientConnector/ClientConnectorThread.hpp | grobbles/linux-logging-daemon | da082225fcd037a5c91849702cf96de5805c816a | [
"MIT"
] | null | null | null | #ifndef CLIENT_CONNECTOR_HPP
#define CLIENT_CONNECTOR_HPP
#include <arpa/inet.h>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <mutex>
#include <netinet/in.h>
#include <pthread.h>
#include <sstream>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <thread>
#include <unistd.h>
#include <vector>
#include "Logging/Logger.hpp"
#include "ObserverPattern/Subject.hpp"
using namespace std;
class ClientConnectorThread : public Subject<string> {
private:
string logtag = "ClientConnectorThread";
string clientPid;
string ipcClientConnectionFile;
int create_socket;
int new_socket;
socklen_t addrlen;
struct sockaddr_un address;
public:
ClientConnectorThread(string ipcClientConnectionFile);
~ClientConnectorThread();
void createIpcSocket();
void runClientConnectionThread();
private:
bool isClientDead(string message);
};
#endif /* !CLIENT_CONNECTOR_HPP */ | 20.269231 | 58 | 0.736243 | grobbles |
98fa520108bf134cd77f90aa0148f92a56ffe35e | 3,719 | hpp | C++ | projects/thing/include/ecosnail/thing/entity_manager.hpp | ecosnail/ecosnail | 10b03f5924da41bca01031341a6cb10de624198e | [
"MIT"
] | null | null | null | projects/thing/include/ecosnail/thing/entity_manager.hpp | ecosnail/ecosnail | 10b03f5924da41bca01031341a6cb10de624198e | [
"MIT"
] | null | null | null | projects/thing/include/ecosnail/thing/entity_manager.hpp | ecosnail/ecosnail | 10b03f5924da41bca01031341a6cb10de624198e | [
"MIT"
] | null | null | null | #pragma once
#include <ecosnail/thing/entity.hpp>
#include <ecosnail/thing/entity_pool.hpp>
#include <ecosnail/tail.hpp>
#include <any>
#include <cassert>
#include <map>
#include <memory>
#include <optional>
#include <type_traits>
#include <typeindex>
#include <vector>
namespace ecosnail::thing {
class EntityManager {
template <class Component>
using ComponentMap = std::map<Entity, Component>;
template <class Component>
static ComponentMap<Component> emptyComponentMap;
public:
template <class Component>
const Component& component(Entity entity) const
{
assert(_components.count(typeid(Component)));
const auto& componentMap =
std::any_cast<const std::map<Entity, Component>&>(
_components.at(typeid(Component)));
assert(componentMap.count(entity));
return componentMap.at(entity);
}
template <class Component>
Component& component(Entity entity)
{
assert(_components.count(typeid(Component)));
auto& componentMap =
std::any_cast<std::map<Entity, Component>&>(
_components.at(typeid(Component)));
assert(componentMap.count(entity));
return componentMap.at(entity);
}
template <class Component>
auto components() const
{
auto it = _components.find(typeid(Component));
if (it == _components.end()) {
const auto& empty = emptyComponentMap<Component>;
return tail::valueRange(empty);
}
const auto& componentMap =
std::any_cast<const ComponentMap<Component>&>(it->second);
return tail::valueRange(componentMap);
}
template <class Component>
auto components()
{
auto it = _components.find(typeid(Component));
if (it == _components.end()) {
return tail::valueRange(emptyComponentMap<Component>);
}
auto& componentMap =
std::any_cast<ComponentMap<Component>&>(it->second);
return tail::valueRange(componentMap);
}
template <class Component>
auto entities() const
{
auto it = _components.find(typeid(Component));
if (it == _components.end()) {
return tail::keyRange(emptyComponentMap<Component>);
}
const auto& componentMap =
std::any_cast<const std::map<Entity, Component>&>(it->second);
return tail::keyRange(componentMap);
}
template <class Component>
auto& add(Entity entity)
{
static_assert(
std::is_default_constructible<Component>(),
"Component is not default-constructible");
return add<Component>(entity, Component{});
}
template <class Component>
auto& add(Entity entity, Component&& component)
{
using ComponentMap = std::map<Entity, Component>;
std::type_index typeIndex(typeid(Component));
auto it = _components.find(typeIndex);
if (it == _components.end()) {
it = _components.insert({typeIndex, ComponentMap()}).first;
}
auto& componentMap = std::any_cast<ComponentMap&>(it->second);
assert(!componentMap.count(entity));
return componentMap.insert(
{entity, std::forward<Component>(component)}).first->second;
}
Entity createEntity()
{
return _entityPool.createEntity();
}
void killEntity(Entity entity)
{
_entityPool.killEntity(entity);
}
private:
EntityPool _entityPool;
std::map<std::type_index, std::any> _components;
};
template <class Component>
EntityManager::ComponentMap<Component> EntityManager::emptyComponentMap;
} // namespace ecosnail::thing
| 27.345588 | 74 | 0.632428 | ecosnail |
98fbc41a5bd8bfd58a94e19c4622ea662c42b56b | 978 | cpp | C++ | test/utility/move_if_noexcept_test.cpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | test/utility/move_if_noexcept_test.cpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | test/utility/move_if_noexcept_test.cpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | #include <nek/utility/move_if_noexcept.hpp>
#include <gtest/gtest.h>
#include <string>
namespace
{
struct noexceptable
{
std::string log = "";
noexceptable() = default;
noexceptable(noexceptable const&) noexcept
{
log += "copy ctor";
}
noexceptable(noexceptable&&) noexcept
{
log += "move ctor";
}
};
struct exceptable
{
std::string log = "";
exceptable() = default;
exceptable(exceptable const&)
{
log += "copy ctor";
}
exceptable(exceptable&&)
{
log += "move ctor";
}
};
}
TEST(move_if_noexcept_test, except)
{
exceptable e;
auto actual = nek::move_if_noexcept(e);
EXPECT_EQ("copy ctor", actual.log);
}
TEST(move_if_noexcept_test, noexcept)
{
noexceptable e;
auto actual = nek::move_if_noexcept(e);
EXPECT_EQ("move ctor", actual.log);
}
| 17.781818 | 50 | 0.539877 | nekko1119 |
c7018a0b45be17c46358868adc0a6772d938fbd7 | 1,419 | hpp | C++ | BB10-Cordova/MessageRetrieve/plugin/src/blackberry10/native/src/message_ndk.hpp | stefanschielke/WebWorks-Community-APIs | fbf4d6708f1e783788b7bfe9dfb3d276c44bd6ce | [
"Apache-2.0"
] | 37 | 2015-01-10T00:32:35.000Z | 2020-07-17T14:10:41.000Z | BB10-Cordova/MessageRetrieve/plugin/src/blackberry10/native/src/message_ndk.hpp | stefanschielke/WebWorks-Community-APIs | fbf4d6708f1e783788b7bfe9dfb3d276c44bd6ce | [
"Apache-2.0"
] | 52 | 2015-01-02T11:20:59.000Z | 2018-09-04T09:08:09.000Z | BB10-Cordova/MessageRetrieve/plugin/src/blackberry10/native/src/message_ndk.hpp | stefanschielke/WebWorks-Community-APIs | fbf4d6708f1e783788b7bfe9dfb3d276c44bd6ce | [
"Apache-2.0"
] | 46 | 2015-01-16T18:52:13.000Z | 2020-07-01T09:03:14.000Z | /*
* Copyright (c) 2013 BlackBerry 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.
*/
#ifndef TEMPLATENDK_HPP_
#define TEMPLATENDK_HPP_
#include <string>
#include <pthread.h>
#include <bb/pim/account/AccountService>
#include <bb/pim/message/MessageService>
class MessageJS;
namespace webworks {
class MessageNDK {
public:
explicit MessageNDK(MessageJS *parent = NULL);
virtual ~MessageNDK();
// The extension methods are defined here
std::string ping();
std::string getEmailMessage(const std::string& accountId, const std::string& messageId);
private:
MessageJS *m_pParent;
int messageProperty;
int messageThreadCount;
bool threadHalt;
std::string threadCallbackId;
pthread_t m_thread;
pthread_cond_t cond;
pthread_mutex_t mutex;
bb::pim::message::MessageService* _message_service;
bb::pim::account::AccountService* _account_service;
};
} // namespace webworks
#endif /* TEMPLATENDK_H_ */
| 24.465517 | 89 | 0.764623 | stefanschielke |
c703586500f37657304b4b8df2ef3147424bc2e9 | 4,791 | cpp | C++ | [FW]my_heat/src/main.cpp | sunduoze/my_heat | af62f1cabc5640f2c63332fcfc74915bb551a83e | [
"MIT"
] | null | null | null | [FW]my_heat/src/main.cpp | sunduoze/my_heat | af62f1cabc5640f2c63332fcfc74915bb551a83e | [
"MIT"
] | 2 | 2022-03-27T14:58:55.000Z | 2022-03-31T04:59:36.000Z | [FW]my_heat/src/main.cpp | sunduoze/my_heat | af62f1cabc5640f2c63332fcfc74915bb551a83e | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "OpenT12.h"
BluetoothSerial SerialBT;
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
OneButton RButton(BUTTON_PIN, true);
U8G2_SSD1306_128X64_NONAME_F_HW_I2C Disp(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 22, /* data=*/21);
PID MyPID(&TipTemperature, &PID_Output, &PID_Setpoint, aggKp, aggKi, aggKd, DIRECT);
/////////////////////////////////////////////////////////////////
char* TipName = (char*)"文件系统错误:请上报";
float BootTemp = 60; //开机温度 (°C)
float SleepTemp = 60; //休眠温度 (°C)
float BoostTemp = 50; //爆发模式升温幅度 (°C)
float ShutdownTime = 0; //关机提醒 (分)
float SleepTime = 10; //休眠触发时间 (分)
float ScreenProtectorTime = 60; //屏保在休眠后的触发时间(秒)
float BoostTime = 60; //爆发模式持续时间 (秒)
bool SYS_Ready = false;
//烙铁头事件
bool TipInstallEvent = true;
bool TipCallSleepEvent = false;
//到温提示音播放完成
bool TempToneFlag = false;
//休眠后屏保延迟显示标志
bool SleepScreenProtectFlag = false;
//温控系统状态
bool ERROREvent = false;
bool ShutdownEvent = false;
bool SleepEvent = false;
bool BoostEvent = false;
bool UnderVoltageEvent = false;
//PWM控制状态
bool PWM_WORKY = false;
uint8_t PIDMode = true;
uint8_t Use_KFP = true;
uint8_t PanelSettings = PANELSET_Detailed;
uint8_t ScreenFlip = false;
uint8_t SmoothAnimation_Flag = true;
float ScreenBrightness = 128;
uint8_t OptionStripFixedLength_Flag = false;
uint8_t Volume = true;
uint8_t RotaryDirection = false;
uint8_t HandleTrigger = HANDLETRIGGER_VibrationSwitch;
double SYS_Voltage = 3.3;
float UndervoltageAlert = 3;
char BootPasswd[20] = {0};
uint8_t Language = LANG_Chinese;
uint8_t MenuListMode = false;
float ADC_PID_Cycle = 220;
//面板状态条
uint8_t TempCTRL_Status = TEMP_STATUS_OFF;
uint8_t* C_table[] = {c1, c2, c3, Lightning, c5, c6, c7};
char* TempCTRL_Status_Mes[] = {
(char*)"错误",
(char*)"停机",
(char*)"休眠",
(char*)"提温",
(char*)"正常",
(char*)"加热",
(char*)"维持",
};
// D:67.50,66.29,41.21,10.00,0.44,2.27,28.97,-0.14 P10 I 2 D
//先初始化硬件->显示LOGO->初始化软件
void setup()
{
noInterrupts();//关闭中断
heat_hw_init();
SYS_Ready = true;
}
void loop()
{
//获取按键
sys_KeyProcess();
// Serial.printf("Temp:%.6fmV,%.6fmV\r\n", analogRead(TIP_ADC_PIN) / 4096.0 * 3300, analogRead(CUR_ADC_PIN) / 4096.0 * 3300);
if (!Menu_System_State)
{
//温度闭环控制
TemperatureControlLoop();
//更新系统事件::系统事件可能会改变功率输出
TimerEventLoop();
}
//更新状态码
SYS_StateCode_Update();
// Serial.printf("D:%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f\r\n", PID_Setpoint, TipTemperature, PID_Output, \
// analogRead(TIP_ADC_PIN) / 4096.0 * 3300, \
// analogRead(CUR_ADC_PIN) / 4096.0 * 3300, \
// MyPID.p, MyPID.i, MyPID.d, MyPID.i_item, MyPID.d_item);
Serial.printf("D:%3.2f,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f\r\n", PID_Setpoint, TipTemperature, PID_Output, \
MyPID.p, MyPID.i, MyPID.d, MyPID.p_item, MyPID.i_item, MyPID.d_item);
SetPOWER((uint8_t)PID_Output);
//刷新UI
System_UI();
}
/**
* @description: 计算主电源电压
* @param {*}
* @return 主电源电压估计值
*/
double Get_MainPowerVoltage(void)
{
//uint16_t POWER_ADC = analogRead(POWER_ADC_PIN);
// double TipADC_V_R2 = analogReadMilliVolts(POWER_ADC_PIN) / 1000.0;
// //double TipADC_V_R2 = ESP32_ADC2Vol(POWER_ADC);
// double TipADC_V_R1 = (TipADC_V_R2 * POWER_ADC_VCC_R1) / POWER_ADC_R2_GND;
// SYS_Voltage = TipADC_V_R1 + TipADC_V_R2;
SYS_Voltage = analogReadMilliVolts(POWER_ADC_PIN) * 0.1f / 1000.0f;
return SYS_Voltage;
}
void SYS_Reboot(void)
{
ESP.restart();
}
void About(void)
{
//播放Logo动画
EnterLogo();
//生成项目QRCode
QRCode qrcode;
uint8_t qrcodeData[qrcode_getBufferSize(3)];
switch (Language)
{
case LANG_Chinese:
qrcode_initText(&qrcode, qrcodeData, 3, 0, "https://gitee.com/createskyblue/OpenT12");
break;
default:
qrcode_initText(&qrcode, qrcodeData, 3, 0, "https://github.com/createskyblue/OpenT12");
break;
}
Clear();
uint8_t x_offset = (SCREEN_COLUMN - qrcode.size * 2) / 2;
uint8_t y_offset = (SCREEN_ROW - qrcode.size * 2) / 2;
for (uint8_t y = 0; y < qrcode.size; y++)
for (uint8_t x = 0; x < qrcode.size; x++)
if (qrcode_getModule(&qrcode, x, y))
Draw_Pixel_Resize(x + x_offset, y + y_offset, x_offset, y_offset, 2, 2);
Disp.setDrawColor(2);
Disp.drawBox(x_offset - 2, y_offset - 2, qrcode.size * 2 + 4, qrcode.size * 2 + 4);
Disp.setDrawColor(1);
while (!sys_KeyProcess())
{
Display();
}
} | 28.349112 | 129 | 0.631392 | sunduoze |
c70551b2c09dd1d37d08a68ce62ca5c7082a104e | 5,993 | cpp | C++ | console/main.cpp | thijsjanzen/OVRT | 30cbbd9994f1463f806faa92a3cd9b967d37dbae | [
"MIT"
] | null | null | null | console/main.cpp | thijsjanzen/OVRT | 30cbbd9994f1463f806faa92a3cd9b967d37dbae | [
"MIT"
] | null | null | null | console/main.cpp | thijsjanzen/OVRT | 30cbbd9994f1463f806faa92a3cd9b967d37dbae | [
"MIT"
] | null | null | null | #include <cstring>
#include <chrono>
#include "../Simulation/simulation.hpp"
#include "../Simulation/analysis.hpp"
#include "config_parser.h"
// forward declaration
bool file_exists (const std::string& name);
void read_parameters_from_ini(Param& p, const std::string file_name);
void obtain_equilibrium(simulation& Simulation, const Param& all_parameters);
int main(int argc, char *argv[]) {
std::cout << "Welcome to this In Silico Simulation of oncolytic tumor virotherapy\n";
std::cout << "Copyright 2019 - 2022, D. Bhatt, T. Janzen & F.J. Weissing\n";
std::cout << "This is version: 0.9.0\n";
std::cout << "All files are to be found in this folder: \n";
std::cout << argv[0] << "\n";
InputParser input(argc, argv);
std::string file_name = "config.ini";
const std::string &filename = input.getCmdOption("-f");
if (!filename.empty()){
file_name = filename;
}
Param all_parameters;
read_parameters_from_ini(all_parameters, file_name);
read_from_command_line(input, all_parameters);
float max_t = 0;
std::array<size_t, 5> cell_counts = do_analysis(all_parameters, max_t);
std::string outcome = get_outcome(cell_counts);
if(!file_exists("output.txt")) {
// write header to file
std::ofstream outfile("output.txt");
outfile << "birth_virus" << "\t"
<< "death_virus" << "\t"
<< "birth_cancer" << "\t"
<< "death_cancer" << "\t"
<< "freq_resistant" << "\t"
<< "outcome" << "\t"
<< "num_normal_cells" << "\t"
<< "num_cancer_cells" << "\t"
<< "num_infected_cells" << "\t"
<< "num_resistant_cells" << "\t"
<< "num_empty_cells" << "\t"
<< "total_runtime" << "\n";
outfile.close();
}
std::ofstream outfile("output.txt", std::ios::app);
outfile << all_parameters.birth_infected << "\t"
<< all_parameters.death_infected << "\t"
<< all_parameters.birth_cancer << "\t"
<< all_parameters.death_cancer << "\t"
<< all_parameters.freq_resistant << "\t"
<< outcome << "\t";
for(size_t i = 0; i < 5; ++i) {
outfile << cell_counts[i] << "\t";
}
outfile << max_t << "\t";
outfile << "\n";
outfile.close();
return 0;
}
void read_parameters_from_ini(Param& p, const std::string file_name) {
ConfigFile from_config(file_name);
p.seed = from_config.getValueOfKey<size_t>("seed");
p.maximum_time = from_config.getValueOfKey<int>("maximum_time");
p.time_adding_cancer = from_config.getValueOfKey<int>("time_adding_cancer");
p.time_adding_virus = from_config.getValueOfKey<int>("time_adding_virus");
p.initial_number_cancer_cells = from_config.getValueOfKey<size_t>("initial_number_cancer_cells");
p.initial_number_normal_cells = from_config.getValueOfKey<size_t>("initial_number_normal_cells");
p.birth_normal = from_config.getValueOfKey<float>("birth_normal");
p.death_normal = from_config.getValueOfKey<float>("death_normal");
p.birth_cancer = from_config.getValueOfKey<float>("birth_cancer");
p.death_cancer = from_config.getValueOfKey<float>("death_cancer");
p.birth_infected = from_config.getValueOfKey<float>("birth_infected");
p.death_infected = from_config.getValueOfKey<float>("death_infected");
p.birth_cancer_resistant = from_config.getValueOfKey<float>("birth_resistant");
p.death_cancer_resistant = from_config.getValueOfKey<float>("death_resistant");
p.percent_infected = from_config.getValueOfKey<float>("percent_infected");
p.prob_normal_infection = from_config.getValueOfKey<float>("prob_normal_infection");
p.freq_resistant = from_config.getValueOfKey<float>("freq_resistant");
p.distance_infection_upon_death = from_config.getValueOfKey<float>("distance_infection_upon_death");
p.prob_infection_upon_death = from_config.getValueOfKey<float>("prob_infection_upon_death");
p.sq_num_cells = from_config.getValueOfKey<size_t>("sq_num_cells");
p.using_3d = from_config.getValueOfKey<bool>("using_3d");
p.infection_type = random_infection;
auto infection_string = from_config.getValueOfKey<std::string>("infection_type");
if(infection_string == "Random")
p.infection_type = random_infection;
if(infection_string == "Center")
p.infection_type = center_infection;
auto start_string = from_config.getValueOfKey<std::string>("start_type");
if(start_string == "Grow")
p.start_setup = grow;
if(start_string == "Full")
p.start_setup = full;
auto grid_string = from_config.getValueOfKey<std::string>("grid_type");
if(grid_string == "regular")
p.use_voronoi_grid = false;
if(grid_string == "voronoi")
p.use_voronoi_grid = true;
auto t_cell_sensitivity_stromal_string = from_config.getValueOfKey<std::string>("t_cell_stromal");
if (t_cell_sensitivity_stromal_string == "sensitive") {
p.t_cell_sensitivity[normal] = true;
} else {
p.t_cell_sensitivity[normal] = false;
}
auto t_cell_sensitivity_cancer_string = from_config.getValueOfKey<std::string>("t_cell_cancer");
if (t_cell_sensitivity_cancer_string == "sensitive") {
p.t_cell_sensitivity[cancer] = true;
} else {
p.t_cell_sensitivity[cancer] = false;
}
auto t_cell_sensitivity_infected_string = from_config.getValueOfKey<std::string>("t_cell_infected");
if (t_cell_sensitivity_infected_string == "sensitive") {
p.t_cell_sensitivity[infected] = true;
} else {
p.t_cell_sensitivity[infected] = false;
}
auto t_cell_sensitivity_resistant_string = from_config.getValueOfKey<std::string>("t_cell_resistant");
if (t_cell_sensitivity_resistant_string == "sensitive") {
p.t_cell_sensitivity[resistant] = true;
} else {
p.t_cell_sensitivity[resistant] = false;
}
return;
}
bool file_exists (const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
| 35.672619 | 104 | 0.680961 | thijsjanzen |
c7055cf0351ecaeb3c64e476aa7de332ca1ecb81 | 24,900 | cxx | C++ | HLT/rec/AliHLTReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | HLT/rec/AliHLTReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | HLT/rec/AliHLTReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | // $Id$
//**************************************************************************
//* This file is property of and copyright by the *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <[email protected]> *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
// @file AliHLTReconstructor.cxx
// @author Matthias Richter
// @date
// @brief Binding class for HLT reconstruction in AliRoot
// Implements bot the interface to run HLT chains embedded into
// AliReconstruction and the unpacking and treatment of HLTOUT
#include <TSystem.h>
#include <TObjString.h>
#include "TFile.h"
#include "TTree.h"
#include "TObject.h"
#include "TObjArray.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include "AliHLTReconstructor.h"
#include "AliLog.h"
#include "AliRawReader.h"
#include "AliESDEvent.h"
#include "AliHLTSystem.h"
#include "AliHLTOUTRawReader.h"
#include "AliHLTOUTDigitReader.h"
#include "AliHLTEsdManager.h"
#include "AliHLTPluginBase.h"
#include "AliHLTMisc.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliHLTMessage.h"
#include "AliCentralTrigger.h"
#include "AliTriggerConfiguration.h"
#include "AliTriggerClass.h"
#include "AliTriggerCluster.h"
#include "AliDAQ.h"
#include "AliRunLoader.h"
#include "AliRunInfo.h"
class AliCDBEntry;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTReconstructor)
AliHLTReconstructor::AliHLTReconstructor()
: AliReconstructor()
, fpEsdManager(NULL)
, fpPluginBase(new AliHLTPluginBase)
, fFlags(0)
, fProcessingStep(kProcessingStepUndefined)
{
//constructor
}
AliHLTReconstructor::AliHLTReconstructor(const char* options)
: AliReconstructor()
, fpEsdManager(NULL)
, fpPluginBase(new AliHLTPluginBase)
, fFlags(0)
, fProcessingStep(kProcessingStepUndefined)
{
//constructor
if (options) Init(options);
}
AliHLTReconstructor::~AliHLTReconstructor()
{
//destructor
if (fpEsdManager) AliHLTEsdManager::Delete(fpEsdManager);
fpEsdManager=NULL;
if (fpPluginBase) {
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
AliDebug(0, Form("terminate HLT system: status %#x", pSystem->GetStatusFlags()));
if (pSystem->CheckStatus(AliHLTSystem::kStarted)) {
// send specific 'event' to execute the stop sequence
pSystem->Reconstruct(0, NULL, NULL);
}
}
delete fpPluginBase;
}
fpPluginBase=NULL;
}
void AliHLTReconstructor::Init(const char* options)
{
// init the reconstructor
SetOption(options);
Init();
}
void AliHLTReconstructor::Init()
{
// init the reconstructor
if (!fpPluginBase) {
AliError("internal memory error: can not get AliHLTSystem instance from plugin");
return;
}
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (!pSystem) {
AliError("can not create AliHLTSystem object");
return;
}
if (pSystem->CheckStatus(AliHLTSystem::kError)) {
AliError("HLT system in error state");
return;
}
TString esdManagerOptions;
// the options scan has been moved to AliHLTSystem, the old code
// here is kept to be able to run an older version of the HLT code
// with newer AliRoot versions.
TString option = GetOption();
TObjArray* pTokens=option.Tokenize(" ");
option="";
if (pTokens) {
int iEntries=pTokens->GetEntries();
for (int i=0; i<iEntries; i++) {
TString token=(((TObjString*)pTokens->At(i))->GetString());
if (token.Contains("loglevel=")) {
TString param=token.ReplaceAll("loglevel=", "");
if (param.IsDigit()) {
pSystem->SetGlobalLoggingLevel((AliHLTComponentLogSeverity)param.Atoi());
} else if (param.BeginsWith("0x") &&
param.Replace(0,2,"",0).IsHex()) {
int severity=0;
sscanf(param.Data(),"%x", &severity);
pSystem->SetGlobalLoggingLevel((AliHLTComponentLogSeverity)severity);
} else {
AliWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
}
} else if (token.Contains("alilog=off")) {
pSystem->SwitchAliLog(0);
} else if (token.CompareTo("ignore-hltout")==0) {
fFlags|=kAliHLTReconstructorIgnoreHLTOUT;
if (option.Length()>0) option+=" ";
option+=token;
} else if (token.CompareTo("run-online-config")==0) {
fFlags|=kAliHLTReconstructorIgnoreHLTOUT;
if (option.Length()>0) option+=" ";
option+=token;
} else if (token.CompareTo("ignore-ctp")==0) {
fFlags|=kAliHLTReconstructorIgnoreCTP;
} else if (token.Contains("esdmanager=")) {
token.ReplaceAll("esdmanager=", "");
token.ReplaceAll(","," ");
token.ReplaceAll("'","");
esdManagerOptions=token;
} else {
if (option.Length()>0) option+=" ";
option+=token;
}
}
delete pTokens;
}
TString ecsParam;
TString ctpParam;
if ((fFlags&kAliHLTReconstructorIgnoreCTP)==0 &&
BuildCTPTriggerClassString(ctpParam)>=0) {
if (!ecsParam.IsNull()) ecsParam+=";";
ecsParam+="CTP_TRIGGER_CLASS=";
ecsParam+=ctpParam;
}
if (!ecsParam.IsNull()) {
option+=" ECS=";
option+=ecsParam;
}
if (!pSystem->CheckStatus(AliHLTSystem::kReady)) {
pSystem->SetDetectorMask(GetRunInfo()->GetDetectorMask());
if (pSystem->ScanOptions(option.Data())<0) {
AliError("error setting options for HLT system");
return;
}
if ((pSystem->Configure())<0) {
AliError("error during HLT system configuration");
return;
}
}
fpEsdManager=AliHLTEsdManager::New();
if (fpEsdManager) {
fpEsdManager->SetOption(esdManagerOptions.Data());
}
AliHLTMisc::Instance().InitStreamerInfos(fgkCalibStreamerInfoEntry);
}
void AliHLTReconstructor::Terminate()
{
/// overloaded from AliReconstructor: terminate event processing
// indicate step 'Terminate'
SetProcessingStep(kProcessingStepTerminate);
if (fpPluginBase) {
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
// 2012-04-02
// clean up the HLTOUT instance if still existing, currently FinishEvent
// is not called at the end of the event processing and the cleanup
// needs to be done here to avoid a warning message. Later it can be
// declared a malfunction if the HLTOUT instance is still existing at
// this point.
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT) {
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
AliDebug(0, Form("terminate HLT system: status %#x", pSystem->GetStatusFlags()));
if (pSystem->CheckStatus(AliHLTSystem::kStarted)) {
// send specific 'event' to execute the stop sequence
pSystem->Reconstruct(0, NULL, NULL);
}
}
}
}
void AliHLTReconstructor::FinishEvent()
{
/// overloaded from AliReconstructor: finish current event
if (!fpPluginBase) return;
// indicate step 'FinishEvent'
SetProcessingStep(kProcessingStepFinishEvent);
AliInfo("finishing event");
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
// this is the end of the lifetime of the HLTOUT instance
// called after all other modules have been reconstructed
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT) {
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
}
}
const char* AliHLTReconstructor::fgkCalibStreamerInfoEntry="HLT/Calib/StreamerInfo";
void AliHLTReconstructor::Reconstruct(AliRawReader* rawReader, TTree* /*clustersTree*/) const
{
// reconstruction of real data without writing of ESD
// For each event, HLT reconstruction chains can be executed and
// added to the existing HLTOUT data
// The HLTOUT data is finally processed in FillESD
if (!fpPluginBase) {
AliError("internal memory error: can not get AliHLTSystem instance from plugin");
return;
}
int iResult=0;
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT) {
// at this stage we always have a new event, regardless state of
// fProcessingStep; build the HLTOUT instance from scratch
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
// same for HLTInput
AliHLTOUT* pHLTInput=NULL;
pSystem->InvalidateHLTInput(&pHLTInput);
if (pHLTInput) {
pHLTInput->Reset();
delete pHLTInput;
pHLTInput=NULL;
}
if (pSystem->CheckStatus(AliHLTSystem::kError)) {
// this is the highest level where an error can be detected, no error
// codes can be returned
AliFatal("HLT system in error state");
return;
}
if (!pSystem->CheckStatus(AliHLTSystem::kReady)) {
AliError("HLT system in wrong state");
return;
}
// indicate the local reconstruction step
SetProcessingStep(kProcessingStepLocal);
// init the HLTOUT instance for the current event
// not nice. Have to query the global run loader to get the current event no.
Int_t eventNo=-1;
AliRunLoader* runloader = AliRunLoader::Instance();
if (runloader) {
eventNo=runloader->GetEventNumber();
}
if (eventNo>=0) {
AliRawReader* input=NULL;
if ((fFlags&kAliHLTReconstructorIgnoreHLTOUT) == 0 ) {
input=rawReader;
}
pHLTOUT=new AliHLTOUTRawReader(input, eventNo, fpEsdManager);
pHLTInput=new AliHLTOUTRawReader(rawReader);
if (pHLTOUT && pHLTInput) {
if (pHLTOUT->Init()>=0 && pHLTInput->Init()>=0) {
pSystem->InitHLTOUT(pHLTOUT);
pSystem->InitHLTInput(pHLTInput);
} else {
AliError("error : initialization of HLTOUT handler failed");
}
} else {
AliError("memory allocation failed: can not create AliHLTOUT object");
}
} else {
AliError("can not get event number");
}
if ((iResult=pSystem->Reconstruct(1, NULL, rawReader))>=0) {
}
pSystem->InvalidateHLTInput(&pHLTInput);
delete pHLTInput;
}
}
void AliHLTReconstructor::FillESD(AliRawReader* rawReader, TTree* /*clustersTree*/,
AliESDEvent* esd) const
{
// reconstruct real data and fill ESD
if (!rawReader || !esd) {
AliError("missing raw reader or esd object");
return;
}
if (!fpPluginBase) {
AliError("internal memory error: can not get AliHLTSystem instance from plugin");
return;
}
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
if (pSystem->CheckStatus(AliHLTSystem::kError)) {
// this is the highest level where an error can be detected, no error
// codes can be returned
AliFatal("HLT system in error state");
return;
}
if (!pSystem->CheckStatus(AliHLTSystem::kReady)) {
AliError("HLT system in wrong state");
return;
}
pSystem->FillESD(-1, NULL, esd);
// the HLTOUT handler has either been created in the AliHLTReconstructor::Reconstruct
// step of this event or is created now. In either case the instance is deleted after
// the processing
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT && fProcessingStep!=kProcessingStepLocal) {
// this is a new event, if local reconstruction would have been executed
// the HLTOUT instance would have been created for the current event already,
// in all other cases one has to create the HLTOUT instance here
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
if (!pHLTOUT) {
AliRawReader* input=NULL;
if ((fFlags&kAliHLTReconstructorIgnoreHLTOUT) == 0 ) {
input=rawReader;
}
pHLTOUT=new AliHLTOUTRawReader(input, esd->GetEventNumberInFile(), fpEsdManager);
}
// indicate step 'ESD filling'
SetProcessingStep(kProcessingStepESD);
if (pHLTOUT) {
ProcessHLTOUT(pHLTOUT, esd, (pSystem->GetGlobalLoggingLevel()&kHLTLogDebug)!=0);
// 2012-03-30: a change in the module sequence of AliReconstruction is soon
// going to be applied: HLT reconstruction is executed fully (i.e. both local
// reconstruction and FillESD) before all the other modules. In order to make the
// HLTOUT data available for other modules it is kept here and released in the method
// FinishEvent
pSystem->InitHLTOUT(pHLTOUT);
} else {
AliError("error creating HLTOUT handler");
}
}
}
void AliHLTReconstructor::Reconstruct(TTree* /*digitsTree*/, TTree* /*clustersTree*/) const
{
// reconstruct simulated data
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
// create the HLTOUT instance in order to be available for other detector reconstruction
// first cleanup any existing instance
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT) {
// at this stage we always have a new event, regardless state of
// fProcessingStep; build the HLTOUT instance from scratch
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
// indicate the local reconstruction step
SetProcessingStep(kProcessingStepLocal);
// not nice. Have to query the global run loader to get the current event no.
// This is related to the missing AliLoader for HLT.
// Since AliReconstruction can not provide a digits tree, the file needs to be accessed
// explicitely, and the corresponding event needs to be selected.
Int_t eventNo=-1;
AliRunLoader* runloader = AliRunLoader::Instance();
if (runloader) {
eventNo=runloader->GetEventNumber();
}
if (eventNo>=0) {
const char* digitfile=NULL;
if ((fFlags&kAliHLTReconstructorIgnoreHLTOUT) == 0 ) {
digitfile="HLT.Digits.root";
}
pHLTOUT=new AliHLTOUTDigitReader(eventNo, fpEsdManager, digitfile);
if (pHLTOUT) {
if (pHLTOUT->Init()>=0) {
pSystem->InitHLTOUT(pHLTOUT);
} else {
AliError("error : initialization of HLTOUT handler failed");
}
} else {
AliError("memory allocation failed: can not create AliHLTOUT object");
}
} else {
AliError("can not get event number");
}
// all data processing happens in FillESD
}
}
void AliHLTReconstructor::FillESD(TTree* /*digitsTree*/, TTree* /*clustersTree*/, AliESDEvent* esd) const
{
// reconstruct simulated data and fill ESD
// later this is the place to extract the simulated HLT data
// for now it's only an user failure condition as he tries to run HLT reconstruction
// on simulated data
TString option = GetOption();
if (!option.IsNull() &&
(option.Contains("config=") || option.Contains("chains="))) {
AliWarning(Form("You are trying to run a custom HLT chain on digits data.\n\n"
"HLT reconstruction can be run embedded into AliReconstruction from\n"
"raw data (real or simulated)). Reconstruction of digit data takes\n"
"place in AliSimulation, appropriate input conversion is needed to\n"
"feed data from the detector digits into the HLT chain.\n"
"Consider running embedded into AliSimulation.\n"
" /*** run macro *****************************************/\n"
" AliSimulation sim;\n"
" sim.SetRunHLT(\"%s\");\n"
" sim.SetRunGeneration(kFALSE);\n"
" sim.SetMakeDigits(\"\");\n"
" sim.SetMakeSDigits(\"\");\n"
" sim.SetMakeDigitsFromHits(\"\");\n"
" sim.Run();\n"
" /*********************************************************/\n\n",
option.Data()));
}
if (!fpPluginBase) {
AliError("internal memory error: can not get AliHLTSystem instance from plugin");
return;
}
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (pSystem) {
if (pSystem->CheckStatus(AliHLTSystem::kError)) {
// this is the highest level where an error can be detected, no error
// codes can be returned
AliFatal("HLT system in error state");
return;
}
if (!pSystem->CheckStatus(AliHLTSystem::kReady)) {
AliError("HLT system in wrong state");
return;
}
// the HLTOUT handler has either been created in the AliHLTReconstructor::Reconstruct
// step of this event or is created now. In either case the instance is deleted after
// the processing
AliHLTOUT* pHLTOUT=NULL;
pSystem->InvalidateHLTOUT(&pHLTOUT);
if (pHLTOUT && fProcessingStep!=kProcessingStepLocal) {
// this is a new event, if local reconstruction would have been executed
// the HLTOUT instance would have been created for the current event already,
// in all other cases one has to create the HLTOUT instance here
pHLTOUT->Reset();
delete pHLTOUT;
pHLTOUT=NULL;
}
if (!pHLTOUT) {
const char* digitfile=NULL;
if ((fFlags&kAliHLTReconstructorIgnoreHLTOUT) == 0 ) {
digitfile="HLT.Digits.root";
}
pHLTOUT=new AliHLTOUTDigitReader(esd->GetEventNumberInFile(), fpEsdManager, digitfile);
}
// indicate step 'ESD filling'
SetProcessingStep(kProcessingStepESD);
if (pHLTOUT) {
ProcessHLTOUT(pHLTOUT, esd, (pSystem->GetGlobalLoggingLevel()&kHLTLogDebug)!=0);
// 2012-03-30: a change in the module sequence of AliReconstruction is soon
// going to be applied: HLT reconstruction is executed fully (i.e. both local
// reconstruction and FillESD) before all the other modules. In order to make the
// HLTOUT data available for other modules it is kept here and released in the method
// FinishEvent
pSystem->InitHLTOUT(pHLTOUT);
} else {
AliError("error creating HLTOUT handler");
}
}
}
void AliHLTReconstructor::ProcessHLTOUT(AliHLTOUT* pHLTOUT, AliESDEvent* esd, bool bVerbose) const
{
// treatment of simulated or real HLTOUT data
if (!pHLTOUT) return;
if (!fpPluginBase) {
AliError("internal memory error: can not get AliHLTSystem instance from plugin");
return;
}
AliHLTSystem* pSystem=fpPluginBase->GetInstance();
if (!pSystem) {
AliError("error getting HLT system instance");
return;
}
if (pHLTOUT->Init()<0) {
AliError("error : initialization of HLTOUT handler failed");
return;
}
if (bVerbose)
PrintHLTOUTContent(pHLTOUT);
int blockindex=pHLTOUT->SelectFirstDataBlock(kAliHLTDataTypeStreamerInfo);
if (blockindex>=0) {
const AliHLTUInt8_t* pBuffer=NULL;
AliHLTUInt32_t size=0;
if (pHLTOUT->GetDataBuffer(pBuffer, size)>=0) {
TObject* pObject=AliHLTMessage::Extract(pBuffer, size);
if (pObject) {
TObjArray* pArray=dynamic_cast<TObjArray*>(pObject);
if (pArray) {
AliHLTMisc::Instance().InitStreamerInfos(pArray);
} else {
AliError(Form("wrong class type of streamer info list: expected TObjArray, but object is of type %s", pObject->Class()->GetName()));
}
} else {
AliError(Form("failed to extract object from data block of type %s", AliHLTComponent::DataType2Text(kAliHLTDataTypeStreamerInfo).c_str()));
}
} else {
AliError(Form("failed to get data buffer for block of type %s", AliHLTComponent::DataType2Text(kAliHLTDataTypeStreamerInfo).c_str()));
}
}
if (pSystem->ProcessHLTOUT(pHLTOUT, esd)<0) {
AliError("error processing HLTOUT");
}
if (bVerbose && esd) {
AliInfo("HLT ESD content:");
esd->Print();
}
}
void AliHLTReconstructor::ProcessHLTOUT(const char* digitFile, AliESDEvent* pEsd) const
{
// debugging/helper function to examine simulated data
if (!digitFile) return;
// read the number of events
TFile f(digitFile);
if (f.IsZombie()) return;
TTree* pTree=NULL;
f.GetObject("rawhltout", pTree);
if (!pTree) {
AliWarning(Form("can not find tree rawhltout in file %s", digitFile));
return ;
}
int nofEvents=pTree->GetEntries();
f.Close();
//delete pTree; OF COURSE NOT! its an object in the file
pTree=NULL;
for (int event=0; event<nofEvents; event++) {
AliHLTOUTDigitReader* pHLTOUT=new AliHLTOUTDigitReader(event, fpEsdManager, digitFile);
if (pHLTOUT) {
AliInfo(Form("event %d", event));
ProcessHLTOUT(pHLTOUT, pEsd, true);
delete pHLTOUT;
} else {
AliError("error creating HLTOUT handler");
}
}
}
void AliHLTReconstructor::ProcessHLTOUT(AliRawReader* pRawReader, AliESDEvent* pEsd) const
{
// debugging/helper function to examine simulated or real HLTOUT data
if (!pRawReader) return;
pRawReader->RewindEvents();
for (int event=0; pRawReader->NextEvent(); event++) {
AliHLTOUTRawReader* pHLTOUT=new AliHLTOUTRawReader(pRawReader, event, fpEsdManager);
if (pHLTOUT) {
AliInfo(Form("event %d", event));
// the two event fields contain: period - orbit - bunch crossing counter
// id[0] id[1]
// |32 0|32 0|
//
// | 28 bit | 24 bit | 12|
// period orbit bcc
AliHLTUInt64_t eventId=0;
const UInt_t* rawreaderEventId=pRawReader->GetEventId();
if (rawreaderEventId) {
eventId=rawreaderEventId[0];
eventId=eventId<<32;
eventId|=rawreaderEventId[1];
}
AliInfo(Form("Event Id from rawreader:\t 0x%016llx", eventId));
ProcessHLTOUT(pHLTOUT, pEsd, true);
delete pHLTOUT;
} else {
AliError("error creating HLTOUT handler");
}
}
}
void AliHLTReconstructor::PrintHLTOUTContent(AliHLTOUT* pHLTOUT) const
{
// print the block specifications of the HLTOUT data blocks
if (!pHLTOUT) return;
int iResult=0;
AliInfo(Form("Event Id from hltout:\t 0x%016llx", pHLTOUT->EventId()));
for (iResult=pHLTOUT->SelectFirstDataBlock();
iResult>=0;
iResult=pHLTOUT->SelectNextDataBlock()) {
AliHLTComponentDataType dt=kAliHLTVoidDataType;
AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
pHLTOUT->GetDataBlockDescription(dt, spec);
const AliHLTUInt8_t* pBuffer=NULL;
AliHLTUInt32_t size=0;
if (pHLTOUT->GetDataBuffer(pBuffer, size)>=0) {
pHLTOUT->ReleaseDataBuffer(pBuffer);
pBuffer=NULL; // just a dummy
}
AliInfo(Form(" %s 0x%x: size %d", AliHLTComponent::DataType2Text(dt).c_str(), spec, size));
}
}
int AliHLTReconstructor::BuildCTPTriggerClassString(TString& triggerclasses) const
{
// build the CTP trigger class string from the OCDB entry of the CTP trigger
int iResult=0;
triggerclasses.Clear();
AliCentralTrigger* pCTP = new AliCentralTrigger();
AliTriggerConfiguration *config=NULL;
TString configstr("");
if (pCTP->LoadConfiguration(configstr) &&
(config = pCTP->GetConfiguration())!=NULL) {
const TObjArray& classesArray = config->GetClasses();
int nclasses = classesArray.GetEntriesFast();
for( int iclass=0; iclass < nclasses; iclass++ ) {
AliTriggerClass* trclass = NULL;
if (classesArray.At(iclass) && (trclass=dynamic_cast<AliTriggerClass*>(classesArray.At(iclass)))!=NULL) {
TString entry;
//trigger classes in the OCDB start at offset 1, not zero we need to subtract 1 when constructing
//the ECS param string, this is done also in offline: Bool_t AliReconstruction::GetEventInfo()
int trindex = trclass->GetIndex()-1;
entry.Form("%02d:%s:", trindex, trclass->GetName());
AliTriggerCluster* cluster=NULL;
TObject* clusterobj=config->GetClusters().FindObject(trclass->GetCluster());
if (clusterobj && (cluster=dynamic_cast<AliTriggerCluster*>(clusterobj))!=NULL) {
TString detectors=cluster->GetDetectorsInCluster();
TObjArray* pTokens=detectors.Tokenize(" ");
if (pTokens) {
for (int dix=0; dix<pTokens->GetEntriesFast(); dix++) {
int id=AliDAQ::DetectorID(((TObjString*)pTokens->At(dix))->GetString());
if (id>=0) {
TString detstr; detstr.Form("%s%02d", dix>0?"-":"", id);
entry+=detstr;
} else {
AliError(Form("invalid detector name extracted from trigger cluster: %s (%s)", ((TObjString*)pTokens->At(dix))->GetString().Data(), detectors.Data()));
iResult=-EPROTO;
break;
}
}
delete pTokens;
}
} else {
AliError(Form("can not find trigger cluster %s in config", trclass->GetCluster()?trclass->GetCluster()->GetName():"NULL"));
iResult=-EPROTO;
break;
}
if (!triggerclasses.IsNull()) triggerclasses+=",";
triggerclasses+=entry;
}
}
}
return iResult;
}
| 33.28877 | 153 | 0.665382 | AllaMaevskaya |
c708e2b93a53b622e19300cfca92e27d809255e6 | 444 | cpp | C++ | Binary Search/One Edit Distance/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | BinarySearch/One Edit Distance/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | BinarySearch/One Edit Distance/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | bool solve(string s, string t) {
int n = s.size(), m = t.size(), i = 0, j = 0, cnt = 0;
if (s == t) {
return true;
}
if (abs(n - m) > 1) {
return false;
}
while (i < n && j < m) {
if (s[i] != t[j]) {
if (cnt == 1) {
return false;
}
if (n > m) {
i++;
} else if (n < m) {
j++;
} else {
i++;
j++;
}
cnt++;
} else {
i++;
j++;
}
}
if (i < n || j < m) {
cnt++;
}
return cnt == 1;
} | 13.875 | 55 | 0.358108 | Code-With-Aagam |
c70a9df84f1952447eed3793fae3fd481fded60d | 25,913 | cpp | C++ | sbg/src/rmsd/rmsd.cpp | chaconlab/korpm | 5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3 | [
"MIT"
] | 1 | 2022-01-02T01:48:05.000Z | 2022-01-02T01:48:05.000Z | sbg/src/rmsd/rmsd.cpp | chaconlab/korpm | 5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3 | [
"MIT"
] | 1 | 2021-11-10T10:50:08.000Z | 2021-11-10T10:50:08.000Z | sbg/src/rmsd/rmsd.cpp | chaconlab/korpm | 5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3 | [
"MIT"
] | 1 | 2021-12-03T03:29:39.000Z | 2021-12-03T03:29:39.000Z |
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <libpdb/include/Macromolecule.h>
#include <libpdb/include/pdbIter.h>
#include <libtools/include/timer.h>
#include <libtools/include/Io.h>
#include <libpdb/include/SS_DISICL.h>
#include <cmdl/CmdLine.h>
using namespace TCLAP;
// Compute the RMSD between two arrays
float atomic_rmsd(float *array, float *array2, int natoms);
// Computes the Gaussian weights profile from inter-atomic distances between "mol" and "mol2"
// allocating profile memory if (*p_profile==NULL).
// Weights are computed according to ec.(7) from: w= exp(-(d^2)/c ) --> c=5A (for big motions)
// Damm & Carlson. "Gaussian-Weighted RMSD Superposition of Proteins: A Structural
// Comparison for Flexible Proteins and Predicted Protein Structures".
// Biophysical Journal. Volume 90, Issue 12, 15 June 2006, Pages 4558-4573
//void gaussian_weight(Macromolecule *mol, Macromolecule *mol2, double **p_profile, double c=5.0);
int main(int argc, char *argv[])
{
CmdLine cmd(argv[0]," ", "1.07" );
char file_ref[500]; // pdb input reference
char file_mob[500]; // pdb input
char file_out[500]; // pdb output
char file_aln[500]; // Sequence alignment file name
char file_sim[500]; // Similarity file name
char tmp_path[500]; // Temporary path
char dist_profiles[] = "dist_profiles.txt";
float matrix4[4][4];
std::string temp;
int aln_level = 2; // Clustal alignment level (1, 2 or 3 to match *, *: or *:. ,respectively)
bool *maskres,*maskres2;
bool *maskmol=NULL, *maskmol2=NULL;
int nmatch,nali1,nali2;
double *prof=NULL; // Distance profile before alignment
double *prof2=NULL; // Distance profile after alignment
Chain *ch; // Mon(7/1/2016): See below...
bool sim_binary = true; // Set true to dump a binary similarity matrix (non-redundant), otherwise plain text format used.
// Reset transformation matrix
for(int i=0; i < 4; i++)
for(int j=0; j < 4; j++)
matrix4[i][j]=0;
try {
//
// Define required arguments no labeled
//
UnlabeledValueArg<std::string> pdb_ref("ref_pdb","Reference PDB file","default","pdb");
cmd.add( pdb_ref );
UnlabeledValueArg<std::string> pdb_mob("mob_pdb","Mobile PDB file (if Multi-PDB, Model index and initial and aligned RMSDs will be dumped.)","default","pdb");
cmd.add( pdb_mob );
// optional arguments
SwitchArg Dist("","dist", "Compute the inter-residue distance profiles (averaged over residue atoms) before and after alignment: dist_profiles.txt", false);
cmd.add( Dist );
ValueArg<int> AlnLevel("","aln_level", "Clustal alignment level (1, 2 or 3 to match *, *: or *:. ,respectively) (default=2)",false,2,"int");
cmd.add( AlnLevel );
ValueArg<std::string> AlnFile("a","aln_file", "Clustal's \".aln\" file defining alignment between initial and target atomic structures.\n",false,"alnstring","string");
cmd.add( AlnFile );
ValueArg<double> gauss_c("C","gauss_c", "Gaussian width (default=20)",false,20.0,"double");
cmd.add( gauss_c );
SwitchArg gauss("g","gauss", "Gaussian-weighted RMSD superposition", false);
cmd.add( gauss );
SwitchArg RemoveH("", "noH","Removing Hydrogen atoms from output files and computations.", false);
cmd.add( RemoveH );
SwitchArg BBone("b","bb", "only BackBone atoms (N,CA,C,O) in proteins", false);
cmd.add( BBone );
SwitchArg CAlpha("c","calpha", "only C alpha in proteins or P in nucleic acids", false);
cmd.add( CAlpha );
SwitchArg sim_text("","sim_text", "Force plain text format for similarity matrix output.", false);
cmd.add( sim_text );
ValueArg<std::string> sim_matrix("s","similarity","Compute the similarity matrix (RMSD). Only for Multi-PDB input.",false,"","string");
cmd.add(sim_matrix);
ValueArg<std::string> pdb_moved("o","output","output pdb file (mobile onto reference)",false,"","string");
cmd.add(pdb_moved);
ValueArg<int> Start("","start","N-terminal loop residue index, first mobile residue (PDB residue index). (default=disabled)",false,-1,"int");
cmd.add( Start );
ValueArg<int> End("","end","C-terminal loop residue index, last mobile residue (PDB residue index). (default=disabled)",false,-1,"int");
cmd.add( End );
ValueArg<char> Chain("","chain", "Chain ID (default=first chain of reference PDB)",false,1,"int");
cmd.add( Chain );
ValueArg<int> NFlanks("","flanks", "Number of loop flanking residues. E.g. \"2\" means two flanking residues at Nt and other two at Ct, \"0\" means disabled (default=0).",false,0,"int");
cmd.add( NFlanks );
ValueArg<int> ResOffset("","res_offset", "Residue index offset from both ends. Typically used to discard anchors (fixed) in Multi-PDB loops file. (default=0)",false,0,"int");
cmd.add( ResOffset );
SwitchArg save_rmsd("r","save_rmsd", " Save rmsd & dihedrals",false);
cmd.add( save_rmsd );
// Parse the command line.
cmd.parse(argc,argv);
init_aminoacids(Rosseta,pdb);
// reading pdb
Macromolecule *mol=new Macromolecule("pdb");
Macromolecule *mol2=new Macromolecule("pdb2");
Macromolecule *mol_ca;
Macromolecule *mol2_ca;
// stupid transformation from string to char
strcpy(file_ref,((temp=pdb_ref.getValue()).c_str()));
strcpy(file_mob,((temp=pdb_mob.getValue()).c_str()));
mol->readPDB(file_ref);
mol2->readPDB(file_mob);
// Removing Hydrogens
if(RemoveH.isSet())
{
mol->delete_hydrogens(); // Remove Hydrogens
mol2->delete_hydrogens(); // Remove Hydrogens
// printf( ">> Hydrogens were removed.\n" );
}
pdbIter *iter_molec;
iter_molec = new pdbIter(mol2);
int nmol = iter_molec->num_molecule();
delete(iter_molec);
int ri = Start.getValue(); // All residues by default
int rf = End.getValue(); // All residues by default
int ichain = -1; // All chains by default
char chain; // Chain ID
Condition *firstmolec; // First molecule conditions
firstmolec = new Condition(0,0,-1,-1,-1,-1,-1,-1,-1,-1); // First loop selection
Conditions *firstmolec2= new Conditions();
firstmolec2->add(firstmolec);
Macromolecule *molec0;
molec0 = mol2->select_cpy(firstmolec2);
iter_molec = new pdbIter(molec0);
// Get loop limits and chain id from first model in Multi-PDB (Mobile)
if(nmol > 1 && (ri < 0 || rf < 0))
{
iter_molec->pos_chain=0;
ch = iter_molec->get_chain();
pdbIter *iter_chain = new pdbIter(ch);
if(ri < 0)
{
iter_chain->pos_fragment=0;
ri = (iter_chain->get_fragment())->getIdNumber(); // get Nt anchor residue number (PDB)
}
if(rf < 0)
{
iter_chain->pos_fragment=iter_chain->num_fragment()-1;
rf = (iter_chain->get_fragment())->getIdNumber(); // get Ct anchor residue number (PDB), i.e. the last that moves...
}
}
// Chain *ch; // Mon(7/1/2016): Compilers (intel and gcc) say this is not declared within scope... WTF???
iter_molec->pos_chain = 0;
ch = iter_molec->get_chain();
chain = ch->getName()[0];
delete iter_molec;
// // Apply the selected number of residues offset (0 by default)
// ri += ResOffset.getValue();
// rf -= ResOffset.getValue();
// fprintf(stderr, "> Considered chain \"%c\" goes from residue %d (Nt) to %d (Ct), including an index offset of %d.\n", chain, ri, rf, ResOffset.getValue() );
// Number of loop flanking residues (e.g. "2" means two flanking residues at Nt, and other two at Ct)
int nflanks = NFlanks.getValue();
if(nflanks <= 0) // No-flanks stuff...
{
// Apply the selected number of residues offset (0 by default)
ri += ResOffset.getValue();
rf -= ResOffset.getValue();
fprintf(stderr, "> Considered chain \"%c\" goes from residue %d (Nt) to %d (Ct), including an index offset of %d.\n", chain, ri, rf, ResOffset.getValue() );
}
// Get chain index (internal) for Reference PDB
pdbIter *iter_mol = new pdbIter(mol);
for( iter_mol->pos_chain = 0; !iter_mol->gend_chain(); iter_mol->next_chain() ) // screen chains
{
ch=iter_mol->get_chain();
if(ch->getName()[0] == chain)
{
ichain = iter_mol->pos_chain; // chain internal index
break;
}
}
delete iter_mol;
if(ichain < 0) // Some checking...
{
fprintf(stderr,"> Sorry, chain \"%c\" not found in %s (reference PDB)! Using all chains!\n",chain,file_ref);
//exit(1);
}
// Note: chain index "0" is assumed for Mobile PDB
// Atomic selection Conditions
Condition *calpha= new Condition(-1,-1,-1,-1,ichain,ichain,ri,rf,-1,-1);
// Condition *calpha= new Condition(-1,-1,ichain,ichain,-1,-1,ri,rf,-1,-1); // Mon (9/4/2018): Bug, we must select by chain, not segment.
// MON: Check above lines !!! Rare....
Condition *calphaX= new Condition(-1,-1,-1,-1,-1,-1,ri,rf,-1,-1); // Selection for mobile Multi-PDB
// Condition *calphaX= new Condition(-1,-1,ichain,ichain,-1,-1,-1,-1,-1,-1); // Selection for mobile Multi-PDB
// mobile = new Condition(-1,-1,-1,-1,-1,-1,ri+1,rf-1,-1,-1); // get residues from Nt+1 to Ct-1, i.e. only those mobile...
if( CAlpha.isSet() )
{
calpha->add(" CA ");
calpha->add(" P ");
}
if( BBone.isSet() )
{
calpha->add(" N ");
calpha->add(" CA ");
calpha->add(" C ");
calpha->add(" O ");
}
Conditions *calpha2= new Conditions();
calpha2->add(calpha);
if( CAlpha.isSet() )
{
calphaX->add(" CA ");
calphaX->add(" P ");
}
if( BBone.isSet() )
{
calphaX->add(" N ");
calphaX->add(" CA ");
calphaX->add(" C ");
calphaX->add(" O ");
}
Conditions *calpha2X= new Conditions();
calpha2X->add(calphaX);
// Compute RMSDs between some loop in the reference PDB and all the loops in the mobile Multi-PDB
// if(nmol > 1 || ri >= 0 || rf >= 0) // If mobile Multi-PDB found
if(nmol > 1) // If mobile Multi-PDB found
{
printf( "# %d models found in input mobile Multi-PDB: %s\n", nmol, file_mob);
// Select relevant atoms
mol_ca = mol->select(calpha2);
mol2_ca = mol2->select(calpha2X);
// Copy trimmed reference Macromolecule (just mobile loop region) to load decoys coordinates later
Macromolecule *mol2_decoy = new Macromolecule(mol_ca);
// }
// else
// {
// fprintf(stderr,"%d missing atoms in mol\n",mol->format_residues(false,2));
// fprintf(stderr,"%d missing atoms in mol2\n",mol2->format_residues(false,2));
// mol_ca = mol;
// mol2_ca = mol2;
// }
int natom = mol_ca->get_num_atoms(); // Get number of atoms in reference loop
int natom2 = mol2_ca->get_num_atoms(); // Get number of atoms in mobile loops
// fprintf(stderr,"natom= %d natom2= %d\n",natom,natom2);
if(natom2 % nmol != 0) // Some checking
{
fprintf(stderr,"Error, different number of atoms between reference PDB and mobile Multi-PDB (natom2= %d, nmol= %d). Forcing exit!\n", natom2, nmol);
exit(2);
}
fprintf(stderr,"natom= %d natom2= %d ichain= %d\n",natom,natom2,ichain);
float *coord;
float *coord2;
mol_ca->coordMatrix( &coord );
mol2_ca->coordMatrix( &coord2 );
for(int i = 0; i < nmol; i++) // Screen all molecules
{
// Set current loop coordinates into dummy loop Macromolecule
mol2_decoy->coordMatrixSet( coord2 + i * natom * 3 );
// Compute the RMSD between two arrays
fprintf(stdout,"%6d %f %f\n",i+1, mol_ca->rmsd(mol2_decoy), mol_ca->minRmsd(mol2_decoy,matrix4) );
// OLD suff...
// fprintf(stdout,"%6d %f\n",i+1, atomic_rmsd(coord, coord2 + i * natom * 3, natom) );
}
// Computing similarity matrix based on RMSD
if(sim_matrix.isSet())
{
// Get similarity file name from parser
strcpy( file_sim,( (temp = sim_matrix.getValue()).c_str() ) );
FILE *f_sim; // Output similarity file handler
fprintf(stdout,"rmsd> Writing similarity CC-RMSD into file %s\n",file_sim);
float simil; // Similarity
int cont = 0;
if( !sim_text.isSet() ) // binary
{
f_sim = fopen(file_sim,"wb");
fwrite(&nmol,sizeof(int),1,f_sim); // Store the total number of loops
// Computing similarity CC-RMSD
for(int i=0; i<nmol; i++)
for(int j=i+1; j<nmol; j++)
{
simil = atomic_rmsd(coord2 + i * natom * 3, coord2 + j * natom * 3, natom);
fwrite(&simil,sizeof(float),1,f_sim); // Dump similarity into file
cont++;
}
}
else // plain-text
{
f_sim = fopen(file_sim,"w");
fprintf(f_sim,"# <i> <j> <similarity> (indices begin from 1)\n"); // Matlab request (i begins in value 1)
// Computing similarity CC-RMSD
for(int i=0; i<nmol; i++)
for(int j=i+1; j<nmol; j++)
{
simil = atomic_rmsd(coord2 + i * natom * 3, coord2 + j * natom * 3, natom);
fprintf(f_sim,"%5d %5d %10f\n",i+1,j+1,simil); // Matlab request (i begins in value 1)
cont++;
}
}
fclose(f_sim);
fprintf(stdout,"rmsd> %d RMSD values written. (cont= %d)\n", nmol*(nmol-1)/2, cont);
}
delete mol2_decoy;
exit(0);
}
// Single loop alignment (in no flanks stuff requested)
if( nflanks <= 0 && (ri >= 0 || rf >= 0) )
{
// Select relevant atoms
mol_ca = mol->select(calpha2);
mol2_ca = mol2->select(calpha2X);
printf("rmsd> Initial_RMSD: %8f", mol_ca->rmsd(mol2_ca));
printf(" Aligned_RMSD: %8f\n", mol_ca->minRmsd(mol2_ca,matrix4));
if(pdb_moved.isSet())
{
M4Rot *matrix4_op=new M4Rot(matrix4);
mol2_ca->applyAtoms(matrix4_op); // superpose full-atom
delete matrix4_op;
strcpy(file_out,((temp=pdb_moved.getValue()).c_str()));
mol2_ca->writePDB(file_out);
printf(">> Saved in %s\n", file_out);
}
exit(0);
}
// Flanks rigid body alignment using Kabsch & Sander stuff...
if(nflanks > 0) // Flanks
{
// Select relevant atoms (the whole chain)
mol_ca = mol->select(calpha2);
mol2_ca = mol2->select(calpha2X);
// Condition(s) to select flanks
Conditions *cflank= new Conditions();
Condition *cflankN = new Condition(-1,-1,-1,-1,ichain,ichain,ri-nflanks,ri-1,-1,-1);
Condition *cflankC = new Condition(-1,-1,-1,-1,ichain,ichain,rf+1,rf+nflanks,-1,-1);
cflankN->add(" N ");
cflankN->add(" CA ");
cflankN->add(" C ");
cflankC->add(" N ");
cflankC->add(" CA ");
cflankC->add(" C ");
cflank->add(cflankN);
cflank->add(cflankC);
// Select relevant atoms (the whole chain)
Macromolecule *mol_flanks = mol->select(cflank);
mol_flanks->writePDB("mol_flanks.pdb");
Conditions *cflank2= new Conditions();
Condition *cflankN2 = new Condition(-1,-1,-1,-1,ichain,ichain,ri-nflanks,ri-1,-1,-1);
Condition *cflankC2 = new Condition(-1,-1,-1,-1,ichain,ichain,rf+1,rf+nflanks,-1,-1);
cflankN2->add(" N ");
cflankN2->add(" CA ");
cflankN2->add(" C ");
cflankC2->add(" N ");
cflankC2->add(" CA ");
cflankC2->add(" C ");
cflank2->add(cflankN2);
cflank2->add(cflankC2);
Macromolecule *mol2_flanks = mol2->select(cflank2);
mol2_flanks->writePDB("mol2_flanks.pdb");
// Compute transformation of target PDB and RMSD evaluation
float matrix4[4][4];
float flank_rmsd = mol_flanks->rmsd(mol2_flanks); // Compute un-aligned RMSD
float flank_rmsd_min = mol_flanks->minRmsd(mol2_flanks, matrix4); // Compute aligned RMSD
printf("rmsd> Flanks RMSD: Initial= %8f Aligned= %8f (%d residues per flank)\n", flank_rmsd, flank_rmsd_min, nflanks);
if(pdb_moved.isSet())
{
// Alignment of target PDB (minRMSD) (computed with flanks selection, but applied to full model)
M4Rot *matrix4_op = new M4Rot(matrix4);
mol2->applyAtoms(matrix4_op); // superpose
delete matrix4_op;
strcpy(file_out,((temp=pdb_moved.getValue()).c_str()));
mol2->writePDB(file_out);
printf("rmsd> Complete mobile PDB was aligned to flanks into %s\n", file_out);
}
mol2->writePDB("aliflanks.pdb");
delete mol_ca;
delete mol2_ca;
delete mol_flanks;
delete mol2_flanks;
exit(0);
}
if(AlnFile.isSet())
{
strcpy(file_aln,((temp=AlnFile.getValue()).c_str())); // Gets Alignment file name
aln_level = AlnLevel.getValue();
printf( "%s> Reading Clustal's sequence alignment from: %s\n","",file_aln);
read_aln(file_aln, &maskres, &nali1, &maskres2, &nali2, &nmatch, aln_level);
printf( "%s> %d residues matched! nali1= %d nali2= %d\n","",nmatch,nali1,nali2);
}
// only selection is considered
float rmsd_i,rmsd_f;
if( CAlpha.isSet() || BBone.isSet() )
{
// if CA / BB selection
mol_ca=mol->select(calpha2);
mol2_ca=mol2->select(calpha2);
// mol->writePDB("mymol.pdb");
// mol_ca->writePDB("mymolca.pdb");
// mol2->writePDB("mymol2.pdb");
// mol2_ca->writePDB("mymol2ca.pdb");
if(AlnFile.isSet())
{
maskmol = mol_ca->maskres2maskatom(maskres);
maskmol2 = mol2_ca->maskres2maskatom(maskres2);
if(save_rmsd.isSet())
{ printf("> Saving initial.rmsd\n");
rmsd_i = mol_ca->rmsd_file(mol2_ca,maskmol,maskmol2, "initial.rmsd");
}
rmsd_i = mol_ca->rmsd(mol2_ca,maskmol,maskmol2);
// here save dihedral....
}
else
rmsd_i = mol_ca->rmsd(mol2_ca);
// fprintf(stderr,"ichain=%d ri=%d rf=%d maskmol %d:\n", ichain, ri, rf, mol_ca->get_num_atoms());
// for(int x=0; x<mol_ca->get_num_atoms(); x++)
// fprintf(stderr," %1d",maskmol[x]);
// fprintf(stderr,"\n");
if(pdb_moved.isSet() || gauss.isSet())
if(AlnFile.isSet())
rmsd_f = mol_ca->minRmsd(mol2_ca,matrix4,maskmol,maskmol2);
else
rmsd_f = mol_ca->minRmsd(mol2_ca,matrix4);
else
if(AlnFile.isSet())
{
// rmsd_f = mol_ca->minRmsd(mol2_ca,maskmol,maskmol2);
// fprintf(stderr,"Not implemented yet!\n");
// exit(0);
rmsd_f = mol_ca->minRmsd(mol2_ca,matrix4,maskmol,maskmol2); // A different function (without matrix4 computation) should be made...
}
else
rmsd_f = mol_ca->minRmsd(mol2_ca);
}
else // All atoms
{
if(AlnFile.isSet())
{
maskmol = mol->maskres2maskatom(maskres);
maskmol2 = mol2->maskres2maskatom(maskres2);
if(save_rmsd.isSet())
{
printf("> Saving initial.rmsd\n");
rmsd_i = mol->rmsd_file(mol2,maskmol,maskmol2,"initial.rmsd");
}
rmsd_i = mol->rmsd(mol2,maskmol,maskmol2);
if(save_rmsd.isSet())
{
// output dihedrals && SS
//
float *di, *di2;
int *ss, *ss2, dangi, dangi2;
Fragment * res, *res2;
int resn, Nres,Nres2, simple, simple2;
Segment * seg;
int chino;
float * chis;
pdbIter *iter1, *iter2;
iter1 = new pdbIter( mol, false, false, true, false); // r maskres2
iter2 = new pdbIter( mol2, false, false, true, false ); // t maskres1
// first SS assign
mol->all_dihedrals( &di);
mol2->all_dihedrals( &di2);
dihedrals2DISICL( di, &ss, (iter1->num_fragment()) );
dihedrals2DISICL( di2, &ss2, (iter2->num_fragment()) );
FILE *f_out=NULL;
fprintf(stdout,">Saving initial.di\n");
if( !(f_out = fopen("initial.di","w")) )
{
fprintf(stderr,"Sorry, unable to write output file! Forcing exit!\n");
exit(2);
}
fprintf(f_out, "# AA resn PHI PSI OMEGA DISICL simple chi1 chi2 chi3 chi4\n");
iter2->pos_fragment = 0;
dangi=0;
Nres=0;
Nres2=0;
for ( iter1->pos_fragment = 0; !iter1->gend_fragment(); iter1->next_fragment() )
{
res = ( Fragment * ) iter1->get_fragment();
if(maskres[iter1->pos_fragment])
{
while(!iter2->gend_fragment() && !maskres2[iter2->pos_fragment])
{// this places the index into the corresponding pas
iter2->next_fragment();
}
Nres=iter1->pos_fragment;
Nres2=iter2->pos_fragment;
dangi=Nres*7;
dangi2=Nres2*7;
res2 = ( Fragment * ) iter1->get_fragment();
simple=DISICL_d2simple[ss[Nres]]; // change DISICL simple SS classes
simple2=DISICL_d2simple[ss2[Nres2]]; // change DISICL simple SS classes
fprintf( f_out, "%3s %8d %8.3f %8.3f %8.3f %3d %3s %3d %3s %8.3f %8.3f %8.3f %8.3f %3s %8d %8.3f %8.3f %8.3f %3d %3s %3d %3s %8.3f %8.3f %8.3f %8.3f\n",
res->getName(), res->getIdNumber(),
di[dangi], di[dangi+1], di[dangi+2], // (phi,psi,omega)
ss[Nres],DISICL_d[ss[Nres]], simple, DISICL_s[simple],
di[dangi+3], di[dangi+4], di[dangi+5], di[dangi+6], // (4x Chi)
res2->getName(), res2->getIdNumber(),
di2[dangi], di2[dangi+1], di2[dangi+2], // (phi,psi,omega)
ss2[Nres],DISICL_d[ss2[Nres2]], simple2, DISICL_s[simple2],
di2[dangi2+3], di2[dangi2+4], di2[dangi2+5], di2[dangi2+6] // (4x Chi)
);
iter2->next_fragment();
}
}
iter1->~pdbIter();
iter2->~pdbIter();
fclose(f_out);
}
}
else
rmsd_i = mol->rmsd(mol2);
if (pdb_moved.isSet() || gauss.isSet())
if(AlnFile.isSet())
rmsd_f = mol->minRmsd(mol2,matrix4,maskmol,maskmol2);
else
rmsd_f = mol->minRmsd(mol2,matrix4);
else
if(AlnFile.isSet())
{
// rmsd_f = mol_ca->minRmsd(mol2_ca,maskmol,maskmol2);
// fprintf(stderr,"Not implemented yet!\n");
// exit(0);
rmsd_f = mol->minRmsd(mol2,matrix4,maskmol,maskmol2);
}
else
rmsd_f = mol->minRmsd(mol2);
}
printf("RMSD: init. %.4f ",rmsd_i);
printf("\n");
for(int i=0; i < 4; i++)
{
for(int j=0; j < 4; j++)
printf("%6.3f ", matrix4[i][j]);
printf("\n");
}
if(Dist.isSet())
{
if( CAlpha.isSet() || BBone.isSet() )
mol_ca->dist_profile(mol2_ca,&prof,maskmol,maskmol2);
else
mol->dist_profile(mol2,&prof,maskmol,maskmol2);
}
if(gauss.isSet()) // YES-Gauss
{
int imax = 1000; // maximum number of iterations
int iter=0;
double *prof_wrmsd=NULL;
float conv = 1e-6; // convergence criteria
float delta = 1e6;
float score_old = 1e6;
float score;
double sum_w=0.0;
int num_atoms,num_res;
// Initial alignment (minRMSD) (computed with selection, but applied to full model)
M4Rot *matrix4_op=new M4Rot(matrix4);
mol2->applyAtoms(matrix4_op); // superpose full-atom
delete matrix4_op;
if( CAlpha.isSet() || BBone.isSet() )
{
num_atoms = mol_ca->get_num_atoms();
num_res = mol_ca->get_num_fragments();
}
else
{
num_atoms = mol->get_num_atoms();
num_res = mol->get_num_fragments();
}
// Iterate until convergence
for(iter=0; iter<imax && delta>conv; iter++)
{
score_old = score;
if( CAlpha.isSet() || BBone.isSet() )
{
// norm_profile(prof_wrmsd, mol_ca->get_num_atoms(), 0.0, 1.0);
if(AlnFile.isSet())
{
mol_ca->gaussian_weight(mol2_ca,&prof_wrmsd,maskmol,maskmol2,gauss_c.getValue());
score = mol_ca->minWRmsd(mol2_ca,matrix4,prof_wrmsd,maskmol,maskmol2); // computing transformation
}
else
{
mol_ca->gaussian_weight(mol2_ca,&prof_wrmsd,gauss_c.getValue());
score = mol_ca->minWRmsd(mol2_ca,matrix4,prof_wrmsd); // computing transformation
}
matrix4_op = new M4Rot(matrix4);
mol2->applyAtoms(matrix4_op);
}
else
{
// norm_profile(prof_wrmsd, mol->get_num_atoms(), 0.0, 1.0);
if(AlnFile.isSet())
{
mol->gaussian_weight(mol2,&prof_wrmsd,maskmol,maskmol2,gauss_c.getValue());
score = mol->minWRmsd(mol2,matrix4,prof_wrmsd,maskmol,maskmol2); // computing transformation
}
else
{
mol->gaussian_weight(mol2,&prof_wrmsd,gauss_c.getValue());
score = mol->minWRmsd(mol2,matrix4,prof_wrmsd); // computing transformation
}
matrix4_op = new M4Rot(matrix4);
mol2->applyAtoms(matrix4_op);
}
delta = fabs(score_old - score);
// printf("iter= %d score= %f old= %f\n",iter,score,score_old);
}
if(AlnFile.isSet())
rmsd_f = mol->rmsd(mol2,maskmol,maskmol2);
else
rmsd_f = mol->rmsd(mol2);
for(int i=0; i < num_atoms; i++)
sum_w += prof_wrmsd[i];
// printf(">> rmsd_i %.4f -> rmsd_f %.4f wrmsd= %f %%match= %.2f iters= %d C= %.1f\n",rmsd_i,rmsd_f,score,100*(sum_w/num_atoms),iter,gauss_c.getValue());
printf(" final %.4f wrmsd= %f %%Matching: atoms= %.2f res= %.2f iter= %d C= %.1f\n",rmsd_f,score,100*(sum_w/num_atoms),100*(sum_w/num_res),iter,gauss_c.getValue());
}
else
printf(" final %.4f\n",rmsd_f);
if(pdb_moved.isSet())
{
if(!gauss.isSet()) // NO-Gauss (with Gauss, transformation was already applied)
{
M4Rot *matrix4_op=new M4Rot(matrix4);
mol2->applyAtoms(matrix4_op); // superpose full-atom
delete matrix4_op;
}
if(Dist.isSet())
// mol->dist_profile(mol2,&prof2,maskmol,maskmol2);
{
if( CAlpha.isSet() || BBone.isSet() )
mol_ca->dist_profile(mol2_ca,&prof2,maskmol,maskmol2);
else
mol->dist_profile(mol2,&prof2,maskmol,maskmol2);
}
strcpy(file_out,((temp=pdb_moved.getValue()).c_str()));
mol2->writePDB(file_out);
printf(">> Saved in %s\n", file_out);
}
if(Dist.isSet())
{
FILE *f_prof;
if((f_prof=fopen(dist_profiles,"w"))==NULL)
{
fprintf(stderr, "\n Error opening file: %s\n\n",dist_profiles);
exit(1);
}
pdbIter *it = new pdbIter(mol,false); // without SMol
int num_res = it->num_fragment();
delete it;
// printf("Number of fragments: %d\n",num_res);
if(pdb_moved.isSet())
{
fprintf(f_prof,"# Res Before[A] After[A]\n");
for(int i=0; i < num_res; i++)
fprintf(f_prof,"%5d %10f %10f\n",i+1,prof[i],prof2[i]);
free(prof2);
}
else
{
fprintf(f_prof,"# Res Before[A]\n");
for(int i=0; i < num_res; i++)
fprintf(f_prof,"%5d %10f\n",i+1,prof[i]);
}
fclose(f_prof);
printf(">> Distance profile(s) saved in %s\n", dist_profiles);
free(prof);
}
// END
}
catch ( ArgException& e )
{
std::cout << " Error->" << e.error() << " " << e.argId() << std::endl;
}
}
// Compute the RMSD between two arrays
float atomic_rmsd(float *array, float *array2, int natoms)
{
double accum = 0.0;
for(int i = 0; i < natoms*3; i++)
{
accum += powf(array[i] - array2[i], 2);
}
return( (float) sqrt(accum / natoms) );
}
| 32.801266 | 188 | 0.632231 | chaconlab |
c70afa5c968204fb92f551e7a66a1b8713e1b0df | 2,789 | cpp | C++ | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | 1 | 2018-06-16T17:53:43.000Z | 2018-06-16T17:53:43.000Z | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null |
#include "KAI/KAI.h"
#include "KAI/BuiltinTypes/Signed32.h"
KAI_BEGIN
namespace Exception
{
nstd::string Base::ToString() const
{
StringStream S;
std::string loc = location.ToString().c_str();
loc = loc.substr(loc.find_last_of('/') + 1);
S << loc.c_str() << text << ": ";
WriteExtendedInformation(S);
return S.ToString().c_str();
}
void TypeMismatch::WriteExtendedInformation(StringStream &S) const
{
S << "first=" << Type::Number(first).ToString() << ", second=" << Type::Number(second).ToString();
}
void UnknownTypeNumber::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void UnknownObject::WriteExtendedInformation(StringStream &S) const
{
S << "handle=" << handle.GetValue();
}
void ObjectNotFound::WriteExtendedInformation(StringStream &S) const
{
S << "label=" << label;
}
void NoProperty::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number << ", type_property=" << type_property;
}
void PacketExtraction::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void PacketInsertion::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void CannotResolve::WriteExtendedInformation(StringStream &S) const
{
if (!path.Empty())
S << "path=" << path;
else if (!label.Empty())
S << "label=" << label;
else
S << "object=" << object;
}
void InvalidPathname::WriteExtendedInformation(StringStream &S) const
{
S << "text=" << text;
}
void ObjectNotInTree::WriteExtendedInformation(StringStream &S) const
{
S << "object=" << object;
}
void UnknownMethod::WriteExtendedInformation(StringStream &S) const
{
S << "name=" << name << ", class=" << class_name;
}
void UnknownHandle::WriteExtendedInformation(StringStream &S) const
{
S << "handle=" << handle.GetValue();
}
void InvalidStringLiteral::WriteExtendedInformation(StringStream &S) const
{
S << "text='" << text << "'";
}
void CannotNew::WriteExtendedInformation(StringStream &S) const
{
S << "object=" << arg;
}
void UnknownKey::WriteExtendedInformation(StringStream &S) const
{
S << "key=" << key;
}
void NotImplemented::WriteExtendedInformation(StringStream &S) const
{
S << "what=" << text;
}
void BadIndex::WriteExtendedInformation(StringStream &S) const
{
S << "index=" << index;
}
void InvalidIdentifier::WriteExtendedInformation(StringStream &S) const
{
S << "what='" << what << "'";
}
void FileNotFound::WriteExtendedInformation(StringStream &S) const
{
S << "filename='" << filename << "'";
}
void UnknownProperty::WriteExtendedInformation(StringStream &S) const
{
S << "class=" << klass << ", property=" << prop;
}
}
KAI_END
//EOF
| 22.134921 | 100 | 0.669416 | kalineh |
c70bb8e0a1fa398648d66bdc673df158b58f6ade | 10,580 | cpp | C++ | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | //
// PropGenerator.cpp
// Rigor
//
// Created by Ajmal Kunnummal on 2/20/15.
// Copyright (c) 2015 ajmal. All rights reserved.
//
#include <opencv2/core/core.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "bk_dynamicgraphs.h"
#include "SLICSegment.h"
#include "PropGenerator.h"
#include "Parameters.h"
#include "SPImage.h"
#include "PixelImage.h"
#include "FuxinGraph.h"
#include "SimpleBK.h"
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
cv::Mat image;
cv::Mat sp_im;
PropGenerator::PropGenerator(Parameters ¶ms){
this->params = params;
}
void print_pos_val(int event, int x, int y, int flags, void* image){
if ( event == cv::EVENT_LBUTTONDOWN ) {
cv::Mat * imp = (cv::Mat *) image;
cv::Mat im = *imp;
cout << "click: " << ((cv::Mat *) image)->at<int>(y, x) << endl;
}
}
void show_in_color(string window, cv::Mat &image){
cv::namedWindow(window, cv::WINDOW_AUTOSIZE);
double min, max;
cv::minMaxIdx(image, &min, &max);
cv::Mat adj_sp_map;
// expand your range to 0..255. Similar to histEq();
image.convertTo(adj_sp_map, CV_8UC1, 255 / (max-min), -min);
// convert to a colormaped image
cv::applyColorMap(adj_sp_map, adj_sp_map, cv::COLORMAP_JET);
cv::imshow(window, adj_sp_map);
cv::setMouseCallback(window, print_pos_val, &image);
}
inline cv::Mat iterator_to_image(AbstractGraph::UnaryIterator it, int sx, int sy) {
cv::Mat cut_im = cv::Mat(sy, sx, CV_8U);
auto im_it = cut_im.begin<uchar>(), im_it_end = cut_im.end<uchar>();
auto p = 0;
for(; im_it != im_it_end; ++im_it, ++it) {
auto ed = (uchar) (*it).first;
*im_it = ed;
if(0 == (int) (*it).second) {
cout << (int) (uchar) (*it).first << endl;
}
}
return cut_im;
}
cv::Mat gradient(cv::Mat image){
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
GaussianBlur( image, image, cv::Size(3,3), 0, 0, cv::BORDER_DEFAULT );
/// Convert it to gray
cv::Mat image_gray;
cvtColor( image, image_gray, CV_RGB2GRAY );
/// Generate grad_x and grad_y
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
/// Gradient X
//Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
Sobel( image_gray, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT );
convertScaleAbs( grad_x, abs_grad_x );
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel( image_gray, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT );
convertScaleAbs( grad_y, abs_grad_y );
/// Total Gradient (approximate)
cv::Mat grad;
addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
cv::Mat gradf = cv::Mat(image.size[0], image.size[1], CV_64F);
auto i_it = grad.begin<uchar>();
for(auto f_it = gradf.begin<double>() ; f_it != gradf.end<double>(); ++i_it, ++f_it) {
*f_it = float(*i_it);
}
return gradf;
}
cv::Mat struct_edges(cv::Mat image){
/// Convert it to gray
cv::Mat image_gray;
cvtColor( image, image_gray, CV_RGB2GRAY );
cv::Mat grayf = cv::Mat(image.size[0], image.size[1], CV_64F);
auto i_it = image_gray.begin<uchar>();
for(auto f_it = grayf.begin<double>() ; f_it != grayf.end<double>(); ++i_it, ++f_it) {
*f_it = float(*i_it);
}
return grayf;
}
void PropGenerator::generate(fs::path filename){
image = cv::imread(filename.c_str());
if (image.empty()) {
// Check for invalid input
std::cout << "Could not open or find the image" << std::endl;
return;
}
if(params.debug){
cout << "Read image" << endl;
cv::namedWindow("Input Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Input Image", image);
}
cv::Mat edges = gradient(image);
//cv::Mat edges = cv::imread("/Users/ajmalkunnummal/Pictures/peppers_str_edges_fat.png");
//edges = struct_edges(edges);
if(params.debug){
cout << "Ran edge detection" << endl;
cv::namedWindow( "Edge Detector", CV_WINDOW_AUTOSIZE );
imshow( "Edge Detector", edges );
}
int num_sp = SPImage::slic_segmentation(image, sp_im, params.num_sp, params.compactness);
if(params.debug) {
cout << "Segmented image. Num of superpixels: " << num_sp << endl;
show_in_color("Superpixels", sp_im);
}
SPImage spixels = SPImage(image, sp_im, edges, num_sp);
if(params.debug) {
cout << "Setup graph and pairwise edges" << endl;
cv::namedWindow("Superpixel Colors", cv::WINDOW_AUTOSIZE);
cv::imshow("Superpixel Colors", spixels.get_color_sp_im());
}
vector< set<int> > seeds = SPImage::generate_seeds(sp_im, params.seeds, params.seed_radius = 5);
if(params.debug){
cout << "Generated " << seeds.size() << " seeds" << endl;
cv::imshow("Seeds", spixels.seeds_to_sp_im(seeds));
}
vector< unique_ptr<AbstractGraph> > graphs;
for ( auto& seed: seeds) {
for (auto graph_type: params.graph_types) {
graphs.push_back( graph_type(seed, &spixels) );
}
}
AbstractGraph::UnaryIterator unaries = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 1]);
vector<edgew> stats;
// for (int i = 0; i < graphs[0]->image->getNumPixels(); unaries++, i++) {
// std::pair<edgew, edgew> unary_pair = *unaries;
//// cout << unary_pair.first << " " << unary_pair.second << endl;
// stats.push_back(unary_pair.first);
// }
for(int i = 1; i < spixels.getNumPairwise(); i+=2) {
auto pw = spixels.get_pairwise(0, i);
stats.push_back(pw.w);
}
sort(stats.begin(), stats.end());
cout << spixels.getNumPairwise() << endl;
cout << stats[0] << endl;
cout << stats[stats.size() / 4] << endl;
cout << stats[stats.size() / 2] << endl;
cout << stats[stats.size() / 4 * 3] << endl;
cout << stats[stats.size() / 8 * 7] << endl;
cout << stats[stats.size() / 16 * 15] << endl;
cout << stats[stats.size() - 7] << endl;
cout << stats[stats.size() - 1] << endl;
if(params.debug){
cout << "Setup " << graphs.size() << " graphs (1 for each seed and graph type)" << endl;
}
auto cuts = nodynamic_param_maxflow(graphs);
if(params.debug){
cout << "Found " << cuts.size() / spixels.spixels.size() << " cuts" << endl;
// for(int i = 0; i < cuts.size() / spixels.spixels.size(); i++){
// for(int j = 0; j < spixels.spixels.size(); j++){
// cout << cuts[ i * spixels.spixels.size() + j];
// }
// cout << endl;
// }
for (auto cur_cut = cuts.begin(); cur_cut != cuts.end(); cur_cut += spixels.spixels.size() ) {
cv::imshow("Cut", spixels.cut_to_image(cur_cut));
cv::waitKey(0);
}
}
if(params.debug)
cv::waitKey(0);
}
void PropGenerator::generate_pix(fs::path filename){
image = cv::imread(filename.c_str());
if (image.empty()) {
// Check for invalid input
std::cout << "Could not open or find the image" << std::endl ;
return;
}
if(params.debug){
cout << "Read image" << endl;
cv::namedWindow("Input Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Input Image", image);
}
cv::Mat edges = gradient(image) ;
//cv::Mat edges = cv::imread("/Users/ajmalkunnummal/Pictures/peppers_str_edges_fat.png");
//edges = struct_edges(edges);
if(params.debug){
cout << "Ran edge detection" << endl;
cv::namedWindow( "Edge Detector", CV_WINDOW_AUTOSIZE );
imshow( "Edge Detector", edges);
}
PixelImage spixels = PixelImage(image, edges);
cout << "Num of pixels: " << spixels.getNumPixels() << endl;
cout << "unary color: " << spixels.get_color(0) << endl;
cout << "unary size:" << spixels.get_size(0) << endl;
cout << "unary ext:" << spixels.get_ext(0) << endl;
vector< set<int> > seeds = { { spixels.getNumPixels() / 2 + spixels.sx / 2 } };
if(params.debug) {
cout << "Generated " << seeds.size() << " seeds" << endl;
// cv::imshow("Seeds", spixels.seeds_to_sp_im(seeds));
}
vector< unique_ptr<AbstractGraph> > graphs;
for ( auto& seed: seeds) {
for (auto graph_type: params.graph_types) {
graphs.push_back( graph_type(seed, &spixels) );
}
}
auto unaries2 = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 0 - 1]);
imshow( "Unaries", iterator_to_image(unaries2, spixels.sx, spixels.sy) );
AbstractGraph::UnaryIterator unaries = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 0 - 1]);
vector<edgew> stats;
// for (int i = 0; i < graphs[0]->image->getNumPixels(); unaries++, i++) {
// std::pair<edgew, edgew> unary_pair = *unaries;
//// cout << unary_pair.first << " " << unary_pair.second << endl;
// stats.push_back(unary_pair.first);
// }
for(int i = 1; i < spixels.getNumPairwise(); i+=2) {
auto pw = spixels.get_pairwise(0, i);
stats.push_back(-pw.w);
}
sort(stats.begin(), stats.end());
cout << stats[0] << endl;
cout << stats[stats.size() / 4] << endl;
cout << stats[stats.size() / 2] << endl;
cout << stats[stats.size() / 4 * 3] << endl;
cout << stats[stats.size() / 8 * 7] << endl;
cout << stats[stats.size() / 16 * 15] << endl;
cout << stats[stats.size() - 7] << endl;
cout << stats[stats.size() - 1] << endl;
cout << "highest" << endl;
if(params.debug){
cout << "Setup " << graphs.size() << " graphs (1 for each seed and graph type)" << endl;
}
auto cuts = nodynamic_param_maxflow(graphs);
if(params.debug){
cout << "Found " << cuts.size() / spixels.getNumPixels() << " cuts" << endl;
for (auto cur_cut = cuts.begin(); cur_cut != cuts.end(); cur_cut += spixels.getNumPixels() ) {
cv::imshow("Cut", spixels.cut_to_image(cur_cut));
cv::waitKey(0);
}
}
if(params.debug)
cv::waitKey(0);
} | 31.58209 | 121 | 0.571267 | ajmalk |
c71593765c3930e695c248de4da51db1ea5354ae | 858 | cpp | C++ | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | 1 | 2019-10-09T11:25:10.000Z | 2019-10-09T11:25:10.000Z | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | null | null | null | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | 1 | 2021-03-31T08:45:51.000Z | 2021-03-31T08:45:51.000Z | // Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
//
// Example 1:
//
// Input: "Let's take LeetCode contest"
// Output: "s'teL ekat edoCteeL tsetnoc"
//
//
//
// Note:
// In the string, each word is separated by single space and there will not be any extra space in the string.
class Solution {
public:
void myReverse(char *a, char *b) {
while (a < b) {
*a ^= *b ^= *a ^= *b;
++a;
--b;
}
}
string reverseWords(string s) {
int i = 0, j = 0;
for (i = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
myReverse(&s[j], &s[i - 1]);
j = i + 1;
}
}
myReverse(&s[j], &s[i - 1]);
return s;
}
};
| 23.833333 | 151 | 0.484848 | i-square |
c716f6f316a208d71eeeff6b0fb0b84bb82eaaae | 443 | hpp | C++ | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | #pragma once
#include <States/States.hpp>
#include <States/MainMenuState.hpp>
class Game
{
public:
Game();
~Game();
void run();
private:
void initWindow();
void render();
void update(const float& deltaTime);
void updateDeltaTime();
void initStates();
void events();
bool isClosed;
float mDeltaTime;
sf::RenderWindow* mWindow;
sf::Event e;
sf::Clock mClock;
std::stack<States*> mStates;
};
| 13.84375 | 38 | 0.641084 | JTuthill01 |
c718f61968dd07a288759f568967812dd56075ea | 2,065 | cpp | C++ | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 4 | 2019-03-03T18:13:30.000Z | 2020-08-25T18:15:30.000Z | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | null | null | null | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 6 | 2016-07-15T11:04:52.000Z | 2021-12-07T03:11:42.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <LowLevel/GteLogger.h>
#include <Graphics/GL4/GteGL4RasterizerState.h>
using namespace gte;
GL4RasterizerState::GL4RasterizerState(RasterizerState const* rasterizerState)
:
GL4DrawingState(rasterizerState)
{
mFillMode = msFillMode[rasterizerState->fillMode];
mCullFace = msCullFace[rasterizerState->cullMode];
mFrontFace = (rasterizerState->frontCCW ? GL_CCW : GL_CW);
mDepthScale = rasterizerState->slopeScaledDepthBias;
mDepthBias = static_cast<float>(rasterizerState->depthBias);
mEnableScissor = (rasterizerState->enableScissor ? GL_TRUE : GL_FALSE);
}
std::shared_ptr<GEObject> GL4RasterizerState::Create(void*, GraphicsObject const* object)
{
if (object->GetType() == GT_RASTERIZER_STATE)
{
return std::make_shared<GL4RasterizerState>(
static_cast<RasterizerState const*>(object));
}
LogError("Invalid object type.");
return nullptr;
}
void GL4RasterizerState::Enable()
{
glPolygonMode(GL_FRONT_AND_BACK, mFillMode);
if (mCullFace != 0)
{
glEnable(GL_CULL_FACE);
glFrontFace(mFrontFace);
glCullFace(mCullFace);
}
else
{
glDisable(GL_CULL_FACE);
}
if (mDepthScale != 0.0f && mDepthBias != 0.0f)
{
glEnable(GL_POLYGON_OFFSET_FILL);
glEnable(GL_POLYGON_OFFSET_LINE);
glEnable(GL_POLYGON_OFFSET_POINT);
glPolygonOffset(mDepthScale, mDepthBias);
}
else
{
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_POLYGON_OFFSET_LINE);
glDisable(GL_POLYGON_OFFSET_POINT);
}
}
GLenum const GL4RasterizerState::msFillMode[] =
{
GL_FILL,
GL_LINE
};
GLenum const GL4RasterizerState::msCullFace[] =
{
0,
GL_FRONT,
GL_BACK
};
| 25.8125 | 89 | 0.6954 | pmjoniak |
c719344b3a34a9cd42a6bcc89c762dffc9340924 | 5,551 | cc | C++ | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_XBar[] = {
120,156,165,86,225,110,27,69,16,222,59,251,236,196,118,98,
199,73,220,34,40,92,11,8,83,104,140,144,34,33,129,16,
4,20,9,41,73,171,115,139,138,133,100,109,238,214,241,133,
187,219,211,237,154,218,253,73,249,201,19,240,34,188,15,47,
2,51,115,119,27,167,53,73,73,227,100,179,51,158,221,157,
249,230,155,217,245,89,241,83,129,191,111,92,139,169,191,97,
18,192,175,197,34,198,98,198,70,140,89,40,219,44,178,88,
108,177,145,149,203,21,22,217,236,113,49,171,228,179,42,139,
170,44,118,216,200,1,27,135,9,198,38,22,11,106,236,119,
198,94,48,246,211,168,198,130,58,19,53,210,174,25,109,157,
5,235,165,182,97,180,107,44,104,50,225,144,182,101,180,235,
44,216,96,98,141,180,155,70,219,96,65,187,212,118,140,182,
201,130,45,38,234,164,237,26,109,139,5,219,108,216,223,129,
48,195,127,224,167,111,193,76,175,195,112,44,226,135,167,231,
194,215,185,170,6,195,112,161,180,136,115,25,135,251,23,214,
195,176,176,214,107,32,29,112,37,158,30,240,204,95,198,243,
0,241,252,3,38,0,4,192,6,8,141,108,38,42,108,84,
69,120,1,36,8,26,112,125,1,243,58,186,15,72,226,28,
192,104,176,243,38,194,137,98,171,20,29,18,55,74,177,70,
226,38,137,109,4,22,197,14,19,91,136,45,206,187,244,213,
54,19,59,8,240,11,155,141,118,153,55,236,55,192,33,175,
10,131,106,194,16,139,120,48,63,229,217,222,116,170,238,129,
252,35,68,36,51,55,149,153,118,39,48,241,101,146,128,42,
76,206,220,152,3,24,153,82,119,175,54,83,17,255,85,40,
213,1,171,195,76,38,90,36,129,27,113,248,231,47,84,27,
149,50,123,198,179,11,29,26,122,66,165,50,81,194,40,223,
3,229,247,92,243,148,235,169,251,44,12,96,76,69,113,94,
255,116,161,133,250,88,61,0,155,71,43,28,224,137,43,83,
29,202,132,71,110,32,38,124,22,233,194,169,79,113,133,200,
192,62,118,121,16,100,224,38,68,149,166,184,10,55,209,83,
97,86,224,81,253,30,102,27,243,59,30,39,60,22,227,177,
110,144,16,203,96,22,161,136,56,234,69,42,104,242,56,155,
9,178,230,167,74,103,28,168,129,214,254,124,62,158,10,30,
136,76,183,13,114,67,244,7,157,215,14,102,2,37,221,49,
223,30,19,210,244,53,178,48,7,158,44,31,241,140,199,164,
252,110,225,71,66,209,162,73,1,243,184,64,143,206,153,228,
48,27,29,26,102,5,204,70,137,206,62,73,84,120,150,136,
128,246,39,168,201,237,37,31,234,216,18,114,88,40,206,3,
41,35,178,62,228,145,18,122,11,102,51,216,180,48,25,103,
60,57,19,125,44,130,139,65,125,8,195,96,42,99,49,120,
62,149,51,53,157,205,195,100,112,38,226,253,129,202,252,1,
178,16,203,103,47,93,16,53,63,195,37,8,126,205,162,143,
221,178,90,237,182,5,159,74,187,218,170,83,128,39,50,241,
229,84,100,34,209,151,42,207,42,43,111,231,165,202,195,154,
171,96,5,216,200,184,183,241,136,91,69,5,36,23,123,141,
139,106,232,163,31,30,70,233,33,220,30,130,224,53,46,5,
245,127,35,195,35,159,226,146,106,17,153,110,97,34,87,5,
97,218,71,178,50,8,81,101,231,78,217,59,106,36,154,14,
98,83,7,1,77,131,137,188,137,216,212,68,140,198,33,205,
6,105,160,125,180,217,121,135,186,9,40,183,16,30,138,244,
29,244,115,167,128,231,101,108,40,53,195,68,202,212,205,94,
174,220,93,252,74,68,192,99,17,184,138,108,38,97,132,141,
227,1,5,11,108,131,82,128,82,11,149,235,103,82,41,216,
146,10,47,149,97,162,93,57,113,139,211,96,175,193,107,174,
152,37,225,36,244,57,214,188,250,192,180,109,176,225,154,12,
205,170,83,17,201,228,76,185,90,238,245,187,255,145,95,15,
201,229,97,185,104,12,147,66,24,191,82,57,205,18,129,67,
10,142,234,226,228,201,209,17,165,52,95,147,135,237,221,198,
237,222,194,237,240,68,242,121,44,39,99,19,165,222,89,86,
47,133,226,153,107,8,170,30,208,215,72,10,158,44,72,165,
242,155,233,198,92,196,252,254,140,75,54,203,42,171,182,43,
93,167,91,237,86,188,119,177,107,189,194,196,227,171,153,88,
80,111,137,140,231,235,37,251,26,164,36,234,21,68,107,25,
162,225,97,106,187,32,218,50,112,192,179,208,42,61,60,146,
242,151,89,106,72,246,186,73,38,200,190,56,62,80,46,117,
180,121,24,207,98,215,135,91,197,15,245,2,153,179,76,208,
254,198,245,140,64,95,34,242,165,100,2,101,201,123,31,7,
244,202,195,20,228,13,84,196,50,91,12,195,231,130,56,17,
243,249,184,60,249,230,105,35,180,240,175,97,210,214,181,119,
43,68,137,163,207,87,183,144,47,87,38,14,82,102,222,33,
65,222,69,234,152,68,108,42,204,130,231,151,88,199,196,65,
154,144,218,33,2,72,233,8,113,111,239,35,244,189,121,25,
47,172,124,15,47,3,143,74,11,115,234,221,41,83,236,225,
6,30,222,55,222,189,55,106,162,247,193,242,55,67,92,187,
86,45,174,8,167,237,16,236,57,45,86,35,241,237,85,72,
84,8,9,187,68,162,74,141,114,9,9,28,155,136,7,6,
27,34,27,66,220,56,36,120,236,18,20,194,168,223,186,25,
50,119,223,28,158,79,192,242,79,92,210,185,12,79,165,237,
212,234,68,147,31,30,174,190,46,221,107,105,2,177,87,76,
236,182,9,182,118,109,176,55,15,7,95,108,127,225,146,181,
60,28,7,131,57,201,43,149,136,104,222,227,241,254,94,138,
143,35,69,143,26,148,50,57,95,228,165,183,191,103,94,235,
30,70,64,111,12,186,142,169,15,230,105,64,98,17,124,116,
232,141,93,166,227,191,202,31,136,95,227,158,116,89,118,172,
142,213,128,79,199,238,245,123,213,222,173,94,187,119,187,119,
231,95,158,139,213,113,
};
EmbeddedPython embedded_m5_objects_XBar(
"m5/objects/XBar.py",
"/home/zhoushuxin/gem5/src/mem/XBar.py",
"m5.objects.XBar",
data_m5_objects_XBar,
1366,
3454);
} // anonymous namespace
| 53.893204 | 66 | 0.660061 | zhoushuxin |
c71977f03a3da3cb0599c971b9a81ac72c6479ef | 2,898 | hpp | C++ | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | /*
** Window.h for Project-Master in /home/peixot_b/Epitech/Tek2/CPP/Arcade/cpp_arcade/lib/sfml/src
**
** Made by peixot_b
** Login <[email protected]>
**
** Started on Thu Mar 23 13:35:43 2017 peixot_b
** Last update Thu Mar 23 13:35:45 2017 peixot_b
*/
#ifndef WINDOW_HPP_
# define WINDOW_HPP_
#include <iostream>
#include <unistd.h>
#include <memory>
#include "Vector3d.hpp"
#include "IWindows.hpp"
#include <SFML/Graphics.hpp>
namespace arcade
{
class Window : public IWindows {
public:
Window(std::shared_ptr<std::vector<std::shared_ptr<arcade::IObject>>>&, uint64_t height = 0, uint64_t width = 0);
virtual ~Window();
virtual bool isOpen() const;
virtual int32_t getHeight() const;
virtual int32_t getLenght() const;
virtual sf::RenderWindow const &get_Window() const;
virtual Vector3d const &getSize() const;
void setMapSize(uint32_t size);
virtual bool event();
virtual arcade::FrameType refresh();
virtual void addObject(std::shared_ptr<arcade::IObject> &, Vector3d const &);
virtual void addObject(std::shared_ptr<arcade::IObject> &);
virtual void moveObject(std::shared_ptr<arcade::IObject> &, Vector3d const &);
virtual void moveObject(std::string, Vector3d const &);
virtual void destroyObject(std::shared_ptr<arcade::IObject> &);
virtual std::shared_ptr<IEvenement> getEvent(void);
virtual void removeObserver(IObserver *);
virtual void registerObserver(IObserver *);
static uint32_t const WINSIZE = 1000;
static uint32_t MAPSIZE;
static float SIZECELL;
protected:
Vector3d _size;
bool _isopen;
sf::RenderWindow _window;
sf::Event _event;
std::shared_ptr<std::vector<std::shared_ptr<arcade::IObject>>> _objects;
int32_t _height;
int32_t _width;
std::vector<arcade::IObserver*> _observers;
Vector3d _min_size;
sf::Clock _clock;
sf::Int32 _calc;
virtual void notify(IEvenement const &);
};
}
#endif /* !WINDOW_HPP_ */ | 38.64 | 121 | 0.484127 | benjyup |
c71a0aa154320c6927d2607d92b198f61fcd1213 | 1,366 | hpp | C++ | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 4 | 2020-06-11T00:35:03.000Z | 2020-06-23T11:57:52.000Z | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 1 | 2020-03-17T13:34:16.000Z | 2020-03-17T13:34:16.000Z | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 2 | 2020-03-19T12:20:17.000Z | 2020-09-03T07:49:06.000Z |
#pragma once
#include <array>
#include "Build/Namespace.hpp"
#include "Types/FundamentalTypes.hpp"
BEGIN_RUKEN_NAMESPACE
/**
* \brief Represents a node in a LinkedChunkList
* \tparam TType Elements type of the node
* \tparam TChunkSize Size in octets of the chunk (node) (default is 16Kb or 2046 octets)
*/
template<typename TType, RkSize TChunkSize = 2048>
class LinkedChunkListNode
{
public:
static constexpr RkSize element_count = TChunkSize / sizeof(TType);
#pragma region Members
std::array<TType, element_count> data {};
LinkedChunkListNode<TType, TChunkSize>* next_node {nullptr};
LinkedChunkListNode<TType, TChunkSize>* prev_node {nullptr};
#pragma endregion
#pragma region Constructors
LinkedChunkListNode() = default;
LinkedChunkListNode(LinkedChunkListNode const& in_copy) = default;
LinkedChunkListNode(LinkedChunkListNode&& in_move) = default;
~LinkedChunkListNode() = default;
#pragma endregion
#pragma region Operators
LinkedChunkListNode& operator=(LinkedChunkListNode const& in_copy) = default;
LinkedChunkListNode& operator=(LinkedChunkListNode&& in_move) = default;
#pragma endregion
};
END_RUKEN_NAMESPACE | 28.458333 | 89 | 0.662518 | Renondedju |
c721fdcc2303702580d1ab10c781f783c5e57df0 | 3,069 | cpp | C++ | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
// https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
#include "UnitSPIRV.h"
namespace {
TEST(TextDestroy, DestroyNull) { spvBinaryDestroy(nullptr); }
TEST(TextDestroy, Default) {
spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_0);
char textStr[] = R"(
OpSource OpenCL_C 12
OpMemoryModel Physical64 OpenCL
OpSourceExtension "PlaceholderExtensionName"
OpEntryPoint Kernel %0 ""
OpExecutionMode %0 LocalSizeHint 1 1 1
%1 = OpTypeVoid
%2 = OpTypeBool
%3 = OpTypeInt 8 0
%4 = OpTypeInt 8 1
%5 = OpTypeInt 16 0
%6 = OpTypeInt 16 1
%7 = OpTypeInt 32 0
%8 = OpTypeInt 32 1
%9 = OpTypeInt 64 0
%10 = OpTypeInt 64 1
%11 = OpTypeFloat 16
%12 = OpTypeFloat 32
%13 = OpTypeFloat 64
%14 = OpTypeVector %3 2
)";
spv_binary binary = nullptr;
spv_diagnostic diagnostic = nullptr;
EXPECT_EQ(SPV_SUCCESS, spvTextToBinary(context, textStr, strlen(textStr),
&binary, &diagnostic));
EXPECT_NE(nullptr, binary);
EXPECT_NE(nullptr, binary->code);
EXPECT_NE(0u, binary->wordCount);
if (diagnostic) {
spvDiagnosticPrint(diagnostic);
ASSERT_TRUE(false);
}
spv_text resultText = nullptr;
EXPECT_EQ(SPV_SUCCESS,
spvBinaryToText(context, binary->code, binary->wordCount, 0,
&resultText, &diagnostic));
spvBinaryDestroy(binary);
if (diagnostic) {
spvDiagnosticPrint(diagnostic);
spvDiagnosticDestroy(diagnostic);
ASSERT_TRUE(false);
}
EXPECT_NE(nullptr, resultText->str);
EXPECT_NE(0u, resultText->length);
spvTextDestroy(resultText);
spvContextDestroy(context);
}
} // anonymous namespace
| 35.686047 | 75 | 0.701531 | Shoegzer |
d178c61c4e9ba53f25a034559952c4317d482ead | 838 | cpp | C++ | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | 6 | 2020-04-23T00:53:05.000Z | 2021-11-11T08:51:14.000Z | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | null | null | null | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | 2 | 2020-11-11T13:30:24.000Z | 2020-12-11T05:39:38.000Z | #include <PrecompiledHeader.h>
#include "SimpleProfiler.h"
SimpleProfiler * g_SimpleProfiler = nullptr;
void DrawSystemPerformanceUnits(std::vector<SystemPerformanceUnit>& units)
{
ImGui::Begin("Performance Info");
std::sort(units.begin(), units.end(), [](SystemPerformanceUnit&a, SystemPerformanceUnit&b) {
return a.miliseconds > b.miliseconds;
});
for (auto &p : units)
{
float ms = p.miliseconds / (float)p.iterations;
ImGui::Text("%s : t=%f ms", p.EventName.c_str(), ms);
}
//units.clear();
//ImGui::Text("Delta Time : %f", info.deltaTime);
//ImGui::Text("Averaged Delta Time: %f", info.averagedDeltaTime);
//ImGui::Text("Drawcalls : %i", info.Drawcalls);
//ImGui::Text("Simulation Time : %f", info.SimTime);
//ImGui::Text("Rendering Time : %f", info.RenderTime);
ImGui::End();
}
| 27.032258 | 93 | 0.661098 | vblanco20-1 |
d178db30d927111c285ec01596affdf6f742b947 | 6,005 | cpp | C++ | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | // This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <[email protected]>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/07/03.
#include "polarphp/utils/DataExtractor.h"
#include "polarphp/utils/ErrorHandling.h"
#include "polarphp/utils/Host.h"
#include "polarphp/utils/SwapByteOrder.h"
namespace polar {
namespace utils {
template <typename T>
static T getU(uint32_t *offsetPtr, const DataExtractor *extractor,
bool isLittleEndian, const char *data)
{
T value = 0;
uint32_t offset = *offsetPtr;
if (extractor->isValidOffsetForDataOfSize(offset, sizeof(value))) {
std::memcpy(&value, &data[offset], sizeof(value));
if (sys::sg_isLittleEndianHost != isLittleEndian) {
polar::utils::swap_byte_order(value);
}
// Advance the offset
*offsetPtr += sizeof(value);
}
return value;
}
template <typename T>
static T *getUs(uint32_t *offsetPtr, T *dst, uint32_t count,
const DataExtractor *extractor, bool isLittleEndian, const char *data)
{
uint32_t offset = *offsetPtr;
if (count > 0 && extractor->isValidOffsetForDataOfSize(offset, sizeof(*dst)*count)) {
for (T *value_ptr = dst, *end = dst + count; value_ptr != end;
++value_ptr, offset += sizeof(*dst)) {
*value_ptr = getU<T>(offsetPtr, extractor, isLittleEndian, data);
}
// Advance the offset
*offsetPtr = offset;
// Return a non-NULL pointer to the converted data as an indicator of
// success
return dst;
}
return nullptr;
}
uint8_t DataExtractor::getU8(uint32_t *offsetPtr) const
{
return getU<uint8_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint8_t *
DataExtractor::getU8(uint32_t *offsetPtr, uint8_t *dst, uint32_t count) const
{
return getUs<uint8_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint16_t DataExtractor::getU16(uint32_t *offsetPtr) const
{
return getU<uint16_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint16_t *DataExtractor::getU16(uint32_t *offsetPtr, uint16_t *dst,
uint32_t count) const
{
return getUs<uint16_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint32_t DataExtractor::getU24(uint32_t *offsetPtr) const
{
uint24_t ExtractedVal =
getU<uint24_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
// The 3 bytes are in the correct byte order for the host.
return ExtractedVal.getAsUint32(sys::sg_isLittleEndianHost);
}
uint32_t DataExtractor::getU32(uint32_t *offsetPtr) const
{
return getU<uint32_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint32_t *DataExtractor::getU32(uint32_t *offsetPtr, uint32_t *dst,
uint32_t count) const
{
return getUs<uint32_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint64_t DataExtractor::getU64(uint32_t *offsetPtr) const
{
return getU<uint64_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint64_t *DataExtractor::getU64(uint32_t *offsetPtr, uint64_t *dst,
uint32_t count) const
{
return getUs<uint64_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint64_t
DataExtractor::getUnsigned(uint32_t *offsetPtr, uint32_t byte_size) const
{
switch (byte_size) {
case 1:
return getU8(offsetPtr);
case 2:
return getU16(offsetPtr);
case 4:
return getU32(offsetPtr);
case 8:
return getU64(offsetPtr);
}
polar_unreachable("getUnsigned unhandled case!");
}
int64_t
DataExtractor::getSigned(uint32_t *offsetPtr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return (int8_t)getU8(offsetPtr);
case 2:
return (int16_t)getU16(offsetPtr);
case 4:
return (int32_t)getU32(offsetPtr);
case 8:
return (int64_t)getU64(offsetPtr);
}
polar_unreachable("getSigned unhandled case!");
}
const char *DataExtractor::getCStr(uint32_t *offsetPtr) const {
uint32_t offset = *offsetPtr;
StringRef::size_type pos = m_data.find('\0', offset);
if (pos != StringRef::npos) {
*offsetPtr = pos + 1;
return m_data.getData() + offset;
}
return nullptr;
}
StringRef DataExtractor::getCStrRef(uint32_t *OffsetPtr) const {
uint32_t Start = *OffsetPtr;
StringRef::size_type Pos = m_data.find('\0', Start);
if (Pos != StringRef::npos) {
*OffsetPtr = Pos + 1;
return StringRef(m_data.getData() + Start, Pos - Start);
}
return StringRef();
}
uint64_t DataExtractor::getULEB128(uint32_t *offsetPtr) const {
uint64_t result = 0;
if (m_data.empty())
return 0;
unsigned shift = 0;
uint32_t offset = *offsetPtr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = m_data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0)
break;
}
*offsetPtr = offset;
return result;
}
int64_t DataExtractor::getSLEB128(uint32_t *offsetPtr) const
{
int64_t result = 0;
if (m_data.empty()) {
return 0;
}
unsigned shift = 0;
uint32_t offset = *offsetPtr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = m_data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
break;
}
}
// Sign bit of byte is 2nd high order bit (0x40)
if (shift < 64 && (byte & 0x40)) {
result |= -(1ULL << shift);
}
*offsetPtr = offset;
return result;
}
} // utils
} // polar
| 28.060748 | 88 | 0.654621 | tryboy |
d17becb7a7c285721fcb2478501b527750f33067 | 3,059 | cpp | C++ | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | #include "Game.h"
#include "CLoad_image.h"
void Game::Draw(Engine* game)
{
SDL_FillRect( game->screen, &game->screen->clip_rect, SDL_MapRGB( game->screen->format, 0, 0, 0 ) );
data.apply(game->screen);
//int X = T.getX();
//int Y = T.getY();
//int kk=0;
/* kk=0;
while(kk<Lektuvai.size())
{
int X = Lektuvai[kk].GetX();
int Y = Lektuvai[kk].GetY();
Load::draw_img(X, Y, Ekranas, Lektuvai[kk].GetSurface(0.5));
kk++;
}*/
//-----------------------------------------------------------------------------
/*
Uint32 colorkey = SDL_MapRGB( Tk->format, 0, 255, 0 );
SDL_SetColorKey( Tk, SDL_SRCCOLORKEY, colorkey );
SDL_Surface* temp = new SDL_Surface;
temp = SDL_DisplayFormatAlpha(Tk);
std::swap(Tk, temp);
SDL_FreeSurface(temp);
delete(temp);
Load::draw_img(400, 50, Ekranas, Tk);
*/
//-----------------------------------------------------------------------------
/* T.render(Ekranas);
kuris++;
if(kuris>30)
kuris=0;
//Piesiamos ciakros apie tanka
Load::draw_img(X + T.rotation->w/2 - A[kuris]->w/2, Y+T.rotation->h/2 - A[kuris]->h/2, Ekranas, A[kuris]);
*/
/*SDL_SetColorKey( Tk, SDL_SRCCOLORKEY, colorkey );
Tk=SDL_DisplayFormatAlpha(Tk);
Load::draw_img(400, 50, Ekranas, Tk);*/
//-----------------------------------------------------------------------------
for(int i = 0; i < kulkos.size() ; i++)
{
if(kulkos.size()!=0)
{
int kx, ky; //Dabartines kulkos koordinates
kx= kulkos[i]->GetX();
ky= kulkos[i]->GetY();
Load::draw_img(kulkos[i]->GetX(),kulkos[i]->GetY(), game->screen, kulkos[i]->KPasukta);
}
}
//-----------------------------------------------------------------------------
/*Pieesiami visi vektoriuje esantys tankai*/
int tmp = tankai.size();
if(tmp!=0)
for(int i = 0; i < tmp; i++)
{
tankai[i]->render(game->screen);
}
//Load::draw_img(400, 50, Ekranas, Tk);
//-----------------------------------------------------------------------------
/*kk=0;
while(kk<Lektuvai.size())
{
int X = Lektuvai[kk].GetX();
int Y = Lektuvai[kk].GetY();
Load::draw_img(X, Y, Ekranas, Lektuvai[kk].GetSurface(1));
kk++;
}*/
//-----------------------------------------------------------------------------
int kk=0;
while(kk<anim.Sprogimai.size())
{
int X = anim.Sprogimai[kk].x;
int Y = anim.Sprogimai[kk].y;
Load::draw_img(X, Y, game->screen, anim.GetFrame( anim.Sprogimai[kk].kadras ) );
kk++;
}
//-----------------------------------------------------------------------------
//SDL_BlitSurface(bg, NULL, game->screen, NULL);
//SDL_UpdateRect(game->screen, 0, 0, 0, 0);
SDL_Flip(game->screen);
//SDL_FreeSurface(Laikinas);
// SDL_FreeSurface(Laikinas1);
//SDL_FreeSurface(Tk);
}
| 28.858491 | 113 | 0.436417 | sheirys |
d17ea87cdd324bd1c305427f0989e04d76736ab9 | 24,509 | inl | C++ | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | 1 | 2018-08-19T15:56:13.000Z | 2018-08-19T15:56:13.000Z | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | null | null | null | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | null | null | null | // Copyright 2018 Christoph Stiller
//
// 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 "mSpriteBatch.h"
#include "mForwardTuple.h"
template <typename ...Args>
mFUNCTION(mSpriteBatch_Create_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Destroy_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetAlphaBlending, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetDrawOrder, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetTextureFilterMode, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_InitializeMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_BindMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
bool mSpriteBatch_Internal_DrawInstantly(mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
return spriteBatch->spriteSortMode == mSB_SSM_None || spriteBatch->alphaMode == mSB_AM_Additive || spriteBatch->alphaMode == mSB_AM_NoAlpha;
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Create, OUT mPtr<mSpriteBatch<Args...>> *pSpriteBatch, IN mAllocator *pAllocator)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSharedPointer_Allocate(pSpriteBatch, pAllocator, (std::function<void(mSpriteBatch<Args...> *)>)[](mSpriteBatch<Args...> *pData) {mSpriteBatch_Destroy_Internal(pData);}, 1));
mERROR_CHECK(mSpriteBatch_Create_Internal(pSpriteBatch->GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_InitializeMesh(*pSpriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Destroy, IN_OUT mPtr<mSpriteBatch<Args...>> *pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
mASSERT_DEBUG((*pSpriteBatch)->isStarted == false, "The sprite batch should currently not be started.");
mERROR_CHECK(mSharedPointer_Destroy(pSpriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Begin, mPtr<mSpriteBatch<Args...>>& spriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(spriteBatch == nullptr, mR_ArgumentNull);
mERROR_IF(spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->isStarted = true;
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
{
mERROR_CHECK(mSpriteBatch_Internal_BindMesh(spriteBatch));
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_SetAlphaBlending(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetDrawOrder(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetTextureFilterMode(spriteBatch));
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Begin, mPtr<mSpriteBatch<Args...>>& spriteBatch, const mSpriteBatch_SpriteSortMode spriteSortMode, const mSpriteBatch_AlphaMode alphaMode, const mSpriteBatch_TextureSampleMode sampleMode /* = mSB_TSM_LinearFiltering */)
{
mFUNCTION_SETUP();
mERROR_IF(spriteBatch == nullptr, mR_ArgumentNull);
mERROR_IF(spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->spriteSortMode = spriteSortMode;
spriteBatch->alphaMode = alphaMode;
spriteBatch->textureSampleMode = sampleMode;
mERROR_CHECK(mSpriteBatch_Begin(spriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_DrawWithDepth, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mVec2f & position, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Create(&renderObject, texture, position, texture->resolutionF, depth, std::forward<Args>(args)...));
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
else
mERROR_CHECK(mQueue_PushBack(spriteBatch->enqueuedRenderObjects, renderObject));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_DrawWithDepth, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mRectangle2D<float_t>& rect, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Create(&renderObject, texture, mVec2f(rect.x, rect.y), mVec2f(rect.w, rect.h), depth, std::forward<Args>(args)...));
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
else
mERROR_CHECK(mQueue_PushBack(spriteBatch->enqueuedRenderObjects, renderObject));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Draw, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture> &texture, const mVec2f & position, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_DrawWithDepth(spriteBatch, texture, position, 0, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Draw, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mRectangle2D<float_t>& rect, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_DrawWithDepth(spriteBatch, texture, rect, 0, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
template <typename ...Args>
mFUNCTION(mSpriteBatch_QuickSortRenderObjects, mPtr<mQueue<mSpriteBatch_Internal_RenderObject<Args...>>> &queue, size_t left, size_t right)
{
mFUNCTION_SETUP();
if (left == right)
mRETURN_SUCCESS();
size_t l = left;
size_t r = right;
const size_t pivotIndex = (left + right) / 2;
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObject;
mERROR_CHECK(mQueue_PointerAt(queue, pivotIndex, &pRenderObject));
const float_t pivot = pRenderObject->position.z;
while (l <= r)
{
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObjectL = nullptr;
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObjectR = nullptr;
while (true)
{
mERROR_CHECK(mQueue_PointerAt(queue, l, &pRenderObjectL));
if (pRenderObjectL->position.z < pivot)
l++;
else
break;
}
while (true)
{
mERROR_CHECK(mQueue_PointerAt(queue, r, &pRenderObjectR));
if (pRenderObjectR->position.z > pivot)
r--;
else
break;
}
if (l <= r)
{
std::swap(*pRenderObjectL, *pRenderObjectR);
l++;
r--;
}
};
if (left < r)
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(queue, left, r));
if (l < right)
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(queue, l, right));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_End, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(!spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->isStarted = false;
if (!mSpriteBatch_Internal_DrawInstantly(spriteBatch))
{
mERROR_CHECK(mSpriteBatch_Internal_BindMesh(spriteBatch));
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_SetAlphaBlending(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetDrawOrder(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetTextureFilterMode(spriteBatch));
size_t count;
mERROR_CHECK(mQueue_GetCount(spriteBatch->enqueuedRenderObjects, &count));
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(spriteBatch->enqueuedRenderObjects, 0, count - 1));
if (spriteBatch->spriteSortMode == mSpriteBatch_SpriteSortMode::mSB_SSM_BackToFront)
{
for (size_t i = 0; i < count; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(spriteBatch->enqueuedRenderObjects, &renderObject));
mDEFER_DESTRUCTION(&renderObject, mSpriteBatch_Internal_RenderObject_Destroy);
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
}
}
else
{
for (int64_t i = (int64_t)count - 1; i >= 0; i--)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopBack(spriteBatch->enqueuedRenderObjects, &renderObject));
mDEFER_DESTRUCTION(&renderObject, mSpriteBatch_Internal_RenderObject_Destroy);
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
}
}
}
else
{
size_t count;
mERROR_CHECK(mQueue_GetCount(spriteBatch->enqueuedRenderObjects, &count));
for (size_t i = 0; i < count; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(spriteBatch->enqueuedRenderObjects, &renderObject));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Destroy(&renderObject));
}
}
mRETURN_SUCCESS();
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
struct mSpriteBatch_GenerateShader;
template<>
struct mSpriteBatch_GenerateShader <>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *)
{
mFUNCTION_SETUP();
mRETURN_SUCCESS();
}
};
template<typename T>
struct mSpriteBatch_GenerateShader <T>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *pParams)
{
mFUNCTION_SETUP();
mERROR_IF(pParams == nullptr, mR_ArgumentNull);
switch (T::type)
{
case mSBE_T_Colour:
mERROR_IF(pParams->colour != 0, mR_InvalidParameter); // Colour parameter cannot be set twice.
pParams->colour = 1;
break;
case mSBE_T_TextureCrop:
mERROR_IF(pParams->textureCrop != 0, mR_InvalidParameter); // TextureCrop parameter cannot be set twice.
pParams->textureCrop = 1;
break;
case mSBE_T_Rotation:
mERROR_IF(pParams->rotation != 0, mR_InvalidParameter); // Rotation parameter cannot be set twice.
pParams->rotation = 1;
break;
case mSBE_T_MatrixTransform:
mERROR_IF(pParams->matrixTransform != 0, mR_InvalidParameter); // MatrixTransform parameter cannot be set twice.
pParams->matrixTransform = 1;
break;
case mSBE_T_TextureFlip:
mERROR_IF(pParams->textureFlip != 0, mR_InvalidParameter); // TextureFlip parameter cannot be set twice.
pParams->textureFlip = 1;
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
};
template<typename T, typename ...Args>
struct mSpriteBatch_GenerateShader <T, Args...>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *pParams)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_GenerateShader<T>::UnpackParams(pParams));
mERROR_CHECK(mSpriteBatch_GenerateShader<Args...>::UnpackParams(pParams));
mRETURN_SUCCESS();
}
};
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Create_Internal, IN_OUT mSpriteBatch<Args...>* pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
mERROR_CHECK(mQueue_Create(&pSpriteBatch->enqueuedRenderObjects, nullptr));
pSpriteBatch->isStarted = false;
pSpriteBatch->alphaMode = mSpriteBatch_AlphaMode::mSB_AM_AlphaBlend;
pSpriteBatch->spriteSortMode = mSpriteBatch_SpriteSortMode::mSB_SSM_BackToFront;
pSpriteBatch->textureSampleMode = mSpriteBatch_TextureSampleMode::mSB_TSM_LinearFiltering;
pSpriteBatch->shaderParams = { 0 };
mERROR_CHECK(mSpriteBatch_GenerateShader<Args...>::UnpackParams(&pSpriteBatch->shaderParams));
// Vertex Shader.
char vertexShader[1024] = "";
mERROR_IF(0 > sprintf_s(vertexShader, "#version 150 core\n\nin vec2 position0;\nin vec2 texCoord0;\nout vec2 _texCoord0;\n\nuniform vec2 screenSize0;\nuniform vec3 startOffset0;\nuniform vec2 scale0;\n"), mR_InternalError);
if (pSpriteBatch->shaderParams.rotation)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\nuniform float " mSBERotation_UniformName ";", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.matrixTransform)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\nuniform mat4 " mSBEMatrixTransform_UniformName ";", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\nvoid main()\n{\n\t_texCoord0 = texCoord0;\n\tvec4 position = vec4(position0, 0.0, 1.0);\n", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy *= scale0;", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.rotation)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tvec2 oldPos = position.xy;\n\tposition.x = cos(" mSBERotation_UniformName ") * oldPos.x - sin(" mSBERotation_UniformName ") * oldPos.y;\n\tposition.y = sin(" mSBERotation_UniformName ") * oldPos.x + cos(" mSBERotation_UniformName ") * oldPos.y;", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy = (position.xy + startOffset0.xy * 2 + scale0) / (screenSize0 * 2);", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.matrixTransform)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition *= " mSBEMatrixTransform_UniformName ";", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy = position.xy * 2 - 1;\n\tposition.y = -position.y;\n\tposition.z = startOffset0.z;\n\n\tgl_Position = position;\n}\n", vertexShader), mR_InternalError);
// Fragment Shader.
char fragmentShader[1024] = "";
mERROR_IF(0 > sprintf_s(fragmentShader, "#version 150 core\n\nout vec4 fragColour0;\n\nin vec2 _texCoord0;\nuniform sampler2D texture0;\n"), mR_InternalError);
if (pSpriteBatch->shaderParams.colour)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec4 " mSBEColour_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureFlip)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec2 " mSBETextureFlip_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureCrop)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec4 " mSBETextureCrop_UniformName ";", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\nvoid main()\n{\n\tvec2 texturePosition = _texCoord0;", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureFlip)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\ttexturePosition = texturePosition * (1 - 2 * " mSBETextureFlip_UniformName ") + " mSBETextureFlip_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureCrop)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\ttexturePosition *= (" mSBETextureCrop_UniformName ".zw - " mSBETextureCrop_UniformName ".xy);\n\ttexturePosition += " mSBETextureCrop_UniformName ".xy;", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\tfragColour0 = texture(texture0, texturePosition);", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.colour)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\tfragColour0 *= " mSBEColour_UniformName ";", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n}\n", fragmentShader), mR_InternalError);
mERROR_CHECK(mSharedPointer_Allocate(&pSpriteBatch->shader, nullptr, (std::function<void(mShader *)>)[](mShader *pData) {mShader_Destroy(pData);}, 1));
mERROR_CHECK(mShader_Create(pSpriteBatch->shader.GetPointer(), vertexShader, fragmentShader, "fragColour0"));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Destroy_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
size_t queueSize = 0;
mERROR_CHECK(mQueue_GetCount(pSpriteBatch->enqueuedRenderObjects, &queueSize));
for (size_t i = 0; i < queueSize; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(pSpriteBatch->enqueuedRenderObjects, &renderObject));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Destroy(&renderObject));
}
mERROR_CHECK(mSharedPointer_Destroy(&pSpriteBatch->shader));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetAlphaBlending, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->alphaMode)
{
case mSB_AM_NoAlpha:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(false));
break;
case mSB_AM_Additive:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case mSB_AM_AlphaBlend:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case mSB_AM_Premultiplied:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetDrawOrder, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->spriteSortMode)
{
case mSB_SSM_None:
glDisable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
break;
case mSB_SSM_BackToFront:
mERROR_CHECK(mRenderParams_ClearDepth());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
break;
case mSB_SSM_FrontToBack:
mERROR_CHECK(mRenderParams_ClearDepth());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetTextureFilterMode, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->textureSampleMode)
{
case mSB_TSM_NearestNeighbor:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case mSB_TSM_LinearFiltering:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_InitializeMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mVec2f buffer[8] = { {-1, -1}, {0, 0}, {-1, 1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}, {1, 1} };
glGenBuffers(1, &spriteBatch->vbo);
glBindBuffer(GL_ARRAY_BUFFER, spriteBatch->vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(buffer), buffer, GL_STATIC_DRAW);
mGL_DEBUG_ERROR_CHECK();
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_BindMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mUnused(spriteBatch);
glBindBuffer(GL_ARRAY_BUFFER, spriteBatch->vbo);
glEnableVertexAttribArray((GLuint)0);
glVertexAttribPointer((GLuint)0, (GLint)2, GL_FLOAT, GL_FALSE, (GLsizei)sizeof(mVec2f) * 2, (const void *)0);
glEnableVertexAttribArray((GLuint)1);
glVertexAttribPointer((GLuint)1, (GLint)2, GL_FLOAT, GL_FALSE, (GLsizei)sizeof(mVec2f) * 2, (const void *)sizeof(mVec2f));
mRETURN_SUCCESS();
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_RenderObject_Create, OUT mSpriteBatch_Internal_RenderObject<Args...>* pRenderObject, const mPtr<mTexture>& texture, const mVec2f position, const mVec2f size, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_IF(pRenderObject == nullptr, mR_ArgumentNull);
pRenderObject->texture = texture;
pRenderObject->position = mVec3f(position, depth);
pRenderObject->size = size;
pRenderObject->args = std::make_tuple<Args...>(std::forward<Args>(args)...);
mRETURN_SUCCESS();
}
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_RenderObject_Destroy, IN_OUT mSpriteBatch_Internal_RenderObject<Args...> *pRenderObject)
{
mFUNCTION_SETUP();
mERROR_IF(pRenderObject == nullptr, mR_ArgumentNull);
mERROR_CHECK(mSharedPointer_Destroy(&pRenderObject->texture));
pRenderObject->args.~tuple();
mRETURN_SUCCESS();
}
template<typename ...Args>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker;
template<>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<>
{
static mFUNCTION(Unpack, mShader &)
{
mFUNCTION_SETUP();
mRETURN_SUCCESS();
}
};
template<typename T>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<T>
{
static mFUNCTION(Unpack, mShader &shader, T t)
{
mFUNCTION_SETUP();
switch (T::type)
{
case mSBE_T_Colour:
mERROR_CHECK(mShader_SetUniform(shader, mSBEColour_UniformName, t));
break;
case mSBE_T_TextureCrop:
mERROR_CHECK(mShader_SetUniform(shader, mSBETextureCrop_UniformName, t));
break;
case mSBE_T_Rotation:
mERROR_CHECK(mShader_SetUniform(shader, mSBERotation_UniformName, t));
break;
case mSBE_T_MatrixTransform:
mERROR_CHECK(mShader_SetUniform(shader, mSBEMatrixTransform_UniformName, t));
break;
case mSBE_T_TextureFlip:
mERROR_CHECK(mShader_SetUniform(shader, mSBETextureFlip_UniformName, t));
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
};
template<typename T, typename ...Args>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<T, Args...>
{
static mFUNCTION(Unpack, mShader &shader, T t, Args... args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render_Unpacker<T>::Unpack(shader, t));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render_Unpacker<Args...>::Unpack(shader, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
};
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_RenderObject_Render, mSpriteBatch_Internal_RenderObject<Args...> &renderObject, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mTexture_Bind(*renderObject.texture.GetPointer()));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "texture0", renderObject.texture));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "screenSize0", mRenderParams_CurrentRenderResolutionF));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "scale0", renderObject.size));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "startOffset0", renderObject.position));
// Set uniforms.
mERROR_CHECK(mForwardTuple(mSpriteBatch_Internal_RenderObject_Render_Unpacker<Args...>::Unpack, *spriteBatch->shader.GetPointer(), renderObject.args));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
mRETURN_SUCCESS();
}
| 35.468886 | 462 | 0.746991 | rainerzufalldererste |
d1801e6e18ea9acf89550577865c582946405fda | 1,465 | cpp | C++ | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | 1 | 2020-04-24T22:55:51.000Z | 2020-04-24T22:55:51.000Z | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | //
// Created by igor on 14/05/2020.
//
#include "opengl/debug/opengl_debug.hpp"
#include "mesh_skinned_drawable_gpu_data.hpp"
namespace vcl {
mesh_skinned_drawable_gpu_data::mesh_skinned_drawable_gpu_data() : mesh_drawable_gpu_data(), vbo_skeleton(0) {}
mesh_skinned_drawable_gpu_data::mesh_skinned_drawable_gpu_data(const mesh_skinned &mesh_cpu_arg) :
mesh_drawable_gpu_data(mesh_cpu_arg) {
// temp copy of the mesh to fill all empty fields
mesh_skinned mesh_cpu = mesh_cpu_arg;
mesh_cpu.fill_empty_fields();
// Fill VBO for skeleton
glGenBuffers(1, &vbo_skeleton);
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
if (!mesh_cpu.bones.empty())
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_bone_data) * mesh_cpu.bones.size(),
&mesh_cpu.bones[0], GL_STATIC_DRAW);
else
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(vao);
// Bones ids at layout 4
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
glEnableVertexAttribArray(4);
glVertexAttribIPointer(4, 4, GL_INT, sizeof(vertex_bone_data), (const GLvoid *) nullptr);
// Bones weights at layout 5
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_bone_data), (const GLvoid *) 16);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
} | 33.295455 | 111 | 0.733788 | asilvaigor |
d1814e87fd208b7a408d02149b61cdf8870840ca | 1,267 | hpp | C++ | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null |
/**
*
* gamepads_handler.hpp
*
* Phased out in favour of port handler and auto handler implementations
**/
#if !defined(AAB_EVENTS_GAMEPADS_HANDLER_CLASS)
#define AAB_EVENTS_GAMEPADS_HANDLER_CLASS
#include"gamepad_handler.hpp"
#include"gamepad_port_handler.hpp"
#include"imports.hpp"
#include<map>
namespace aab {
namespace events{
/*
class GamepadsHandler : public GamepadPortHandler
{
private:
//typedef std::map <int, GamepadHandler::Ptr> HandlerMap;
//HandlerMap handlersG;
public:
typedef aab::types::Smart <GamepadsHandler>::Ptr Ptr;
typedef aab::input::HatPosition HatPosition;
explicit GamepadsHandler (GamepadHandler::Ptr, int id = 0);
explicit GamepadsHandler ();
virtual ~GamepadsHandler () throw ();
//void setHandler (GamepadHandler::Ptr, int id);
//void clearHandler (int id);
//void clearHandlers ();
//GamepadHandler::Ptr getHandler (int id);
//bool hasHandler (int id) const;
//int countHandlers () const;
void buttonPressed (int, int);
void buttonReleased (int, int);
void axisMove (int, int, double);
void ballMove (int, int, double, double);
void hatMove (int, int, HatPosition);
};
*/
} // events
} // aab
#endif // AAB_EVENTS_GAMEPADS_HANDLER_CLASS
| 22.22807 | 74 | 0.700868 | MrTAB |
d1848fc6a0544ad7d0f1dcaa883452f99d5cd3f2 | 8,585 | cpp | C++ | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | 2 | 2018-01-18T21:30:20.000Z | 2018-01-19T02:24:46.000Z | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | /*
**
**
**---------------------------------------------------------------------------
** Copyright 1999 Martin Colberg
** Copyright 1999-2016 Randy Heit
** Copyright 2005-2016 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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.
**---------------------------------------------------------------------------
**
*/
// Cajun bot
//
// [RH] Moved console commands out of d_netcmd.c (in Cajun source), because
// they don't really belong there.
#include "c_cvars.h"
#include "c_dispatch.h"
#include "b_bot.h"
#include "m_argv.h"
#include "doomstat.h"
#include "p_local.h"
#include "cmdlib.h"
#include "teaminfo.h"
#include "d_net.h"
#include "serializer.h"
#include "d_player.h"
#include "vm.h"
IMPLEMENT_CLASS(DBot, false, true)
IMPLEMENT_POINTERS_START(DBot)
IMPLEMENT_POINTER(dest)
IMPLEMENT_POINTER(prev)
IMPLEMENT_POINTER(enemy)
IMPLEMENT_POINTER(missile)
IMPLEMENT_POINTER(mate)
IMPLEMENT_POINTER(last_mate)
IMPLEMENT_POINTERS_END
DEFINE_FIELD(DBot, dest)
DBot::DBot ()
: DThinker(STAT_BOT)
{
Clear ();
}
void DBot::Clear ()
{
player = NULL;
Angle = 0.;
dest = NULL;
prev = NULL;
enemy = NULL;
missile = NULL;
mate = NULL;
last_mate = NULL;
memset(&skill, 0, sizeof(skill));
t_active = 0;
t_respawn = 0;
t_strafe = 0;
t_react = 0;
t_fight = 0;
t_roam = 0;
t_rocket = 0;
first_shot = true;
sleft = false;
allround = false;
increase = false;
old = { 0, 0 };
}
FSerializer &Serialize(FSerializer &arc, const char *key, botskill_t &skill, botskill_t *def)
{
if (arc.BeginObject(key))
{
arc("aiming", skill.aiming)
("perfection", skill.perfection)
("reaction", skill.reaction)
("isp", skill.isp)
.EndObject();
}
return arc;
}
void DBot::Serialize(FSerializer &arc)
{
Super::Serialize (arc);
arc("player", player)
("angle", Angle)
("dest", dest)
("prev", prev)
("enemy", enemy)
("missile", missile)
("mate", mate)
("lastmate", last_mate)
("skill", skill)
("active", t_active)
("respawn", t_respawn)
("strafe", t_strafe)
("react", t_react)
("fight", t_fight)
("roam", t_roam)
("rocket", t_rocket)
("firstshot", first_shot)
("sleft", sleft)
("allround", allround)
("increase", increase)
("old", old);
}
void DBot::Tick ()
{
Super::Tick ();
if (player->mo == NULL || bglobal.freeze)
{
return;
}
BotThinkCycles.Clock();
bglobal.m_Thinking = true;
Think ();
bglobal.m_Thinking = false;
BotThinkCycles.Unclock();
}
CVAR (Int, bot_next_color, 11, 0)
CVAR (Bool, bot_observer, false, 0)
CCMD (addbot)
{
if (gamestate != GS_LEVEL && gamestate != GS_INTERMISSION)
{
Printf ("Bots cannot be added when not in a game!\n");
return;
}
if (!players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can add bots\n");
return;
}
if (argv.argc() > 2)
{
Printf ("addbot [botname] : add a bot to the game\n");
return;
}
if (argv.argc() > 1)
bglobal.SpawnBot (argv[1]);
else
bglobal.SpawnBot (NULL);
}
void FCajunMaster::ClearPlayer (int i, bool keepTeam)
{
if (players[i].mo)
{
players[i].mo->Destroy ();
players[i].mo = NULL;
}
botinfo_t *bot = botinfo;
while (bot && stricmp (players[i].userinfo.GetName(), bot->name))
bot = bot->next;
if (bot)
{
bot->inuse = BOTINUSE_No;
bot->lastteam = keepTeam ? players[i].userinfo.GetTeam() : TEAM_NONE;
}
if (players[i].Bot != NULL)
{
players[i].Bot->Destroy ();
players[i].Bot = NULL;
}
players[i].~player_t();
::new(&players[i]) player_t;
players[i].userinfo.Reset();
playeringame[i] = false;
}
CCMD (removebots)
{
if (!players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can remove bots\n");
return;
}
Net_WriteByte (DEM_KILLBOTS);
}
CCMD (freeze)
{
if (CheckCheatmode ())
return;
if (netgame && !players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can use freeze mode\n");
return;
}
Net_WriteByte (DEM_GENERICCHEAT);
Net_WriteByte (CHT_FREEZE);
}
CCMD (listbots)
{
botinfo_t *thebot = bglobal.botinfo;
int count = 0;
while (thebot)
{
Printf ("%s%s\n", thebot->name, thebot->inuse == BOTINUSE_Yes ? " (active)" : "");
thebot = thebot->next;
count++;
}
Printf ("> %d bots\n", count);
}
// set the bot specific weapon information
// This is intentionally not in the weapon definition anymore.
void InitBotStuff()
{
static struct BotInit
{
const char *type;
int movecombatdist;
int weaponflags;
const char *projectile;
} botinits[] = {
{ "Pistol", 25000000, 0, NULL },
{ "Shotgun", 24000000, 0, NULL },
{ "SuperShotgun", 15000000, 0, NULL },
{ "Chaingun", 27000000, 0, NULL },
{ "RocketLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "Rocket" },
{ "PlasmaRifle", 27000000, 0, "PlasmaBall" },
{ "BFG9000", 10000000, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_BFG, "BFGBall" },
{ "GoldWand", 25000000, 0, NULL },
{ "GoldWandPowered", 25000000, 0, NULL },
{ "Crossbow", 24000000, 0, "CrossbowFX1" },
{ "CrossbowPowered", 24000000, 0, "CrossbowFX2" },
{ "Blaster", 27000000, 0, NULL },
{ "BlasterPowered", 27000000, 0, "BlasterFX1" },
{ "SkullRod", 27000000, 0, "HornRodFX1" },
{ "SkullRodPowered", 27000000, 0, "HornRodFX2" },
{ "PhoenixRod", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "PhoenixFX1" },
{ "Mace", 27000000, WIF_BOT_REACTION_SKILL_THING, "MaceFX2" },
{ "MacePowered", 27000000, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "MaceFX4" },
{ "FWeapHammer", 22000000, 0, "HammerMissile" },
{ "FWeapQuietus", 20000000, 0, "FSwordMissile" },
{ "CWeapStaff", 25000000, 0, "CStaffMissile" },
{ "CWeapFlane", 27000000, 0, "CFlameMissile" },
{ "MWeapWand", 25000000, 0, "MageWandMissile" },
{ "CWeapWraithverge", 22000000, 0, "HolyMissile" },
{ "MWeapFrost", 19000000, 0, "FrostMissile" },
{ "MWeapLightning", 23000000, 0, "LightningFloor" },
{ "MWeapBloodscourge", 20000000, 0, "MageStaffFX2" },
{ "StrifeCrossbow", 24000000, 0, "ElectricBolt" },
{ "StrifeCrossbow2", 24000000, 0, "PoisonBolt" },
{ "AssaultGun", 27000000, 0, NULL },
{ "MiniMissileLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "MiniMissile" },
{ "FlameThrower", 24000000, 0, "FlameMissile" },
{ "Mauler", 15000000, 0, NULL },
{ "Mauler2", 10000000, 0, "MaulerTorpedo" },
{ "StrifeGrenadeLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "HEGrenade" },
{ "StrifeGrenadeLauncher2", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "PhosphorousGrenade" },
};
for(unsigned i=0;i<sizeof(botinits)/sizeof(botinits[0]);i++)
{
const PClass *cls = PClass::FindClass(botinits[i].type);
if (cls != NULL && cls->IsDescendantOf(NAME_Weapon))
{
AWeapon *w = (AWeapon*)GetDefaultByType(cls);
if (w != NULL)
{
w->MoveCombatDist = botinits[i].movecombatdist/65536.;
w->WeaponFlags |= botinits[i].weaponflags;
w->ProjectileType = PClass::FindActor(botinits[i].projectile);
}
}
}
static const char *warnbotmissiles[] = { "PlasmaBall", "Ripper", "HornRodFX1" };
for(unsigned i=0;i<countof(warnbotmissiles);i++)
{
AActor *a = GetDefaultByName (warnbotmissiles[i]);
if (a != NULL)
{
a->flags3|=MF3_WARNBOT;
}
}
}
| 26.578947 | 111 | 0.672103 | raa-eruanna |
d18877b4a5906058307b3f59197c735faea752b0 | 2,724 | hpp | C++ | examples/suffix_sorting/construct_bwt.hpp | stevenybw/thrill | a2dc05035f4e24f64af0a22b60155e80843a5ba9 | [
"BSD-2-Clause"
] | 609 | 2015-08-27T11:09:24.000Z | 2022-03-28T21:34:05.000Z | examples/suffix_sorting/construct_bwt.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 109 | 2015-09-10T21:34:42.000Z | 2022-02-15T14:46:26.000Z | examples/suffix_sorting/construct_bwt.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 114 | 2015-08-27T14:54:13.000Z | 2021-12-08T07:28:35.000Z | /*******************************************************************************
* examples/suffix_sorting/construct_bwt.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
#define THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
#include <thrill/api/collapse.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/max.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/api/zip_with_index.hpp>
namespace examples {
namespace suffix_sorting {
template <typename InputDIA, typename SuffixArrayDIA>
InputDIA ConstructBWT(const InputDIA& input, const SuffixArrayDIA& suffix_array,
uint64_t input_size) {
// thrill::Context& ctx = input.ctx();
using Char = typename InputDIA::ValueType;
using Index = typename SuffixArrayDIA::ValueType;
struct IndexRank {
Index index;
Index rank;
} TLX_ATTRIBUTE_PACKED;
struct IndexChar {
Index index;
Char ch;
} TLX_ATTRIBUTE_PACKED;
return suffix_array
.Map([input_size](const Index& i) {
if (i == Index(0))
return Index(input_size - 1);
return i - Index(1);
})
.ZipWithIndex([](const Index& text_pos, const size_t& i) {
return IndexRank { text_pos, Index(i) };
})
// .Zip(Generate(ctx, input_size),
// [](const Index& text_pos, const size_t& idx) {
// return IndexRank { text_pos, Index(idx) };
// })
.Sort([](const IndexRank& a, const IndexRank& b) {
return a.index < b.index;
})
.Zip(input,
[](const IndexRank& text_order, const Char& ch) {
return IndexChar { text_order.rank, ch };
})
.Sort([](const IndexChar& a, const IndexChar& b) {
return a.index < b.index;
})
.Map([](const IndexChar& ic) {
return ic.ch;
})
.Collapse();
}
} // namespace suffix_sorting
} // namespace examples
#endif // !THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
/******************************************************************************/
| 33.62963 | 80 | 0.532305 | stevenybw |
d1935945395c81611d54a5935c2822f403fe555a | 545 | cc | C++ | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | // Copyright (c) 2020 [Your Name]. All rights reserved.
#include <cinder/app/App.h>
#include <mylibrary/ObjectInfo.h>
#include <string>
namespace mylibrary {
ObjectInfo::ObjectInfo(std::string name, cinder::Color color,
cinder::vec3 position, int type) {
mName = name;
mColor = color;
mPosition = position;
mType = type;
}
ObjectInfo::ObjectInfo() {
mName = "random object";
mColor = cinder::Color(0.34f, 0.78f, 1.0f);
mPosition = cinder::vec3(0, 5, 0);
mType = rand() % 2;
}
} // namespace mylibrary | 22.708333 | 61 | 0.645872 | CS126SP20 |
d1967ca07239d426d07f5bad59f6a32e325ad75b | 3,120 | cc | C++ | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | 2 | 2019-07-15T08:34:38.000Z | 2019-08-07T12:27:23.000Z | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | /*
* @Author: py.wang
* @Date: 2019-07-21 08:21:33
* @Last Modified by: py.wang
* @Last Modified time: 2019-07-22 08:42:22
*/
#include "src/net/Buffer.h"
#include "src/net/http/HttpContext.h"
using namespace slack;
using namespace slack::net;
// 解析请求行
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
bool succeed = false;
const char *start = begin;
const char *space = std::find(start, end, ' ');
// find method
if (space != end && request_.setMethod(start, space))
{
start = space + 1;
space = std::find(start, end, ' ');
// find path
if (space != end)
{
const char *question = std::find(start, space, '?');
// find query
if (question != space)
{
request_.setPath(start, question);
request_.setQuery(question, space);
}
else
{
request_.setPath(start, space);
}
start = space + 1;
succeed = (end - start == 8) && std::equal(start, end-1, "HTTP/1.");
if (succeed)
{
if (*(end-1) == '1')
{
request_.setVersion(HttpRequest::kHttp11);
}
else if (*(end-1) == '0')
{
request_.setVersion(HttpRequest::kHttp10);
}
else
{
succeed = false;
}
}
}
}
return succeed;
}
bool HttpContext::parseRequest(Buffer *buf, Timestamp receiveTime)
{
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (state_ == kExpectRequestLine)
{
const char *crlf = buf->findCRLF();
if (crlf)
{
// 解析请求行
ok = processRequestLine(buf->peek(), crlf);
if (ok)
{
request_.setReceiveTime(receiveTime);
buf->retrieveUntil(crlf+2);
state_ = kExpectHeaders;
}
else
{
hasMore = false;
}
}
else
{
hasMore = false;
}
}
else if (state_ == kExpectHeaders)
{
const char *crlf = buf->findCRLF();
if (crlf)
{
const char *colon = std::find(buf->peek(), crlf, ':');
if (colon != crlf)
{
request_.addHeader(buf->peek(), colon, crlf);
}
else
{
// empty line, end of header
state_ = kGotAll;
hasMore = false;
}
buf->retrieveUntil(crlf+2);
}
else
{
hasMore = false;
}
}
else if (state_ == kExpectBody)
{
}
}
return ok;
} | 26.440678 | 80 | 0.403526 | plantree |
d19d6d8b431259cfd6d59b75185b11f379b835c0 | 845 | cpp | C++ | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | 1 | 2022-03-01T21:06:30.000Z | 2022-03-01T21:06:30.000Z | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | null | null | null | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | null | null | null | // ChessTree.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <chrono>
#include <Windows.h>
#include "Log.h"
#include "Engine.h"
#include "XboardCommand.h"
#ifdef _WIN32
#define CMD_CLEAR_SCREEN "cls"
#elif
#define CMD_CLEAR_SCREEN "clear"
#endif
typedef std::chrono::high_resolution_clock::time_point Timepoint;
void idea3() {
std::string input, output;
chess::Engine engine;
chess::XboardCommand command(engine);
while (1) {
Sleep(200); // for some reason
std::getline(std::cin, input);
Log::add("input: " + input);
if (command.process(input, output) == false) {
break;
}
Log::add("output: " + output);
if (!output.empty()) {
std::cout << output << std::endl;
}
}
}
int main()
{
Log::begin();
idea3();
Log::end();
return 0;
} | 15.648148 | 99 | 0.657988 | pradeepdsmk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.