hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8170f0018e70661b2b0a55dbf3b4ac069321ca55 | 1,318 | cpp | C++ | ALGORITHMS/Dynamic Programming/DP_06_Path_With_Max_Goldmine.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | ALGORITHMS/Dynamic Programming/DP_06_Path_With_Max_Goldmine.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | ALGORITHMS/Dynamic Programming/DP_06_Path_With_Max_Goldmine.cpp | compl3xX/ROAD-TO-DSA | 2261c112135a51d9d88c4b57e6f062f6b32550a7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int collectGold(int n, int m, vector<vector<int>> &arr, vector<vector<int>> &dp)
{
for (int j = arr[0].size() - 1; j >= 0; j--)
{
for (int i = arr.size() - 1; i >= 0; i--)
{
if (j == arr[0].size() - 1)
{
dp[i][j] = arr[i][j];
}
else if (i == 0)
{
dp[i][j] = arr[i][j] + max(dp[i][j + 1], dp[i + 1][j + 1]);
}
else if (i == arr.size() - 1)
{
dp[i][j] = arr[i][j] + max(dp[i][j + 1], dp[i - 1][j + 1]);
}
else
{
int mxofd = max(dp[i + 1][j + 1], dp[i - 1][j + 1]);
dp[i][j] = arr[i][j] + max(dp[i][j + 1], mxofd);
}
}
}
int max = dp[0][0];
for (int i = 1; i < dp.size(); i++)
{
if (dp[i][0] > max)
{
max = dp[i][0];
}
}
return max;
}
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> arr(n, vector<int>(m));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> arr[i][j];
}
}
vector<vector<int>> dp(n, vector<int>(m));
cout << collectGold(n, m, arr, dp);
} | 21.966667 | 80 | 0.336115 | [
"vector"
] |
8171f6010c8ead39cf0ce75dbafa679f48a40acb | 1,626 | cpp | C++ | src/sm/StateMachine.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 2 | 2016-05-21T03:09:19.000Z | 2016-08-27T03:40:51.000Z | src/sm/StateMachine.cpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 75 | 2017-10-08T22:21:19.000Z | 2020-03-30T21:13:20.000Z | src/sm/StateMachine.cpp | StratifyLabs/StratifyLib | 975a5c25a84296fd0dec64fe4dc579cf7027abe6 | [
"MIT"
] | 5 | 2018-03-27T16:44:09.000Z | 2020-07-08T16:45:55.000Z | /*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include "sm/StateMachine.hpp"
using namespace sm;
Object::Object(StateMachine & state_machine) : m_state_machine(state_machine){
//the object needs to be added to the state machines lists
switch(type()){
case TYPE_STATE: m_state_machine.append_state(*this); break;
case TYPE_CONDITION: m_state_machine.append_condition(*this); break;
case TYPE_ACTION: m_state_machine.append_action(*this); break;
case TYPE_OBJECT:
case TYPE_MACHINE:
break;
}
}
StateMachine::StateMachine() : Object(*this) {
}
void StateMachine::set_state(const char * name){
}
void StateMachine::set_state(const State * state){
//make sure the state is in the list of states
}
void StateMachine::generate_dot_code(){
//go over the state list and show transitions
}
void StateMachine::execute(){
State * next_state;
if( active_state() ){
active_state()->execute_entry_action();
}
do {
execute_action(); //execute machine level actions
//execute the active state actions
active_state()->execute_action();
//check for exit conditions to transition to new states
next_state = active_state()->check_exit_condition();
if( next_state != active_state() ){
//debug output for a transition
set_state(next_state);
}
} while( active_state() );
}
void State::execute_action(){
//execute the actions in the list
}
void State::execute_entry_action(){
//execute actions in entry list
}
State * State::check_exit_condition(){
//check for exit conditions and set appropriate actions
return this;
}
| 20.582278 | 100 | 0.729397 | [
"object"
] |
40c45910e5a7adcabb671a1868cb259dc45a338e | 9,186 | cpp | C++ | StreamRecorder/SensorScenario.cpp | ozgunkaratas/mastersthesis | 3ea3ae99744292620d26f4a3595370f4709c6eda | [
"MIT"
] | 1 | 2021-10-06T08:02:46.000Z | 2021-10-06T08:02:46.000Z | StreamRecorder/SensorScenario.cpp | ozgunkaratas/mastersthesis | 3ea3ae99744292620d26f4a3595370f4709c6eda | [
"MIT"
] | null | null | null | StreamRecorder/SensorScenario.cpp | ozgunkaratas/mastersthesis | 3ea3ae99744292620d26f4a3595370f4709c6eda | [
"MIT"
] | null | null | null | #include "SensorScenario.h"
extern "C"
HMODULE LoadLibraryA(
LPCSTR lpLibFileName
);
static ResearchModeSensorConsent camAccessCheck;
static HANDLE camConsentGiven;
static ResearchModeSensorConsent imuAccessCheck;
static HANDLE imuConsentGiven;
//constr
SensorScenario::SensorScenario(const std::vector<ResearchModeSensorType>& kEnabledSensorTypes) : m_kEnabledSensorTypes(kEnabledSensorTypes)
{
}
//deconstr
//release all sensors and dont reach them anymore
SensorScenario::~SensorScenario()
{
if (m_pLFCameraSensor)
{
m_pLFCameraSensor->Release();
}
if (m_pRFCameraSensor)
{
m_pRFCameraSensor->Release();
}
if (m_pLLCameraSensor)
{
m_pLLCameraSensor->Release();
}
if (m_pRRCameraSensor)
{
m_pRRCameraSensor->Release();
}
if (m_pLTSensor)
{
m_pLTSensor->Release();
}
if (m_pAHATSensor)
{
m_pAHATSensor->Release();
}
if (m_pAccelSensor)
{
m_pAccelSensor->Release();
}
if (m_pGyroSensor)
{
m_pGyroSensor->Release();
}
if (m_pMagSensor)
{
m_pMagSensor->Release();
}
if (m_pSensorDevice)
{
m_pSensorDevice->EnableEyeSelection();
m_pSensorDevice->Release();
}
if (m_pSensorDeviceConsent)
{
m_pSensorDeviceConsent->Release();
}
}
//for spatial reference purposes
//used for cameras
void SensorScenario::GetRigNodeId(GUID& outGuid) const
{
IResearchModeSensorDevicePerception* pSensorDevicePerception;
winrt::check_hresult(m_pSensorDevice->QueryInterface(IID_PPV_ARGS(&pSensorDevicePerception)));
winrt::check_hresult(pSensorDevicePerception->GetRigNodeId(&outGuid));
pSensorDevicePerception->Release();
}
//this will initialize all of the sensors
void SensorScenario::InitializeSensors()
{
size_t sensorCount = 0;
//given that the user has said okay for conset
camConsentGiven = CreateEvent(nullptr, true, false, nullptr);
imuConsentGiven = CreateEvent(nullptr, true, false, nullptr);
// Load Research Mode library
HMODULE hrResearchMode = LoadLibraryA("ResearchModeAPI");
if (hrResearchMode)
{
typedef HRESULT(__cdecl* PFN_CREATEPROVIDER) (IResearchModeSensorDevice** ppSensorDevice);
PFN_CREATEPROVIDER pfnCreate = reinterpret_cast<PFN_CREATEPROVIDER>(GetProcAddress(hrResearchMode, "CreateResearchModeSensorDevice"));
if (pfnCreate)
{
winrt::check_hresult(pfnCreate(&m_pSensorDevice));
}
}
// Manage Sensor Consent
winrt::check_hresult(m_pSensorDevice->QueryInterface(IID_PPV_ARGS(&m_pSensorDeviceConsent)));
winrt::check_hresult(m_pSensorDeviceConsent->RequestCamAccessAsync(SensorScenario::CamAccessOnComplete));
winrt::check_hresult(m_pSensorDeviceConsent->RequestIMUAccessAsync(SensorScenario::ImuAccessOnComplete));
//some fundamental initialization
m_pSensorDevice->DisableEyeSelection();
m_pSensorDevice->GetSensorCount(&sensorCount);
m_sensorDescriptors.resize(sensorCount);
m_pSensorDevice->GetSensorDescriptors(m_sensorDescriptors.data(), m_sensorDescriptors.size(), &sensorCount);
//the Researchmode interface has the ability to
//query what type of sensor we are using
//here, a loop checks all of the sensors
//that are currently active
for (auto& sensorDescriptor : m_sensorDescriptors)
{
if (sensorDescriptor.sensorType == LEFT_FRONT)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), LEFT_FRONT) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pLFCameraSensor));
}
if (sensorDescriptor.sensorType == RIGHT_FRONT)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), RIGHT_FRONT) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pRFCameraSensor));
}
if (sensorDescriptor.sensorType == LEFT_LEFT)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), LEFT_LEFT) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pLLCameraSensor));
}
if (sensorDescriptor.sensorType == RIGHT_RIGHT)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), RIGHT_RIGHT) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pRRCameraSensor));
}
if (sensorDescriptor.sensorType == DEPTH_LONG_THROW)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), DEPTH_LONG_THROW) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pLTSensor));
}
if (sensorDescriptor.sensorType == DEPTH_AHAT)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), DEPTH_AHAT) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pAHATSensor));
}
//IMU individual start-ups below
//for accel
if (sensorDescriptor.sensorType == IMU_ACCEL)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), IMU_ACCEL) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pAccelSensor));
}
//for gyr
if (sensorDescriptor.sensorType == IMU_GYRO)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), IMU_GYRO) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pGyroSensor));
}
//for mag
if (sensorDescriptor.sensorType == IMU_MAG)
{
if (std::find(m_kEnabledSensorTypes.begin(), m_kEnabledSensorTypes.end(), IMU_MAG) == m_kEnabledSensorTypes.end())
{
continue;
}
winrt::check_hresult(m_pSensorDevice->GetSensor(sensorDescriptor.sensorType, &m_pMagSensor));
}
}
}
//consent
void SensorScenario::CamAccessOnComplete(ResearchModeSensorConsent consent)
{
camAccessCheck = consent;
SetEvent(camConsentGiven);
}
//consent
void SensorScenario::ImuAccessOnComplete(ResearchModeSensorConsent consent)
{
imuAccessCheck = consent;
SetEvent(imuConsentGiven);
}
//this step will initialize the cameras
//whatever has been given in main.cpp as enum will
//pop up here
void SensorScenario::InitializeCameraReaders()
{
// Get RigNode id which will be used to initialize
// the spatial locators for camera readers objects
GUID guid;
GetRigNodeId(guid);
if (m_pLFCameraSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pLFCameraSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
if (m_pRFCameraSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pRFCameraSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
if (m_pLLCameraSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pLLCameraSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
if (m_pRRCameraSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pRRCameraSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
if (m_pLTSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pLTSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
if (m_pAHATSensor)
{
auto cameraReader = std::make_shared<RMCameraReader>(m_pAHATSensor, camConsentGiven, &camAccessCheck, guid);
m_cameraReaders.push_back(cameraReader);
}
}
void SensorScenario::InitializeIMU()
{
//fire up the IMUS
// i dont know if i need to
//create the same pushback on vectors
//as the cameras
if (m_pAccelSensor)
{
m_Accel = std::make_shared<Accel>(m_pAccelSensor, imuConsentGiven, &imuAccessCheck);
}
if (m_pGyroSensor)
{
m_Gyro = std::make_shared<Gyro>(m_pGyroSensor, imuConsentGiven, &imuAccessCheck);
}
if (m_pMagSensor)
{
m_Mag = std::make_shared<Mag>(m_pMagSensor, imuConsentGiven, &imuAccessCheck);
}
}
//a storage folder is created in which the streams will be recorded
void SensorScenario::StartRecording(const winrt::Windows::Storage::StorageFolder& folder,
const winrt::Windows::Perception::Spatial::SpatialCoordinateSystem& worldCoordSystem)
{
for (int i = 0; i < m_cameraReaders.size(); ++i)
{
m_cameraReaders[i]->SetWorldCoordSystem(worldCoordSystem);
m_cameraReaders[i]->SetStorageFolder(folder);
}
//sets the IMU storage folder for
//accel+gyro+mag at the same time
m_Accel->AccelSetStorageFolder(folder);
m_Gyro->GyroSetStorageFolder(folder);
m_Mag->MagSetStorageFolder(folder);
}
//when it stops recording
//it will both cut the recording for
//RM sensors and non-RM sensors
//but these are done in different files
void SensorScenario::StopRecording()
{
for (int i = 0; i < m_cameraReaders.size(); ++i)
{
m_cameraReaders[i]->ResetStorageFolder();
}
//resets the IMU storage folder for
//accel+gyro+mag at the same time
m_Accel->AccelResetStorageFolder();
m_Gyro->GyroResetStorageFolder();
m_Mag->MagResetStorageFolder();
}
| 26.096591 | 139 | 0.758763 | [
"vector"
] |
40cd799f8fbf133fb9bdab34dbf0fb2ac1911b77 | 756 | cpp | C++ | Kodovi/src/Instruction.cpp | ssttefann/Visualizing-Sorting-Algorithms | 0946bb8e743ef98e318db3c8f478898447520937 | [
"MIT"
] | null | null | null | Kodovi/src/Instruction.cpp | ssttefann/Visualizing-Sorting-Algorithms | 0946bb8e743ef98e318db3c8f478898447520937 | [
"MIT"
] | null | null | null | Kodovi/src/Instruction.cpp | ssttefann/Visualizing-Sorting-Algorithms | 0946bb8e743ef98e318db3c8f478898447520937 | [
"MIT"
] | null | null | null | #include "Instruction.h"
#include <Windows.h>
#include <MMSystem.h>
#include "GUI.h"
#include "Graph.h"
void ColorChange::do_it()
//changes the color of a widget representing a flight
{
vf->boja = this->color;
}
void WidgetSwap::do_it()
//swaps the places of two widgets
{
int x1, x2;
x1 = vf2->x() - vf->x();
x2 = vf->x() - vf2->x();
vf->move(x1, 0);
vf2->move(x2, 0);
//redraw of window should be called after this function
}
void ColorSwap::do_it()
//changes the color of two widgets at the same time
{
vf->boja = this->color1;
vf2->boja = this->color2;
}
void RevertColor::do_it()
//changes the color of multiple widgets to the specified Fl_Color
{
for (int i = 0; i < vector.size(); i++) {
vector[i]->boja = color;
}
}
| 17.581395 | 66 | 0.64418 | [
"vector"
] |
40cffcacc597e5509230ec8fd21d9d7d1a9c58a7 | 4,160 | cpp | C++ | client/ctHive/ILMSDK/source/LibraryModuleBase.cpp | ThERisEn/hack-bundle-tampermonkey | beaddcc600c3ea2ed689488291f9b7c878e80dee | [
"MIT"
] | null | null | null | client/ctHive/ILMSDK/source/LibraryModuleBase.cpp | ThERisEn/hack-bundle-tampermonkey | beaddcc600c3ea2ed689488291f9b7c878e80dee | [
"MIT"
] | null | null | null | client/ctHive/ILMSDK/source/LibraryModuleBase.cpp | ThERisEn/hack-bundle-tampermonkey | beaddcc600c3ea2ed689488291f9b7c878e80dee | [
"MIT"
] | 4 | 2019-07-11T21:17:12.000Z | 2022-02-02T03:13:42.000Z | /*-****************************************************************************
$Archive: SinnerTwin/JY008C637-ILM_SDK/source/LibraryModuleBase.cpp$
$Revision: 1$
$Date: Wednesday, March 17, 2010 4:26:17 PM$
$Author: sarahs$
Template: cpp_file.cpp 3.0
CPRCLASS = "PROPRIETARY LEVEL I"
*******************************************************************************
*/
/*----------------- LibraryModuleBase - FILE DESCRIPTION -----------------*
Implementation of the LibraryModuleBase class and the endpoint handler redirection
functions.
*/
/* $NoKeywords$ (No rcs replacement keywords below this point) */
/*----------------- LibraryModuleBase - INCLUDES -------------------------*/
#include <vector>
#include <sstream>
#include "LibraryModuleBase.h"
#include "CustomCommand.h"
/*----------------- LibraryModuleBase - DECLARATIONS ----------------------*/
using namespace InterfaceLibrary;
using namespace InterfaceLibrary::Primitive;
static String noHandlerDefinedErrMsg("Error: The ILM target has no handler object defined");
extern "C" DLL_EXPORT InterfaceLibrary::String initializeExt(InterfaceLibrary::uint32 mode, InterfaceLibrary::uint32 version) ;
/*==========================================================================*/
LibraryModuleBase* LibraryModuleBase::handlerObject = NULL;
CTInstance* LibraryModuleBase::callback = NULL;
Dl_info LibraryModuleBase::sharedObjectInfo;
LibraryModuleBase::LibraryModuleBase()
{
if(handlerObject==NULL) {
// The first instance created has some housekeeping to do
handlerObject = this;
dladdr((void *)( initializeExt), &sharedObjectInfo) ;
callback = new CTInstance();
}
}
LibraryModuleBase::~LibraryModuleBase()
{
if (handlerObject==this) {
delete callback;
handlerObject=NULL;
}
}
String LibraryModuleBase::InitializeExt(uint32 mode, uint32 version)
{
ctMode = mode;
ctVersion = version;
return "";
}
String LibraryModuleBase::Shutdown(void)
{
return "";
}
vector<Validator> LibraryModuleBase::ValidatePrimitives(void) const
{
return primitiveRefTable.GetSupportedPrimitives();
}
const CustomCommandSet& LibraryModuleBase::AddCommands(void) const
{
return customCommands;
}
ProcessCmdResponse LibraryModuleBase::ProcessCmd (vector<Activation>& activations)
{
ProcessCmdResponse retVal;
ProcessCmdAccumulator accum;
for (size_t i=0; i<activations.size() && retVal.type.empty(); i++) {
RefTableEntry* primRef = primitiveRefTable[activations[i].primitiveID];
if (primRef->handler==NULL) {
std::stringstream errmsg;
errmsg << "The ILM has not defined a handler function for command primitive "
<< primRef->primitiveID << "; this primitive was skipped.";
retVal.resultsLines.push_back(ProcessCmdResponse::Line(0, errmsg.str().c_str()));
retVal.type = ProcessCmdResponse::TYPE_Local_Failure;
} else {
// Once again in this God-forsaken interface definition, we must deal with
// void pointers (hidden in the activations' arguments). Catching everything
// so as to deal with problems as gracefully as possible.
// TODO: Will probably want to catch more types; specifically, we'll probably
// want to make exception types for Local and Remote failures, and give the
// handlers the option of throwing these for convenience.
try {
primRef->handler(activations[i], accum, retVal);
} catch (...) {
std::stringstream errmsg;
errmsg << "Unknown error encountered when calling handler for primitive "
<< primRef->primitiveID;
retVal.resultsLines.push_back(ProcessCmdResponse::Line(0, errmsg.str().c_str()));
retVal.type = ProcessCmdResponse::TYPE_Local_Failure;
}
}
}
// If nobody set the type element, go ahead and assume "Success"
if (retVal.type.empty()) {
retVal.type = ProcessCmdResponse::TYPE_Success;
}
return retVal;
}
| 33.015873 | 128 | 0.620673 | [
"object",
"vector"
] |
40d148803959a4208f737f5fadec6f8df26c597d | 1,491 | cpp | C++ | aws-cpp-sdk-fsx/source/model/DeleteFileSystemRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-fsx/source/model/DeleteFileSystemRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-fsx/source/model/DeleteFileSystemRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2020-11-04T03:18:11.000Z | 2020-11-04T03:18:11.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/fsx/model/DeleteFileSystemRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::FSx::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteFileSystemRequest::DeleteFileSystemRequest() :
m_fileSystemIdHasBeenSet(false),
m_clientRequestToken(Aws::Utils::UUID::RandomUUID()),
m_clientRequestTokenHasBeenSet(true),
m_windowsConfigurationHasBeenSet(false),
m_lustreConfigurationHasBeenSet(false)
{
}
Aws::String DeleteFileSystemRequest::SerializePayload() const
{
JsonValue payload;
if(m_fileSystemIdHasBeenSet)
{
payload.WithString("FileSystemId", m_fileSystemId);
}
if(m_clientRequestTokenHasBeenSet)
{
payload.WithString("ClientRequestToken", m_clientRequestToken);
}
if(m_windowsConfigurationHasBeenSet)
{
payload.WithObject("WindowsConfiguration", m_windowsConfiguration.Jsonize());
}
if(m_lustreConfigurationHasBeenSet)
{
payload.WithObject("LustreConfiguration", m_lustreConfiguration.Jsonize());
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteFileSystemRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSSimbaAPIService_v20180301.DeleteFileSystem"));
return headers;
}
| 22.590909 | 110 | 0.7666 | [
"model"
] |
40d2bb9400811dfe0431de8206e7fbd7aac32a7b | 2,870 | hpp | C++ | vm/exception.hpp | larrytheliquid/rubinius | 5af42280ab95626f33517ca5f6330e17be04ec64 | [
"BSD-3-Clause"
] | 1 | 2015-11-05T03:49:26.000Z | 2015-11-05T03:49:26.000Z | vm/exception.hpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | 1 | 2022-03-12T14:09:00.000Z | 2022-03-12T14:09:00.000Z | vm/exception.hpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | 1 | 2022-03-12T12:08:44.000Z | 2022-03-12T12:08:44.000Z | #ifndef RBX_EXCEPTION_HPP
#define RBX_EXCEPTION_HPP
#include <string>
#include <cstdlib>
#include <cstring>
#include "object_types.hpp"
#include "prelude.hpp"
#include "builtin/object.hpp"
namespace rubinius {
class Exception;
void abort();
void print_backtrace();
/**
* Base class for the various exception.
*
* Each exception class should define a +raise+ function. Code
* should call the +raise+ function instead of throwing one of
* the exceptions directly. This allows setting a breakpoint
* on +raise+ to more easily debug exceptions. For example, to
* cause a Assertion exception, use
*
* Assertion::raise(type, obj, reason);
*
* instead of
*
* throw Assertion(type, obj, reason);
*/
class VMException {
public: /* Instance vars */
typedef std::vector<std::string> Backtrace;
Backtrace* backtrace;
char* reason;
public: /* Ctors */
VMException(bool make_backtrace = true);
VMException(const char* reason, bool make_backtrace = true);
~VMException() { if(reason) free(reason); }
public: /* Interface */
void print_backtrace();
};
/**
* An assertion in the VM failed for the given +reason+.
* Only use this exception if there is no possible hope
* of handling the condition in Ruby-land. Otherwise, use:
*
* Exception::assertion_error(state, reason);
*/
class Assertion : public VMException {
public: /* Ctors */
/**
* Use Assertion::raise to throw an Assertion exception.
*/
Assertion(const char* reason) : VMException(reason) { }
public: /* Interface */
/**
* Throws an Assertion exception with explanation +reason+.
*/
static void raise(const char* reason);
};
class TypeError : public VMException {
public: /* Instance vars */
object_type type;
Object* object;
public: /* Ctors */
TypeError(object_type type, Object* obj, const char* reason = NULL)
: VMException(reason), type(type), object(obj) { }
public: /* Interface */
static void raise(object_type type, Object* obj, const char* reason = NULL);
};
/**
* Any exceptional VM condition that can be handled in Ruby-land
* should be propagated using a RubyException. However, instead
* of using this exception directly, use the appropriate static
* method on the builtin class Exception.
*/
class RubyException : public VMException {
public: /* Instance vars */
Exception* exception;
public: /* Ctors */
RubyException(Exception* exception, bool make_backtrace);
public: /* Interface */
static void raise(Exception* exception, bool make_backtrace = false);
/**
* Prints out the exception message and the Ruby backtrace.
* Also prints the VM backtrace if it was generated.
*/
void show(STATE);
};
};
#endif
| 24.117647 | 80 | 0.658885 | [
"object",
"vector"
] |
40d437a90917c900904f9a867a8aa16cd0cec4c9 | 533 | cpp | C++ | ABC/abc087/c.cpp | EnsekiTT/atcoder | 6b40332d1b2493d1b6c00c9f1912895a67a3bbcb | [
"MIT"
] | null | null | null | ABC/abc087/c.cpp | EnsekiTT/atcoder | 6b40332d1b2493d1b6c00c9f1912895a67a3bbcb | [
"MIT"
] | null | null | null | ABC/abc087/c.cpp | EnsekiTT/atcoder | 6b40332d1b2493d1b6c00c9f1912895a67a3bbcb | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include<vector>
#include<numeric>
using namespace std;
int main()
{
int N;
cin >> N;
vector<int> A1(N), A2(N);
for(int i=0; i<N; ++i){
cin >> A1[i];
}
for(int i=0; i<N; ++i){
cin >> A2[i];
}
int sum1, sum2, max_sum;
max_sum = 0;
for(int i=0; i<N; ++i){
sum1= accumulate(A1.begin(), A1.begin()+i+1, 0);;
sum2= accumulate(A2.begin()+i, A2.end(), 0);;
if(max_sum < (sum1+sum2)){
max_sum = sum1+sum2;
}
}
cout << max_sum << endl;
return 0;
}
| 17.193548 | 53 | 0.536585 | [
"vector"
] |
40d56773262831b6423419f45ff942ebc282367a | 1,401 | cpp | C++ | src/fsc/object/plane.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | 1 | 2018-11-26T19:06:52.000Z | 2018-11-26T19:06:52.000Z | src/fsc/object/plane.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | null | null | null | src/fsc/object/plane.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | null | null | null | //----------------------------------------------------------------------------------------------------------------------
// Copyright : (c) Julian Bouzas 2018
// License : BSD3-style (see LICENSE)
// Maintainer : Julian Bouzas - nnoell3[at]gmail.com
//----------------------------------------------------------------------------------------------------------------------
// STL
#include <memory>
// FSC
#include "base/vertices/square.hpp"
#include "base/polygon.hpp"
#include "plane.hpp"
namespace fsc {
namespace object {
Plane::Plane(unsigned int width, unsigned int height, float scale_factor, glm::vec4 color,
base::transformer::Translate translate, base::transformer::Scale scale, base::transformer::Rotate rotate, base::transformer::Model model) :
Complex(std::move(translate), std::move(scale), std::move(rotate), std::move(model)),
width_(std::move(width)),
height_(std::move(height)),
scale_factor_(std::move(scale_factor)),
color_(std::move(color)) {
for (unsigned int i = 0; i < width; ++i)
for (unsigned int j = 0; j < height; ++j)
AddObject(std::make_shared<base::Polygon>(base::vertices::GetSquare(), color_, true, base::transformer::Translate {{i, j, 0.0f}}, base::transformer::Scale {{scale_factor_, scale_factor_, scale_factor_}}));
}
Plane::~Plane() {
}
} // namespace object
} // namespace fsc | 41.205882 | 212 | 0.54818 | [
"object",
"model"
] |
40d920ac0013759d9ea407c3720c7a8cb289dc0e | 8,105 | cpp | C++ | examples/WebsocketExample.cpp | vectorgraphics/LspCpp | 19411f6ca65b24964f421024035a3d7ec36dc8b1 | [
"MIT"
] | null | null | null | examples/WebsocketExample.cpp | vectorgraphics/LspCpp | 19411f6ca65b24964f421024035a3d7ec36dc8b1 | [
"MIT"
] | null | null | null | examples/WebsocketExample.cpp | vectorgraphics/LspCpp | 19411f6ca65b24964f421024035a3d7ec36dc8b1 | [
"MIT"
] | null | null | null |
#include "LibLsp/JsonRpc/WebSocketServer.h"
#include "LibLsp/lsp/textDocument/signature_help.h"
#include "LibLsp/lsp/general/initialize.h"
#include "LibLsp/lsp/ProtocolJsonHandler.h"
#include "LibLsp/lsp/textDocument/typeHierarchy.h"
#include "LibLsp/lsp/AbsolutePath.h"
#include "LibLsp/lsp/textDocument/resolveCompletionItem.h"
#include <network/uri.hpp>
#include "LibLsp/JsonRpc/Endpoint.h"
#include "LibLsp/JsonRpc/stream.h"
#include "LibLsp/JsonRpc/TcpServer.h"
#include "LibLsp/lsp/textDocument/document_symbol.h"
#include "LibLsp/lsp/workspace/execute_command.h"
#include <boost/filesystem.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <boost/beast/version.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/dispatch.hpp>
#include "LibLsp/JsonRpc/Endpoint.h"
#include "LibLsp/JsonRpc/RemoteEndPoint.h"
#include "LibLsp/JsonRpc/stream.h"
#include "LibLsp/lsp/ProtocolJsonHandler.h"
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
//------------------------------------------------------------------------------
std::string _address = "127.0.0.1";
std::string _port = "9333";
using namespace std;
class DummyLog :public lsp::Log
{
public:
void log(Level level, std::wstring&& msg)
{
std::wcout << msg << std::endl;
};
void log(Level level, const std::wstring& msg)
{
std::wcout << msg << std::endl;
};
void log(Level level, std::string&& msg)
{
std::cout << msg << std::endl;
};
void log(Level level, const std::string& msg)
{
std::cout << msg << std::endl;
};
};
// Sends a WebSocket message and prints the response
class Client : public std::enable_shared_from_this<Client>
{
net::io_context ioc;
tcp::resolver resolver_;
websocket::stream<beast::tcp_stream> ws_;
beast::flat_buffer buffer_;
std::string host_;
std::string user_agent_;
std::shared_ptr < lsp::ProtocolJsonHandler > protocol_json_handler = std::make_shared< lsp::ProtocolJsonHandler>();
DummyLog _log;
std::shared_ptr<GenericEndpoint> endpoint = std::make_shared<GenericEndpoint>(_log);
std::shared_ptr<lsp::websocket_stream_wrapper> proxy_;
public:
RemoteEndPoint point;
public:
// Resolver and socket require an io_context
explicit
Client()
: resolver_(net::make_strand(ioc))
, ws_(net::make_strand(ioc)),point(protocol_json_handler, endpoint, _log)
{
proxy_ = std::make_shared<lsp::websocket_stream_wrapper>(ws_);
}
// Start the asynchronous operation
void
run(
char const* host,
char const* port, char const* user_agent)
{
// Save these for later
host_ = host;
user_agent_ = user_agent;
// Look up the domain name
resolver_.async_resolve(
host,
port,
beast::bind_front_handler(
&Client::on_resolve,
shared_from_this()));
std::thread([&]
{
ioc.run();
}).detach();
while (!point.IsWorking())
{
std::this_thread::sleep_for(std::chrono::milliseconds (50));
}
}
void
on_resolve(
beast::error_code ec,
tcp::resolver::results_type results)
{
if (ec)
return;
// Set the timeout for the operation
beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));
// Make the connection on the IP address we get from a lookup
beast::get_lowest_layer(ws_).async_connect(
results,
beast::bind_front_handler(
&Client::on_connect,
shared_from_this()));
}
void
on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type)
{
if (ec)
return;
// Turn off the timeout on the tcp_stream, because
// the websocket stream has its own timeout system.
beast::get_lowest_layer(ws_).expires_never();
// Set suggested timeout settings for the websocket
ws_.set_option(
websocket::stream_base::timeout::suggested(
beast::role_type::client));
// Set a decorator to change the User-Agent of the handshake
ws_.set_option(websocket::stream_base::decorator(
[=](websocket::request_type& req)
{
req.set(http::field::user_agent,
user_agent_.c_str());
}));
// Perform the websocket handshake
ws_.async_handshake(host_, "/",
beast::bind_front_handler(
&Client::on_handshake,
shared_from_this()));
}
void
on_handshake(beast::error_code ec)
{
if (ec)
return;
// Send the message
point.startProcessingMessages(proxy_, proxy_);
// Read a message into our buffer
ws_.async_read(
buffer_,
beast::bind_front_handler(
&Client::on_read,
shared_from_this()));
}
void
on_read(
beast::error_code ec,
std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if (ec)
return;
char* data = reinterpret_cast<char*>(buffer_.data().data());
std::vector<char> elements(data, data + bytes_transferred);
buffer_.clear();
proxy_->on_request.EnqueueAll(std::move(elements), false);
ws_.async_read(
buffer_,
beast::bind_front_handler(
&Client::on_read,
shared_from_this()));
}
void
on_close(beast::error_code ec)
{
if (ec)
return;
// If we get here then the connection is closed gracefully
// The make_printable() function helps print a ConstBufferSequence
std::cout << beast::make_printable(buffer_.data()) << std::endl;
}
};
class Server
{
public:
Server(const std::string& user_agent) : server(user_agent,_address, _port, protocol_json_handler, endpoint, _log)
{
server.point.registerHandler(
[&](const td_initialize::request& req)
{
td_initialize::response rsp;
CodeLensOptions code_lens_options;
code_lens_options.resolveProvider = true;
rsp.result.capabilities.codeLensProvider = code_lens_options;
return rsp;
});
std::thread([&]()
{
server.run();
}).detach();
}
~Server()
{
server.stop();
}
std::shared_ptr < lsp::ProtocolJsonHandler > protocol_json_handler = std::make_shared < lsp::ProtocolJsonHandler >();
DummyLog _log;
std::shared_ptr < GenericEndpoint > endpoint = std::make_shared<GenericEndpoint>(_log);
lsp::WebSocketServer server;
};
int main()
{
std::string user_agent = std::string(BOOST_BEAST_VERSION_STRING) +" websocket-server-async";
Server server(user_agent);
auto client = std::make_shared<Client>();
user_agent = std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-async";
client->run(_address.c_str(), _port.c_str(), user_agent.c_str());
td_initialize::request req;
auto rsp = client->point.waitResponse(req);
if (rsp)
{
std::cout << rsp->ToJson() << std::endl;
}
return 0;
}
| 27.289562 | 123 | 0.602097 | [
"vector"
] |
40da72cc87c241bd905406a22977ccd8520a6296 | 27,730 | cc | C++ | onnxruntime/core/optimizer/attention_fusion.cc | codemzs/onnxruntime | c69194ec4c8c9674368113aa6044d0db708cd813 | [
"MIT"
] | 1 | 2020-07-12T14:56:55.000Z | 2020-07-12T14:56:55.000Z | onnxruntime/core/optimizer/attention_fusion.cc | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | null | null | null | onnxruntime/core/optimizer/attention_fusion.cc | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | 2 | 2020-05-21T20:08:25.000Z | 2021-04-19T10:39:13.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/graph_utils.h"
#include "core/optimizer/initializer.h"
#include "core/optimizer/attention_fusion.h"
#include "core/optimizer/utils.h"
#include <cmath>
#define DEBUG_LOG(x) LOGS(logger, VERBOSE) << x
using namespace ONNX_NAMESPACE;
using namespace onnxruntime::common;
namespace onnxruntime {
static bool ValidateMatMulInitializer(const Graph& graph, const Node& matmul, int64_t hidden_size) {
const NodeArg& input_b = *(matmul.InputDefs()[1]);
if (!graph_utils::IsInitializer(graph, input_b.Name(), true)) {
return false;
}
return optimizer_utils::ValidateShape(input_b, {hidden_size, hidden_size});
}
static bool ValidateAddBiasInitializer(const Graph& graph, const Node& add, int64_t hidden_size) {
const NodeArg& input_b = *(add.InputDefs()[1]);
if (!graph_utils::IsInitializer(graph, input_b.Name(), true)) {
return false;
}
return optimizer_utils::ValidateShape(input_b, {hidden_size});
}
// Merge 1-D weights (q, k and v) by concanating them one by one.
template <typename T>
void MergeWeights(const T* q, const T* k, const T* v, std::vector<T>& result, int64_t element_count) {
for (int64_t i = 0; i < element_count; i++) {
result.push_back(*q);
q++;
}
for (int64_t i = 0; i < element_count; i++) {
result.push_back(*k);
k++;
}
for (int64_t i = 0; i < element_count; i++) {
result.push_back(*v);
v++;
}
}
// Merge 2-D weights (q, k and v) by concanating them row by row.
template <typename T>
void MergeMatMulWeights(const T* q_weight, const T* k_weight, const T* v_weight, std::vector<T>& result, int64_t hidden_size) {
const T* q = q_weight;
const T* k = k_weight;
const T* v = v_weight;
for (int64_t i = 0; i < hidden_size; i++, q += hidden_size, k += hidden_size, v += hidden_size) {
MergeWeights(q, k, v, result, hidden_size);
}
}
// Load q, k and v weights, and validate their data types.
static bool LoadQkvWeights(
Graph& graph,
const Node& q, const Node& k, const Node& v,
const ONNX_NAMESPACE::TensorProto*& q_tensor,
const ONNX_NAMESPACE::TensorProto*& k_tensor,
const ONNX_NAMESPACE::TensorProto*& v_tensor) {
if (!graph.GetInitializedTensor(q.InputDefs()[1]->Name(), q_tensor)) {
return false;
}
// Attention Op requires float or float16 weights.
const auto data_type = q_tensor->data_type();
if (data_type != ONNX_NAMESPACE::TensorProto_DataType_FLOAT &&
data_type != ONNX_NAMESPACE::TensorProto_DataType_FLOAT16) {
return false;
}
if (!graph.GetInitializedTensor(k.InputDefs()[1]->Name(), k_tensor) ||
data_type != k_tensor->data_type()) {
return false;
}
if (!graph.GetInitializedTensor(v.InputDefs()[1]->Name(), v_tensor) ||
data_type != v_tensor->data_type()) {
return false;
}
return true;
}
// Merge the weights of Q, K and V inputs for MatMul or Add (bias) into one input.
static NodeArg& MergeQkvWeights(Graph& graph, int64_t hidden_size,
const ONNX_NAMESPACE::TensorProto* q_tensor,
const ONNX_NAMESPACE::TensorProto* k_tensor,
const ONNX_NAMESPACE::TensorProto* v_tensor,
bool is_matmul) {
assert(nullptr != q_tensor);
assert(nullptr != k_tensor);
assert(nullptr != v_tensor);
Initializer q_initializer(*q_tensor, graph.ModelPath());
Initializer k_initializer(*k_tensor, graph.ModelPath());
Initializer v_initializer(*v_tensor, graph.ModelPath());
auto data_type = q_tensor->data_type();
ONNX_NAMESPACE::TensorProto initializer;
initializer.set_name(graph.GenerateNodeArgName(is_matmul ? "qkv_weights" : "qkv_bias"));
// Shape of weights for MatMul is (hidden_size, 3 * hidden_size)
// Shape of weights for Add bias is (3 * hidden_size)
if (is_matmul) {
initializer.add_dims(hidden_size);
}
initializer.add_dims(3 * hidden_size);
initializer.set_data_type(data_type);
const int64_t element_count = 3 * hidden_size * (is_matmul ? hidden_size : 1);
if (data_type == ONNX_NAMESPACE::TensorProto_DataType_FLOAT) {
const float* q_weight = q_initializer.data<float>();
const float* k_weight = k_initializer.data<float>();
const float* v_weight = v_initializer.data<float>();
std::vector<float> result;
result.reserve(element_count);
if (is_matmul) {
MergeMatMulWeights<float>(q_weight, k_weight, v_weight, result, hidden_size);
} else {
MergeWeights<float>(q_weight, k_weight, v_weight, result, hidden_size);
}
initializer.set_raw_data(result.data(), element_count * sizeof(float));
} else { // data_type == ONNX_NAMESPACE::TensorProto_DataType_FLOAT16
const MLFloat16* q_weight = q_initializer.data<MLFloat16>();
const MLFloat16* k_weight = k_initializer.data<MLFloat16>();
const MLFloat16* v_weight = v_initializer.data<MLFloat16>();
std::vector<MLFloat16> result;
result.reserve(element_count);
if (is_matmul) {
MergeMatMulWeights<MLFloat16>(q_weight, k_weight, v_weight, result, hidden_size);
} else {
MergeWeights<MLFloat16>(q_weight, k_weight, v_weight, result, hidden_size);
}
initializer.set_raw_data(result.data(), element_count * sizeof(MLFloat16));
}
return graph_utils::AddInitializer(graph, initializer);
}
// Add a Cast to convert Mask from int64 to int32.
static NodeArg& CastMaskToInt32(Graph& graph, NodeArg* mask_input, ProviderType provider_type) {
const TensorShapeProto* mask_shape = mask_input->Shape();
TypeProto mask_int32;
mask_int32.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT32);
auto dim0 = mask_int32.mutable_tensor_type()->mutable_shape()->add_dim();
*dim0 = mask_shape->dim(0);
auto dim1 = mask_int32.mutable_tensor_type()->mutable_shape()->add_dim();
*dim1 = mask_shape->dim(1);
auto& cast32 = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("Mask_Int32"), &mask_int32);
Node& node = graph.AddNode(graph.GenerateNodeName("MaskCast"),
"Cast",
"Cast mask from int64 to int32",
{mask_input},
{&cast32},
nullptr,
kOnnxDomain);
// Add attribute: "to" = 6
ONNX_NAMESPACE::AttributeProto to;
to.set_name("to");
to.set_type(ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INT);
to.set_i(static_cast<int64_t>(ONNX_NAMESPACE::TensorProto_DataType_INT32));
node.AddAttribute("to", to);
node.SetExecutionProviderType(provider_type);
return cast32;
}
static NodeArg& AddMaskReduceSum(Graph& graph, NodeArg* reduce_sum_input, TypeProto& output_type, ProviderType provider_type) {
NodeArg& reduce_sum_output = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName("MaskIndex_Int32"), &output_type);
const std::vector<NodeArg*> input_defs{reduce_sum_input};
const std::vector<NodeArg*> output_defs{&reduce_sum_output};
Node& node = graph.AddNode(
graph.GenerateNodeName("MaskIndex"),
"ReduceSum",
"Count number of words",
input_defs,
output_defs,
{},
kOnnxDomain);
// Add attribute: "axes" = [1]
ONNX_NAMESPACE::AttributeProto axes;
axes.set_name("axes");
axes.set_type(ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INTS);
axes.add_ints(1);
node.AddAttribute("axes", axes);
// Add attribute: "keepdims" = 0
ONNX_NAMESPACE::AttributeProto keepdims;
keepdims.set_name("keepdims");
keepdims.set_type(ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_INT);
keepdims.set_i(static_cast<int64_t>(0));
node.AddAttribute("keepdims", keepdims);
node.SetExecutionProviderType(provider_type);
return reduce_sum_output;
}
static NodeArg* ProcessMask(Graph& graph, NodeArg* mask_input, ProviderType provider_type, const logging::Logger& logger) {
// Validate mask input shape (batch_size, sequence_length) and data type.
// Note that batch_size and sequence_length could be symbolic.
const TensorShapeProto* mask_shape = mask_input->Shape();
if (mask_shape == nullptr || mask_shape->dim_size() != 2 || mask_input->Type() == nullptr) {
DEBUG_LOG("Mask shape is unknown or not 2D, or data type unknown");
return nullptr;
}
auto data_type = mask_input->TypeAsProto()->tensor_type().elem_type();
if (data_type != ONNX_NAMESPACE::TensorProto_DataType_INT64 &&
data_type != ONNX_NAMESPACE::TensorProto_DataType_INT32) {
DEBUG_LOG("Mask data type is not int32 or int64");
return nullptr;
}
NodeArg* reduce_sum_input = mask_input;
if (data_type == ONNX_NAMESPACE::TensorProto_DataType_INT64) {
NodeArg& cast_int32 = CastMaskToInt32(graph, mask_input, provider_type);
reduce_sum_input = &cast_int32;
}
// Construct shape based on mask input shape. Note that batch_size could be symbolic.
TypeProto output_type;
output_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT32);
auto dim = output_type.mutable_tensor_type()->mutable_shape()->add_dim();
*dim = mask_shape->dim(0);
NodeArg& output = AddMaskReduceSum(graph, reduce_sum_input, output_type, provider_type);
return &output;
}
static NodeArg* GetOrCreateMaskIndex(
Graph& graph,
NodeArg* mask_input,
std::map<std::string, NodeArg*>& mask_index_map,
ProviderType provider_type,
const logging::Logger& logger) {
// Lookup in map, and return the mask index if created.
auto search = mask_index_map.find(mask_input->Name());
if (search != mask_index_map.end()) {
return search->second;
}
NodeArg* output = ProcessMask(graph, mask_input, provider_type, logger);
if (nullptr == output) {
return nullptr;
}
// Add it to map for lookup later.
mask_index_map.insert(std::pair<std::string, NodeArg*>(mask_input->Name(), output));
return output;
}
Status AttentionFusion::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const {
GraphViewer graph_viewer(graph);
const auto& node_topology_list = graph_viewer.GetNodesInTopologicalOrder();
// A map from mask input arg name to mask index output.
std::map<std::string, NodeArg*> mask_index_map;
int fused_count = 0;
for (auto node_index : node_topology_list) {
auto* p_node = graph.GetNode(node_index);
if (p_node == nullptr)
continue; // we removed the node as part of an earlier fusion
Node& node = *p_node;
ORT_RETURN_IF_ERROR(Recurse(node, modified, graph_level, logger));
if (node.GetOutputEdgesCount() == 4 &&
graph_utils::IsSupportedOptypeVersionAndDomain(node, "LayerNormalization", {1}, kOnnxDomain) &&
graph_utils::IsSupportedProvider(node, GetCompatibleExecutionProviders())) {
// Get hidden size from layer norm bias tensor shape.
const NodeArg& layer_norm_bias = *(node.InputDefs()[2]);
if (!optimizer_utils::IsShapeKnownOnAllDims(layer_norm_bias, 1)) {
DEBUG_LOG("shape of layer norm bias tensor not expected");
continue;
}
int64_t hidden_size = layer_norm_bias.Shape()->dim(0).dim_value();
// Check that LayerNormalization has 4 children: 1 Add, 3 MatMul
const Node* add_node = nullptr;
int add_count = 0;
int matmul_count = 0;
for (auto it = node.OutputNodesBegin(); it != node.OutputNodesEnd(); ++it) {
if ((*it).OpType().compare("Add") == 0) {
add_count++;
add_node = &(*it);
} else if ((*it).OpType().compare("MatMul") == 0) {
matmul_count++;
}
}
if (add_count != 1 || matmul_count != 3) {
DEBUG_LOG("Attention subgraph expects 1 Add and 3 MatMul as children of LayerNormalization.");
continue;
}
if (AttentionFusion::FuseSubGraph(node, *add_node, graph, hidden_size, mask_index_map, logger)) {
fused_count++;
modified = true;
}
}
}
if (fused_count > 0) {
LOGS(logger, INFO) << "Total fused Attention node count: " << fused_count;
}
return Status::OK();
}
/** Fuse Attention SubGraph.
@remark add_after_layer_norm is the Add node in the bottom of sub-graph.
Abbreviatios: B is batch_size, S is sequence_length, W is hidden_size
N is number of attention heads, H is head size, and W=N*H
B and S could be symbolic.
Graph before Fusion (q_, k_, v_, qk_, qkv_ and mask_ prefix is added before Operator type):
[Input](BxSxW)
|
LayerNormalization
/ | | \ [Weights](WxW)
/ | | \ /
| q_MatMul k_MatMul v_MatMul [Bias](W)
| | | | /
| q_Add k_Add v_Add [Shape=0,0,N,H]
| | | | /
| q_Reshape k_Reshape v_Reshape [Mask] (BxS)
| | | | |
|q_Transpose k_Transpose v_Transpose mask_Unsqueeze(axes=1)
| (0,2,1,3) (0,2,3,1) (perm=0,2,1,3) |
| \ / | mask_Unsqueeze(axes=2)
| qk_MatMul | |
| | [B=2] | [A=1] mask_Cast(to=1)
| | / | \ /
| qk_Div | mask_Sub [A=1000]
| \ | \ /
| mask_Add <-------- /---------------------mask_Mul
| | /
| Softmax /
| \ /
| \ /
| qkv_MatMul
| |
| Transpose (perm=0,2,1,3)
| |
| Reshape---[shape=0,0,W]
| |
| MatMul----[Weights](WxW)
| |
| Add----[Bias](W)
+-------------------|---+
| |
Add
After Fusion:
LayerNormalization [Weights](Wx3W) Mask
| \ / [Bias](3W) |
| \ / / |
| Attention <------------ReduceSum
\ |
\ MatMul
\ |
\ Add
+------|---+
| |
Add
*/
bool AttentionFusion::FuseSubGraph(Node& layer_norm, const Node& add_after_layer_norm, Graph& graph, int64_t hidden_size, std::map<std::string, NodeArg*>& mask_index_map, const logging::Logger& logger) {
std::vector<graph_utils::EdgeEndToMatch> parent_path{
{0, 0, "Add", {7}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 0, "Reshape", {5}, kOnnxDomain},
{0, 0, "Transpose", {1}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 1, "Transpose", {1}, kOnnxDomain},
{0, 0, "Reshape", {5}, kOnnxDomain},
{0, 0, "Add", {7}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 0, "LayerNormalization", {1}, kOnnxDomain}};
std::vector<const Node::EdgeEnd*> edges;
if (!graph_utils::FindPath(add_after_layer_norm, true, parent_path, edges, logger)) {
DEBUG_LOG("Faild to find path v");
return false;
}
const Node& add = edges[0]->GetNode();
const Node& matmul = edges[1]->GetNode();
const Node& reshape = edges[2]->GetNode();
const Node& transpose = edges[3]->GetNode();
const Node& qkv_matmul = edges[4]->GetNode();
const Node& v_transpose = edges[5]->GetNode();
const Node& v_reshape = edges[6]->GetNode();
const Node& v_add = edges[7]->GetNode();
const Node& v_matmul = edges[8]->GetNode();
const Node& v_root = edges[9]->GetNode();
if (v_root.Index() != layer_norm.Index()) {
return false;
}
if (add.GetOutputEdgesCount() != 1 ||
matmul.GetOutputEdgesCount() != 1 ||
reshape.GetOutputEdgesCount() != 1 ||
transpose.GetOutputEdgesCount() != 1 ||
qkv_matmul.GetOutputEdgesCount() != 1 ||
v_transpose.GetOutputEdgesCount() != 1 ||
v_reshape.GetOutputEdgesCount() != 1 ||
v_add.GetOutputEdgesCount() != 1 ||
v_matmul.GetOutputEdgesCount() != 1 ||
v_root.GetOutputEdgesCount() != 4) {
DEBUG_LOG("Output edge count not expected for nodes in path v");
return false;
}
std::vector<int64_t> perm;
if (!(graph_utils::GetRepeatedNodeAttributeValues(transpose, "perm", perm) && perm.size() == 4 && perm[0] == 0 && perm[1] == 2 && perm[2] == 1 && perm[3] == 3)) {
DEBUG_LOG("Failed in match Transpose attribute perm. Expected: 0, 2, 1, 3");
return false;
}
if (!(graph_utils::GetRepeatedNodeAttributeValues(v_transpose, "perm", perm) && perm.size() == 4 && perm[0] == 0 && perm[1] == 2 && perm[2] == 1 && perm[3] == 3)) {
DEBUG_LOG("Failed in match v_transpose attribute perm. Expected: 0, 2, 1, 3");
return false;
}
std::vector<int64_t> v_reshape_shape;
if (!optimizer_utils::AppendTensorFromInitializer(graph, *(v_reshape.InputDefs()[1]), v_reshape_shape) ||
v_reshape_shape.size() != 4 ||
v_reshape_shape[2] <= 0 ||
v_reshape_shape[3] <= 0 ||
hidden_size != v_reshape_shape[2] * v_reshape_shape[3]) {
DEBUG_LOG("v_reshape initializer value is not expected");
return false;
}
const int64_t num_attention_head = v_reshape_shape[2];
const int64_t attention_head_size = v_reshape_shape[3];
std::vector<int64_t> reshape_shape;
if (!optimizer_utils::AppendTensorFromInitializer(graph, *(reshape.InputDefs()[1]), reshape_shape) ||
reshape_shape.size() != 3 ||
reshape_shape[2] != hidden_size) {
DEBUG_LOG("reshape initializer value is not expected");
return false;
}
// Validate the input shape of MatMul and Add according to hidden_size.
if (!(ValidateAddBiasInitializer(graph, add, hidden_size) &&
ValidateMatMulInitializer(graph, matmul, hidden_size) &&
ValidateAddBiasInitializer(graph, v_add, hidden_size) &&
ValidateMatMulInitializer(graph, v_matmul, hidden_size))) {
DEBUG_LOG("Failed in match v_matmul and v_add input shape");
return false;
}
// path 2 to find mask
std::vector<graph_utils::EdgeEndToMatch> mask_path{
{0, 0, "Softmax", {1, 11}, kOnnxDomain},
{0, 0, "Add", {7}, kOnnxDomain},
{0, 1, "Mul", {7}, kOnnxDomain},
{0, 0, "Sub", {7}, kOnnxDomain},
{0, 1, "Cast", {9}, kOnnxDomain},
{0, 0, "Unsqueeze", {1, 11}, kOnnxDomain},
{0, 0, "Unsqueeze", {1, 11}, kOnnxDomain}};
if (!graph_utils::FindPath(qkv_matmul, true, mask_path, edges, logger)) {
DEBUG_LOG("Failed to find path for mask");
return false;
}
const Node& softmax = edges[0]->GetNode();
const Node& mask_add = edges[1]->GetNode();
const Node& mask_mul = edges[2]->GetNode();
const Node& mask_sub = edges[3]->GetNode();
const Node& mask_cast = edges[4]->GetNode();
const Node& mask_unsqueeze_2 = edges[5]->GetNode();
const Node& mask_unsqueeze_1 = edges[6]->GetNode();
if (softmax.GetOutputEdgesCount() != 1 ||
mask_add.GetOutputEdgesCount() != 1 ||
mask_sub.GetOutputEdgesCount() != 1 ||
mask_cast.GetOutputEdgesCount() != 1 ||
mask_unsqueeze_2.GetOutputEdgesCount() != 1 ||
mask_unsqueeze_1.GetOutputEdgesCount() != 1) {
DEBUG_LOG("Output edge count not expected for mask nodes");
return false;
}
if (!optimizer_utils::IsAttributeWithExpectedValue(softmax, "axis", 3)) {
DEBUG_LOG("Softmax attribute axis is expected to be 3");
return false;
}
std::vector<int64_t> axes;
if (!(graph_utils::GetRepeatedNodeAttributeValues(mask_unsqueeze_1, "axes", axes) && axes.size() == 1 && axes[0] == 1)) {
DEBUG_LOG("mask_unsqueeze_1 axes not matched. Expect: 1");
return false;
}
if (!(graph_utils::GetRepeatedNodeAttributeValues(mask_unsqueeze_2, "axes", axes) && axes.size() == 1 && axes[0] == 2)) {
DEBUG_LOG("mask_unsqueeze_2 axes not matched. Expect: 2");
return false;
}
if (!optimizer_utils::IsInitializerWithExpectedValue(graph, *(mask_sub.InputDefs()[0]), float(1), false)) {
DEBUG_LOG("mask_sub const input not matched");
return false;
}
if (!optimizer_utils::IsInitializerWithExpectedValue(graph, *(mask_mul.InputDefs()[1]), float(-10000), false)) {
DEBUG_LOG("mask_mul const input not matched");
return false;
}
// path to q
std::vector<graph_utils::EdgeEndToMatch> q_path{
{0, 0, "Div", {7}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 0, "Transpose", {1}, kOnnxDomain},
{0, 0, "Reshape", {5}, kOnnxDomain},
{0, 0, "Add", {7}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 0, "LayerNormalization", {1}, kOnnxDomain}};
if (!graph_utils::FindPath(mask_add, true, q_path, edges, logger)) {
DEBUG_LOG("Failed to find path for q");
return false;
}
const Node& qk_div = edges[0]->GetNode();
const Node& qk_matmul = edges[1]->GetNode();
const Node& q_transpose = edges[2]->GetNode();
const Node& q_reshape = edges[3]->GetNode();
const Node& q_add = edges[4]->GetNode();
const Node& q_matmul = edges[5]->GetNode();
const Node& q_root = edges[6]->GetNode();
if (q_root.Index() != layer_norm.Index()) {
DEBUG_LOG("q root should be layer normalization");
return false;
}
std::vector<int64_t> q_reshape_shape;
if (!optimizer_utils::AppendTensorFromInitializer(graph, *(q_reshape.InputDefs()[1]), q_reshape_shape) ||
q_reshape_shape.size() != 4 ||
q_reshape_shape[2] != num_attention_head ||
q_reshape_shape[3] != attention_head_size) {
DEBUG_LOG("q_reshape const not matched");
return false;
}
float expected_value = std::sqrt(static_cast<float>(attention_head_size));
if (!optimizer_utils::IsInitializerWithExpectedValue(graph, *(qk_div.InputDefs()[1]), expected_value, false)) {
DEBUG_LOG("qk_div const not matched.");
return false;
}
if (!(graph_utils::GetRepeatedNodeAttributeValues(q_transpose, "perm", perm) && perm.size() == 4 && perm[0] == 0 && perm[1] == 2 && perm[2] == 1 && perm[3] == 3)) {
DEBUG_LOG("q_transpose perm attribute not matched");
return false;
}
if (!(ValidateAddBiasInitializer(graph, q_add, hidden_size) &&
ValidateMatMulInitializer(graph, q_matmul, hidden_size))) {
DEBUG_LOG("q_matmul and q_add shape not matched");
return false;
}
// path to k
std::vector<graph_utils::EdgeEndToMatch> k_path{
{0, 1, "Transpose", {1}, kOnnxDomain},
{0, 0, "Reshape", {5}, kOnnxDomain},
{0, 0, "Add", {7}, kOnnxDomain},
{0, 0, "MatMul", {1, 9}, kOnnxDomain},
{0, 0, "LayerNormalization", {1}, kOnnxDomain}};
if (!graph_utils::FindPath(qk_matmul, true, k_path, edges, logger)) {
DEBUG_LOG("Failed to find path for k");
return false;
}
const Node& k_transpose = edges[0]->GetNode();
const Node& k_reshape = edges[1]->GetNode();
const Node& k_add = edges[2]->GetNode();
const Node& k_matmul = edges[3]->GetNode();
const Node& k_root = edges[4]->GetNode();
if (k_root.Index() != layer_norm.Index()) {
DEBUG_LOG("k root is not layer norm");
return false;
}
if (!(graph_utils::GetRepeatedNodeAttributeValues(k_transpose, "perm", perm) && perm.size() == 4 && perm[0] == 0 && perm[1] == 2 && perm[2] == 3 && perm[3] == 1)) {
DEBUG_LOG("k_transpose perm attribute not matched");
return false;
}
if (!(ValidateAddBiasInitializer(graph, k_add, hidden_size) &&
ValidateMatMulInitializer(graph, k_matmul, hidden_size))) {
DEBUG_LOG("k_matmul and k_add shape not matched");
return false;
}
std::vector<int64_t> k_reshape_shape;
if (!optimizer_utils::AppendTensorFromInitializer(graph, *(k_reshape.InputDefs()[1]), k_reshape_shape) ||
k_reshape_shape.size() != 4 ||
k_reshape_shape[2] != num_attention_head ||
k_reshape_shape[3] != attention_head_size) {
DEBUG_LOG("k_reshape const not matched");
return false;
}
// Load q, k and v weights
const ONNX_NAMESPACE::TensorProto* q_weight_tensor = nullptr;
const ONNX_NAMESPACE::TensorProto* k_weight_tensor = nullptr;
const ONNX_NAMESPACE::TensorProto* v_weight_tensor = nullptr;
if (!LoadQkvWeights(graph, q_matmul, k_matmul, v_matmul, q_weight_tensor, k_weight_tensor, v_weight_tensor)) {
DEBUG_LOG("Failed to load Q, K and V weights, or data type is not float or float16.");
return false;
}
const ONNX_NAMESPACE::TensorProto* q_bias_tensor = nullptr;
const ONNX_NAMESPACE::TensorProto* k_bias_tensor = nullptr;
const ONNX_NAMESPACE::TensorProto* v_bias_tensor = nullptr;
if (!LoadQkvWeights(graph, q_add, k_add, v_add, q_bias_tensor, k_bias_tensor, v_bias_tensor)) {
DEBUG_LOG("Failed to load Q, K and V bias tensors, or data type is not float or float16.");
return false;
}
// Now everything is ready, we will start fusing subgraph.
NodeArg* mask_input = graph.GetNode(mask_unsqueeze_1.Index())->MutableInputDefs()[0];
NodeArg* mask_index = GetOrCreateMaskIndex(graph, mask_input, mask_index_map, layer_norm.GetExecutionProviderType(), logger);
if (nullptr == mask_index) {
DEBUG_LOG("Failed to create mask index");
return false;
}
// Merge Q, K and V weights
NodeArg& qkv_weights = MergeQkvWeights(graph, hidden_size, q_weight_tensor, k_weight_tensor, v_weight_tensor, true);
NodeArg& qkv_bias = MergeQkvWeights(graph, hidden_size, q_bias_tensor, k_bias_tensor, v_bias_tensor, false);
// Create Attention Node.
const std::vector<NodeArg*> input_defs{layer_norm.MutableOutputDefs()[0], &qkv_weights, &qkv_bias, mask_index};
const std::vector<NodeArg*> output_defs{graph.GetNode(reshape.Index())->MutableOutputDefs()[0]};
Node& attention_node = graph.AddNode(
graph.GenerateNodeName("Attention"),
"Attention",
"Fused Attention subgraphs ",
input_defs,
output_defs,
nullptr,
kMSDomain);
attention_node.AddAttribute("num_heads", num_attention_head);
// Assign provider to this new node.
attention_node.SetExecutionProviderType(layer_norm.GetExecutionProviderType());
// Remove nodes that are not used anymore.
std::vector<NodeIndex> nodes_to_remove{
reshape.Index(),
transpose.Index(),
qkv_matmul.Index(),
v_transpose.Index(),
v_reshape.Index(),
v_add.Index(),
v_matmul.Index(),
softmax.Index(),
mask_add.Index(),
qk_div.Index(),
qk_matmul.Index(),
q_transpose.Index(),
q_reshape.Index(),
q_add.Index(),
q_matmul.Index(),
k_transpose.Index(),
k_reshape.Index(),
k_add.Index(),
k_matmul.Index()};
// When the last Attention node is fused. Original mask processing nodes can be removed safely.
if (mask_mul.GetOutputEdgesCount() == 1) {
nodes_to_remove.push_back(mask_mul.Index());
nodes_to_remove.push_back(mask_sub.Index());
nodes_to_remove.push_back(mask_cast.Index());
nodes_to_remove.push_back(mask_unsqueeze_2.Index());
nodes_to_remove.push_back(mask_unsqueeze_1.Index());
}
for (const auto& node_index : nodes_to_remove) {
Node* node = graph.GetNode(node_index);
graph_utils::RemoveNodeOutputEdges(graph, *node);
graph.RemoveNode(node->Index());
}
DEBUG_LOG("Fused an attention node.");
return true;
}
} // namespace onnxruntime
| 39.001406 | 203 | 0.640137 | [
"shape",
"vector"
] |
40de09c65c36b033db2ae9d78135f71d586370af | 15,740 | cpp | C++ | Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Private/Data/SsTypes.cpp | SpriteStudio/SS6PlayerForUnrealEngine4 | 86b18ab02d6253f73a5c8607f8b67f05780c7a46 | [
"MIT"
] | 17 | 2018-01-11T06:07:57.000Z | 2022-03-04T09:57:33.000Z | Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Private/Data/SsTypes.cpp | SpriteStudio/SS6PlayerForUnrealEngine4 | 86b18ab02d6253f73a5c8607f8b67f05780c7a46 | [
"MIT"
] | 10 | 2018-02-28T02:09:07.000Z | 2019-12-14T12:23:52.000Z | Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Private/Data/SsTypes.cpp | SpriteStudio/SS6PlayerForUnrealEngine4 | 86b18ab02d6253f73a5c8607f8b67f05780c7a46 | [
"MIT"
] | 3 | 2019-08-30T08:25:15.000Z | 2021-01-30T12:13:38.000Z | #include "SsTypes.h"
//---------------------------------------------------------------
//相互変換 SsPartType
FString __EnumToString_( TEnumAsByte<SsPartType::Type> n )
{
if ( n == SsPartType::Invalid ) return "invalid";
if ( n == SsPartType::Null ) return "null";
if ( n == SsPartType::Normal ) return "normal";
if ( n == SsPartType::Text ) return "text";
if ( n == SsPartType::Instance ) return "instance";
if ( n == SsPartType::Effect ) return "effect";
if ( n == SsPartType::Armature ) return "armature";
if ( n == SsPartType::Mesh ) return "mesh";
if ( n == SsPartType::MoveNode ) return "movenode";
if ( n == SsPartType::Constraint ) return "constraint";
if ( n == SsPartType::Mask ) return "mask";
if ( n == SsPartType::Joint ) return "joint";
if ( n == SsPartType::BonePoint ) return "bonepoint";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsPartType::Type>& out)
{
out = SsPartType::Invalid;
if ( n == "invalid") out = SsPartType::Invalid;
if ( n == "null") out = SsPartType::Null;
if ( n == "normal") out = SsPartType::Normal;
if ( n == "text") out = SsPartType::Text;
if ( n == "instance") out = SsPartType::Instance;
if ( n == "effect") out = SsPartType::Effect;
if ( n == "armature") out = SsPartType::Armature;
if ( n == "mesh") out = SsPartType::Mesh;
if ( n == "movenode") out = SsPartType::MoveNode;
if ( n == "constraint") out = SsPartType::Constraint;
if ( n == "mask") out = SsPartType::Mask;
if ( n == "joint") out = SsPartType::Joint;
if ( n == "bonepoint") out = SsPartType::BonePoint;
}
//---------------------------------------------------------------
//相互変換 SsPartsSortMode
FString __EnumToString_(SsPartsSortMode::_enum n)
{
if ( n == SsPartsSortMode::invalid ) return "invalid";
if ( n == SsPartsSortMode::prio ) return "prio";
if ( n == SsPartsSortMode::z ) return "z";
return "invalid";
}
void __StringToEnum_( FString n , SsPartsSortMode::_enum &out )
{
out = SsPartsSortMode::invalid;
if ( n == "invalid") out = SsPartsSortMode::invalid;
if ( n == "prio") out = SsPartsSortMode::prio;
if ( n == "z") out = SsPartsSortMode::z;
}
//---------------------------------------------------------------
//相互変換 SsBoundsType
FString __EnumToString_( TEnumAsByte<SsBoundsType::Type> n )
{
if ( n == SsBoundsType::Invalid ) return "invalid";
if ( n == SsBoundsType::None ) return "none";
if ( n == SsBoundsType::Quad ) return "quad";
if ( n == SsBoundsType::Aabb ) return "aabb";
if ( n == SsBoundsType::Circle ) return "circle";
if ( n == SsBoundsType::CircleSmin ) return "circle_smin";
if ( n == SsBoundsType::CircleSmax ) return "circle_smax";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsBoundsType::Type> &out )
{
out = SsBoundsType::Invalid;
if ( n == "invalid") out = SsBoundsType::Invalid;
if ( n == "none") out = SsBoundsType::None;
if ( n == "quad") out = SsBoundsType::Quad;
if ( n == "aabb") out = SsBoundsType::Aabb;
if ( n == "circle") out = SsBoundsType::Circle;
if ( n == "circle_smin") out = SsBoundsType::CircleSmin;
if ( n == "circle_smax") out = SsBoundsType::CircleSmax;
}
//---------------------------------------------------------------
//相互変換 SsBoundsType
FString __EnumToString_( TEnumAsByte<SsInheritType::Type> n )
{
if ( n == SsInheritType::Invalid ) return "invalid";
if ( n == SsInheritType::Parent ) return "parent";
if ( n == SsInheritType::Self ) return "self";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsInheritType::Type> &out )
{
out = SsInheritType::Invalid;
if ( n == "invalid") out = SsInheritType::Invalid;
if ( n == "parent") out = SsInheritType::Parent;
if ( n == "self") out = SsInheritType::Self;
}
//---------------------------------------------------------------
//相互変換 SsBlendType
FString __EnumToString_( TEnumAsByte<SsBlendType::Type> n )
{
if ( n == SsBlendType::Invalid ) return "invalid";
if ( n == SsBlendType::Mix ) return "mix";
if ( n == SsBlendType::Mul ) return "mul";
if ( n == SsBlendType::Add ) return "add";
if ( n == SsBlendType::Sub ) return "sub";
if ( n == SsBlendType::MulAlpha ) return "mulalpha";
if ( n == SsBlendType::Screen ) return "screen";
if ( n == SsBlendType::Exclusion ) return "exclusion";
if ( n == SsBlendType::Invert ) return "invert";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsBlendType::Type> &out )
{
out = SsBlendType::Invalid;
if ( n == "invalid") out = SsBlendType::Invalid;
if ( n == "mix") out = SsBlendType::Mix;
if ( n == "mul") out = SsBlendType::Mul;
if ( n == "add") out = SsBlendType::Add;
if ( n == "sub") out = SsBlendType::Sub;
if ( n == "mulalpha") out = SsBlendType::MulAlpha;
if ( n == "screen") out = SsBlendType::Screen;
if ( n == "exclusion") out = SsBlendType::Exclusion;
if ( n == "invert") out = SsBlendType::Invert;
}
//---------------------------------------------------------------
//相互変換 SsInterpolationType
FString __EnumToString_( TEnumAsByte<SsInterpolationType::Type> n )
{
if ( n == SsInterpolationType::Invalid ) return "invalid";
if ( n == SsInterpolationType::None ) return "none";
if ( n == SsInterpolationType::Linear ) return "linear";
if ( n == SsInterpolationType::Hermite ) return "hermite";
if ( n == SsInterpolationType::Bezier ) return "bezier";
if ( n == SsInterpolationType::Acceleration ) return "acceleration";
if ( n == SsInterpolationType::Deceleration ) return "deceleration";
return "none";
}
void __StringToEnum_( FString n , TEnumAsByte<SsInterpolationType::Type> &out )
{
out = SsInterpolationType::None;
if ( n == "invalid") out = SsInterpolationType::Invalid;
if ( n == "none") out = SsInterpolationType::None;
if ( n == "linear") out = SsInterpolationType::Linear;
if ( n == "hermite") out = SsInterpolationType::Hermite;
if ( n == "bezier") out = SsInterpolationType::Bezier;
if ( n == "acceleration") out = SsInterpolationType::Acceleration;
if ( n == "deceleration") out = SsInterpolationType::Deceleration;
}
//---------------------------------------------------------------
//相互変換 SsTexWrapMode
FString __EnumToString_( TEnumAsByte<SsTexWrapMode::Type> n )
{
if ( n == SsTexWrapMode::Invalid ) return "invalid";
if ( n == SsTexWrapMode::Clamp ) return "clamp";
if ( n == SsTexWrapMode::Repeat ) return "repeat";
if ( n == SsTexWrapMode::Mirror ) return "mirror";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsTexWrapMode::Type> &out )
{
out = SsTexWrapMode::Invalid;
if ( n == "invalid") out = SsTexWrapMode::Invalid;
if ( n == "clamp") out = SsTexWrapMode::Clamp;
if ( n == "repeat") out = SsTexWrapMode::Repeat;
if ( n == "mirror") out = SsTexWrapMode::Mirror;
}
//---------------------------------------------------------------
//相互変換 SsTexFilterMode
FString __EnumToString_( TEnumAsByte<SsTexFilterMode::Type> n )
{
if ( n == SsTexFilterMode::Invalid ) return "invalid";
if ( n == SsTexFilterMode::Nearest ) return "nearlest"; // sspj側の誤植?
if ( n == SsTexFilterMode::Linear ) return "linear";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsTexFilterMode::Type> &out )
{
out = SsTexFilterMode::Invalid;
if ( n == "invalid") out = SsTexFilterMode::Invalid;
if ( n == "nearlest") out = SsTexFilterMode::Nearest; // sspj側の誤植?
if ( n == "linear") out = SsTexFilterMode::Linear;
}
//---------------------------------------------------------------
//相互変換 SsTexFilterMode
FString __EnumToString_( TEnumAsByte<SsColorBlendTarget::Type> n )
{
if ( n == SsColorBlendTarget::Invalid ) return "invalid";
if ( n == SsColorBlendTarget::Whole ) return "whole";
if ( n == SsColorBlendTarget::Vertex ) return "vertex";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsColorBlendTarget::Type> &out )
{
out = SsColorBlendTarget::Invalid;
if ( n == "invalid") out = SsColorBlendTarget::Invalid;
if ( n == "whole") out = SsColorBlendTarget::Whole;
if ( n == "vertex") out = SsColorBlendTarget::Vertex;
}
//---------------------------------------------------------------
//相互変換 SsAttributeKind
FString __EnumToString_( TEnumAsByte<SsAttributeKind::Type> n )
{
if ( n == SsAttributeKind::Invalid ) return "invalid";
if ( n == SsAttributeKind::Cell ) return "CELL";
if ( n == SsAttributeKind::Posx ) return "POSX";
if ( n == SsAttributeKind::Posy ) return "POSY";
if ( n == SsAttributeKind::Posz ) return "POSZ";
if ( n == SsAttributeKind::Rotx ) return "ROTX";
if ( n == SsAttributeKind::Roty ) return "ROTY";
if ( n == SsAttributeKind::Rotz ) return "ROTZ";
if ( n == SsAttributeKind::Sclx ) return "SCLX";
if ( n == SsAttributeKind::Scly ) return "SCLY";
if ( n == SsAttributeKind::Losclx ) return "LSCX";
if ( n == SsAttributeKind::Loscly ) return "LSCY";
if ( n == SsAttributeKind::Alpha ) return "ALPH";
if ( n == SsAttributeKind::Loalpha ) return "LALP";
if ( n == SsAttributeKind::Prio ) return "PRIO";
if ( n == SsAttributeKind::Fliph ) return "FLPH";
if ( n == SsAttributeKind::Flipv ) return "FLPV";
if ( n == SsAttributeKind::Hide ) return "HIDE";
if ( n == SsAttributeKind::PartsColor ) return "PCOL";
if ( n == SsAttributeKind::Color ) return "VCOL";
if ( n == SsAttributeKind::Vertex ) return "VERT";
if ( n == SsAttributeKind::Pivotx ) return "PVTX";
if ( n == SsAttributeKind::Pivoty ) return "PVTY";
if ( n == SsAttributeKind::Anchorx ) return "ANCX";
if ( n == SsAttributeKind::Anchory ) return "ANCY";
if ( n == SsAttributeKind::Sizex ) return "SIZX";
if ( n == SsAttributeKind::Sizey ) return "SIZY";
if ( n == SsAttributeKind::Imgfliph ) return "IFLH";
if ( n == SsAttributeKind::Imgflipv ) return "IFLV";
if ( n == SsAttributeKind::Uvtx ) return "UVTX";
if ( n == SsAttributeKind::Uvty ) return "UVTY";
if ( n == SsAttributeKind::Uvrz ) return "UVRZ";
if ( n == SsAttributeKind::Uvsx ) return "UVSX";
if ( n == SsAttributeKind::Uvsy ) return "UVSY";
if ( n == SsAttributeKind::Boundr ) return "BNDR";
if ( n == SsAttributeKind::User ) return "USER";
if ( n == SsAttributeKind::Instance ) return "IPRM";
if ( n == SsAttributeKind::Effect) return "EFCT";
if ( n == SsAttributeKind::Mask ) return "MASK";
if ( n == SsAttributeKind::Deform ) return "DEFM";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsAttributeKind::Type> &out )
{
out = SsAttributeKind::Invalid;
if ( n == "invalid") out = SsAttributeKind::Invalid;
if ( n == "CELL") out = SsAttributeKind::Cell;
if ( n == "POSX") out = SsAttributeKind::Posx;
if ( n == "POSY") out = SsAttributeKind::Posy;
if ( n == "POSZ") out = SsAttributeKind::Posz;
if ( n == "ROTX") out = SsAttributeKind::Rotx;
if ( n == "ROTY") out = SsAttributeKind::Roty;
if ( n == "ROTZ") out = SsAttributeKind::Rotz;
if ( n == "SCLX") out = SsAttributeKind::Sclx;
if ( n == "SCLY") out = SsAttributeKind::Scly;
if ( n == "LSCX") out = SsAttributeKind::Losclx;
if ( n == "LSCY") out = SsAttributeKind::Loscly;
if ( n == "ALPH") out = SsAttributeKind::Alpha;
if ( n == "LALP") out = SsAttributeKind::Loalpha;
if ( n == "PRIO") out = SsAttributeKind::Prio;
if ( n == "FLPH") out = SsAttributeKind::Fliph;
if ( n == "FLPV") out = SsAttributeKind::Flipv;
if ( n == "HIDE") out = SsAttributeKind::Hide;
if ( n == "PCOL") out = SsAttributeKind::PartsColor;
if ( n == "VCOL") out = SsAttributeKind::Color;
if ( n == "VERT") out = SsAttributeKind::Vertex;
if ( n == "PVTX") out = SsAttributeKind::Pivotx;
if ( n == "PVTY") out = SsAttributeKind::Pivoty;
if ( n == "ANCX") out = SsAttributeKind::Anchorx;
if ( n == "ANCY") out = SsAttributeKind::Anchory;
if ( n == "SIZX") out = SsAttributeKind::Sizex;
if ( n == "SIZY") out = SsAttributeKind::Sizey;
if ( n == "IFLH") out = SsAttributeKind::Imgfliph;
if ( n == "IFLV") out = SsAttributeKind::Imgflipv;
if ( n == "UVTX") out = SsAttributeKind::Uvtx;
if ( n == "UVTY") out = SsAttributeKind::Uvty;
if ( n == "UVRZ") out = SsAttributeKind::Uvrz;
if ( n == "UVSX") out = SsAttributeKind::Uvsx;
if ( n == "UVSY") out = SsAttributeKind::Uvsy;
if ( n == "BNDR") out = SsAttributeKind::Boundr;
if ( n == "USER") out = SsAttributeKind::User;
if ( n == "IPRM") out = SsAttributeKind::Instance;
if ( n == "EFCT") out = SsAttributeKind::Effect;
if ( n == "MASK") out = SsAttributeKind::Mask;
if ( n == "DEFM") out = SsAttributeKind::Deform;
}
//---------------------------------------------------------------
//相互変換 SsPartType
FString __EnumToString_( TEnumAsByte<SsEffectNodeType::Type> n )
{
if ( n == SsEffectNodeType::Invalid ) return "invalid";
if ( n == SsEffectNodeType::Root ) return "root";
if ( n == SsEffectNodeType::Emmiter ) return "emmiter";
if ( n == SsEffectNodeType::Particle ) return "particle";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsEffectNodeType::Type>& out)
{
out = SsEffectNodeType::Invalid;
if ( n == "invalid") out = SsEffectNodeType::Invalid;
if ( n == "root") out = SsEffectNodeType::Root;
if ( n == "emmiter") out = SsEffectNodeType::Emmiter;
if ( n == "particle") out = SsEffectNodeType::Particle;
}
//---------------------------------------------------------------
//相互変換 SsPartType
FString __EnumToString_( TEnumAsByte<SsRenderBlendType::Type> n )
{
if ( n == SsRenderBlendType::Invalid ) return "invalid";
if ( n == SsRenderBlendType::Mix ) return "Mix";
if ( n == SsRenderBlendType::Add ) return "Add";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsRenderBlendType::Type>& out)
{
out = SsRenderBlendType::Invalid;
if ( n == "invalid") out = SsRenderBlendType::Invalid;
if ( n == "Mix") out = SsRenderBlendType::Mix;
if ( n == "Add") out = SsRenderBlendType::Add;
}
TEnumAsByte<SsBlendType::Type> SsRenderBlendTypeToBlendType(TEnumAsByte<SsRenderBlendType::Type> n)
{
switch(n)
{
case SsRenderBlendType::Mix: return SsBlendType::Mix;
case SsRenderBlendType::Add: return SsBlendType::Add;
}
return SsBlendType::Mix;
}
//---------------------------------------------------------------
//相互変換 SsIkRotationArrow
FString __EnumToString_( TEnumAsByte<SsIkRotationArrow::Type> n )
{
if ( n == SsIkRotationArrow::Arrowfree) return "arrowfree";
if ( n == SsIkRotationArrow::Clockwise) return "clockwise";
if ( n == SsIkRotationArrow::Anticlockwise) return "anticlockwise";
return "unknown";
}
void __StringToEnum_( FString n , TEnumAsByte<SsIkRotationArrow::Type>& out)
{
out = SsIkRotationArrow::Unknown;
if ( n == "arrowfree") out = SsIkRotationArrow::Arrowfree;
if ( n == "clockwise") out = SsIkRotationArrow::Clockwise;
if ( n == "anticlockwise") out = SsIkRotationArrow::Anticlockwise;
}
//---------------------------------------------------------------
//相互変換 SsSequenceType
FString __EnumToString_( TEnumAsByte<SsSequenceType::Type> n )
{
if ( n == SsSequenceType::Last) return "LAST";
if ( n == SsSequenceType::Keep) return "KEEP";
if ( n == SsSequenceType::Top) return "TOP";
return "invalid";
}
void __StringToEnum_( FString n , TEnumAsByte<SsSequenceType::Type>& out)
{
out = SsSequenceType::Invalid;
if ( n == "LAST") out = SsSequenceType::Last;
if ( n == "KEEP") out = SsSequenceType::Keep;
if ( n == "TOP") out = SsSequenceType::Top;
}
//---------------------------------------------------------------
//相互変換 SsMeshDivType
FString __EnumToString_( TEnumAsByte<SsMeshDivType::Type> n )
{
if ( n == SsMeshDivType::PolylineBase) return "polyline_base";
if ( n == SsMeshDivType::Boxdiv) return "boxdiv";
return "unknown";
}
void __StringToEnum_( FString n , TEnumAsByte<SsMeshDivType::Type>& out)
{
out = SsMeshDivType::Unknown;
if ( n == "polyline_base") out = SsMeshDivType::PolylineBase;
if ( n == "boxdiv") out = SsMeshDivType::Boxdiv;
}
| 36.861827 | 99 | 0.621665 | [
"mesh"
] |
40de0b412503f3aeded6af35c5456674f8e5119a | 537 | cpp | C++ | thread_1.cpp | wasimusu/cpp_practice | 8feb8dd51bb07d8c5781c8e8a870421f21e4ba57 | [
"MIT"
] | 1 | 2020-08-26T13:08:58.000Z | 2020-08-26T13:08:58.000Z | thread_1.cpp | wasimusu/cpp_practice | 8feb8dd51bb07d8c5781c8e8a870421f21e4ba57 | [
"MIT"
] | null | null | null | thread_1.cpp | wasimusu/cpp_practice | 8feb8dd51bb07d8c5781c8e8a870421f21e4ba57 | [
"MIT"
] | null | null | null | #include <thread>
#include <iostream>
#include <vector>
#include <future>
using namespace std;
void foo() {
cout << "Foo" << endl;
}
void bar() {
cout << "Bar" << endl;
}
int factorial(int x) {
if (x == 1 || x == 0) return 1;
return x * factorial(x - 1);
}
int main() {
vector<thread> threads;
threads.emplace_back(std::thread(foo));
threads.emplace_back(std::thread(bar));
auto f = std::async(factorial, 5);
threads[0].join();
threads[1].join();
cout << f.get() << endl;
return 0;
} | 17.322581 | 43 | 0.573557 | [
"vector"
] |
40dfbde48ea0d2bbb8d46333d16630b2efc41f3b | 28,260 | cpp | C++ | src/plant_costsse/nrel_land_bosse/cmod_windbos.cpp | WISDEM/Plant_CostsSE | c93c99fbb23a92c7222f15259bd3e204fb323407 | [
"Apache-2.0"
] | 1 | 2018-12-27T09:03:16.000Z | 2018-12-27T09:03:16.000Z | src/plant_costsse/nrel_land_bosse/cmod_windbos.cpp | WISDEM/Plant_CostsSE | c93c99fbb23a92c7222f15259bd3e204fb323407 | [
"Apache-2.0"
] | 2 | 2015-07-08T19:53:35.000Z | 2017-09-03T14:06:44.000Z | src/plant_costsse/nrel_land_bosse/cmod_windbos.cpp | WISDEM/Plant_CostsSE | c93c99fbb23a92c7222f15259bd3e204fb323407 | [
"Apache-2.0"
] | 5 | 2017-09-14T17:09:33.000Z | 2021-04-19T18:39:55.000Z | #include "core.h"
static var_info _cm_vtab_windbos[] = {
/* VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS*/
// Inputs
{ SSC_INPUT, SSC_NUMBER, "machine_rating", "Machine Rating", "kW", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "rotor_diameter", "Rotor Diameter", "m", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "hub_height", "Hub Height", "m", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "number_of_turbines", "Number of Turbines", "", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "interconnect_voltage", "Interconnect Voltage", "kV", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "distance_to_interconnect", "Distance to Interconnect", "miles", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "site_terrain", "Site Terrain", "", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "turbine_layout", "Turbine Layout", "", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "soil_condition", "Soil Condition", "", "", "wind_bos", "*", "INTEGER", "" },
// Values that can be calculated in UI, or can be entered directly by the user
{ SSC_INPUT, SSC_NUMBER, "construction_time", "Construction Time", "months", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "om_building_size", "O&M Building Size", "ft^2", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "quantity_test_met_towers", "Quantity of Temporary Meteorological Towers for Testing", "", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "quantity_permanent_met_towers", "Quantity of Permanent Meteorological Towers for Testing", "", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "weather_delay_days", "Wind / Weather delay days", "", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "crane_breakdowns", "Crane breakdowns", "", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "access_road_entrances", "Access road entrances", "", "", "wind_bos", "*", "", "" },
// inputs from cost model outputs
{ SSC_INPUT, SSC_NUMBER, "turbine_capital_cost", "Turbine Capital Cost", "$/kW", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "tower_top_mass", "Tower Top Mass", "Tonnes", "", "wind_bos", "*", "", "" },
// advanced user BOS inputs
{ SSC_INPUT, SSC_NUMBER, "delivery_assist_required", "Delivery Assist Required", "y/n", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "pad_mount_transformer_required","Pad mount Transformer required", "y/n", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "new_switchyard_required", "New Switchyard Required", "y/n", "", "wind_bos", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "rock_trenching_required", "Rock trenching required", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "mv_thermal_backfill", "MV thermal backfill", "mi", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "mv_overhead_collector", "MV overhead collector", "mi", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "performance_bond", "Performance bond", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "contingency", "Contingency", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "warranty_management", "Warranty management", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "sales_and_use_tax", "Sales and Use Tax", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "overhead", "Overhead", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "profit_margin", "Profit Margin", "%", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "development_fee", "Development Fee", "$M", "", "wind_bos", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "turbine_transportation", "Turbine Transportation", "mi", "", "wind_bos", "*", "", "" },
// { SSC_OUTPUT, SSC_ARRAY, "e_net", "AC Generation", "kWh", "", "wind_bos", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_NUMBER, "project_total_budgeted_cost", "Project Total Budgeted Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "transportation_cost", "Transportation Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "insurance_cost", "Insurance Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "engineering_cost", "Engineering Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "power_performance_cost", "Power Performance Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "site_compound_security_cost", "Site Compound & Security Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "building_cost", "Building Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "transmission_cost", "Transmission Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "markup_cost", "Markup Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "development_cost", "Development Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "access_roads_cost", "Access Roads Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "foundation_cost", "Foundation Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "erection_cost", "Turbine Erection Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "electrical_materials_cost", "MV Electrical Materials Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "electrical_installation_cost", "MV Electrical Installation Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "substation_cost", "Substation Cost", "$s", "", "wind_bos", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "project_mgmt_cost", "Project Management Cost", "$s", "", "wind_bos", "*", "", "" },
var_info_invalid };
class cm_windbos : public compute_module
{
public:
cm_windbos()
{
add_var_info(_cm_vtab_windbos);
}
//
// LandBOS.h
// LandBOS
//
// Created by Andrew Ning on 3/12/14.
// Copyright (c) 2014 NREL. All rights reserved.
//
// **********************************************************************
// Code from LandBOS.h and LandBOS.c starts here, ends at 'exec' function
// **********************************************************************
typedef enum { FLAT_TO_ROLLING, RIDGE_TOP, MOUNTAINOUS } SiteTerrain;
typedef enum { SIMPLE, COMPLEX } TurbineLayout;
typedef enum { STANDARD, BOUYANT } SoilCondition;
int round_bos(double number)
{
return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}
// wind farm size in MW
double farmSize(double rating, int nTurb){
return rating * nTurb / 1000.0;
}
// Construction Time (months)
//int defaultConstructionTime(int nTurb){
// return round_bos(0.0001*nTurb*nTurb + 0.0963*nTurb + 2.7432);
//}
// Access road entrances
//int defaultAccessRoadEntrances(int nTurb){
// return fmax(1, round_bos(nTurb / 20.0));
//}
// O&M Building Size (ft2)
//double defaultBuildingSize(double farmSize){
// double buildingSize;
// // O&M Building Size (ft2)
// if (farmSize < 200){
// buildingSize = 3000;
// }
// else if (farmSize < 500){
// buildingSize = 5000;
// }
// else if (farmSize < 800){
// buildingSize = 7000;
// }
// else if (farmSize < 1000){
// buildingSize = 9000;
// }
// else{
// buildingSize = 12000;
// }
// return buildingSize;
//}
// Quantity of Temporary Meteorological Towers for Testing
//double defaultTempMetTowers(double farmSize){
// return round_bos(farmSize / 75.0);
//}
// Quantity of Permanent Meteorological Towers for Testing
//double defaultPermanentMetTowers(double farmSize){
// int permanent;
// if (farmSize < 100){
// permanent = 1;
// }
// else if (farmSize < 200){
// permanent = 2;
// }
// else{
// permanent = (int)(farmSize / 100.0);
// }
// return permanent;
//}
// Wind/Weather delay days
//int defaultWeatherDelayDays(int nTurb){
// return round_bos(nTurb / 5.0);
//}
// Crane breakdowns
//int defaultCraneBreakdowns(int nTurb){
// return round_bos(nTurb / 20.0);
//}
double transportationCost(double tcc, double rating, int nTurb, double hubHt, double transportDist){
double cost = tcc * rating * nTurb;
if (rating < 2500 && hubHt < 100) {
cost += 1349 * pow(transportDist, 0.746) * nTurb;
}
else {
cost += 1867 * pow(transportDist, 0.726) * nTurb;
}
assign("transportation_cost", var_data(cost));
return cost;
}
double engineeringCost(int nTurb, double farmSize)
{
double cost = 7188.5 * nTurb;
cost += round_bos(3.4893*std::log(nTurb) - 7.3049) * 16800;
double multiplier = 2.0;
if (farmSize < 200) multiplier = 1.0;
cost += multiplier * 161675;
cost += 4000;
assign("engineering_cost", var_data(cost));
return cost;
}
double powerPerformanceCost(double hubHt, double permanent, double temporary){
double multiplier1 = 290000;
double multiplier2 = 116800;
if (hubHt < 90) {
multiplier1 = 232600;
multiplier2 = 92600;
}
double cost = 200000 + permanent*multiplier1 + temporary*multiplier2;
assign("power_performance_cost", var_data(cost));
return cost;
}
double accessRoadsCost(SiteTerrain terrain, TurbineLayout layout, int nTurb, double diameter, int constructionTime, int accessRoadEntrances){
double factor1 = 0.0;
double factor2 = 0.0;
if (layout == SIMPLE){
if (terrain == FLAT_TO_ROLLING){
factor1 = 49962.5;
factor2 = 24.8;
}
else if (terrain == RIDGE_TOP){
factor1 = 59822.0;
factor2 = 26.8;
}
else if (terrain == MOUNTAINOUS){
factor1 = 66324.0;
factor2 = 26.8;
}
}
else if (layout == COMPLEX){
if (terrain == FLAT_TO_ROLLING){
factor1 = 62653.6;
factor2 = 30.9;
}
else if (terrain == RIDGE_TOP){
factor1 = 74213.3;
factor2 = 33.0;
}
else if (terrain == MOUNTAINOUS){
factor1 = 82901.1;
factor2 = 33.0;
}
}
double cost = (nTurb*factor1 + nTurb*diameter*factor2
+ constructionTime * 55500
+ accessRoadEntrances * 3800)*1.05;
assign("access_roads_cost", var_data(cost));
return cost;
}
double siteCompoundCost(int accessRoadEntrances, int constructionTime, double farmSize)
{
double cost = 9825.0*accessRoadEntrances + 29850.0*constructionTime;
double multiplier;
if (farmSize > 100){
multiplier = 10.0;
}
else if (farmSize > 30){
multiplier = 5.0;
}
else{
multiplier = 3.0;
}
cost += multiplier * 30000;
if (farmSize > 30){
cost += 90000;
}
cost += farmSize * 60 + 62400;
assign("site_compound_security_cost", var_data(cost));
return cost;
}
double buildingCost(double buildingSize){
double cost = buildingSize * 125 + 176125;
assign("building_cost", var_data(cost));
return cost;
}
double foundationCost(double rating, double diameter, double topMass, double hubHt, SoilCondition soil, int nTurb)
{
double cost = rating*diameter*topMass / 1000.0
+ 163421.5*pow(nTurb, -0.1458) + (hubHt - 80) * 500;
if (soil == BOUYANT){
cost += 20000;
}
cost *= nTurb;
assign("foundation_cost", var_data(cost));
return cost;
}
double erectionCost(double rating, double hubHt, int nTurb, int weatherDelayDays, int craneBreakdowns, int deliveryAssistRequired)
{
double cost = (37 * rating + 27000 * pow(nTurb, -0.42145) + (hubHt - 80) * 500)*nTurb;
if (deliveryAssistRequired){
cost += 60000 * nTurb;
}
cost += 20000 * weatherDelayDays + 35000 * craneBreakdowns + 181 * nTurb + 1834;
assign("erection_cost", var_data(cost));
return cost;
}
double electricalMaterialsCost(SiteTerrain terrain, TurbineLayout layout, double farmSize, double diameter, int nTurb, int padMountTransformer, double thermalBackfill)
{
double factor1 = 0.0;
double factor2 = 0.0;
double factor3 = 0.0;
if (layout == SIMPLE){
if (terrain == FLAT_TO_ROLLING){
factor1 = 66733.4;
factor2 = 27088.4;
factor3 = 545.4;
}
else if (terrain == RIDGE_TOP){
factor1 = 67519.4;
factor2 = 27874.4;
factor3 = 590.8;
}
else if (terrain == MOUNTAINOUS){
factor1 = 68305.4;
factor2 = 28660.4;
factor3 = 590.8;
}
}
else if (layout == COMPLEX){
if (terrain == FLAT_TO_ROLLING){
factor1 = 67519.4;
factor2 = 27874.4;
factor3 = 681.7;
}
else if (terrain == RIDGE_TOP){
factor1 = 68305.4;
factor2 = 28660.4;
factor3 = 727.2;
}
else if (terrain == MOUNTAINOUS){
factor1 = 69484.4;
factor2 = 29839.4;
factor3 = 727.2;
}
}
double cost;
if (padMountTransformer){
cost = nTurb*factor1;
}
else{
cost = nTurb*factor2;
}
cost += floor(farmSize / 25.0) * 35375 + floor(farmSize / 100.0) * 50000
+ diameter*nTurb*factor3 + thermalBackfill * 5 + 41945;
assign("electrical_materials_cost", var_data(cost));
return cost;
}
double electricalInstallationCost(SiteTerrain terrain, TurbineLayout layout, double farmSize, double diameter, int nTurb, double rockTrenchingLength, double overheadCollector)
{
double factor1 = 0.0;
double factor2 = 0.0;
double factor3 = 0.0;
if (layout == SIMPLE){
if (terrain == FLAT_TO_ROLLING){
factor1 = 7059.3;
factor2 = 352.4;
factor3 = 297.0;
}
else if (terrain == RIDGE_TOP){
factor1 = 7683.5;
factor2 = 564.3;
factor3 = 483.0;
}
else if (terrain == MOUNTAINOUS){
factor1 = 8305.0;
factor2 = 682.6;
factor3 = 579.0;
}
}
else if (layout == COMPLEX){
if (terrain == FLAT_TO_ROLLING){
factor1 = 7683.5;
factor2 = 564.9;
factor3 = 446.0;
}
else if (terrain == RIDGE_TOP){
factor1 = 8305.0;
factor2 = 866.8;
factor3 = 713.0;
}
else if (terrain == MOUNTAINOUS){
factor1 = 9240.0;
factor2 = 972.8;
factor3 = 792.0;
}
}
double cost = (int)(farmSize / 25.0) * 14985;
if (farmSize > 200){
cost += 300000;
}
else{
cost += 155000;
}
cost += nTurb*(factor1 + diameter*(factor2 + factor3*rockTrenchingLength / 100.0))
+ overheadCollector * 200000 + 10000;
assign("electrical_installation_cost", var_data(cost));
return cost;
}
double substationCost(double voltage, double farmSize)
{
double cost = 11652 * (voltage + farmSize) + 11795 * pow(farmSize, 0.3549) + 1526800;
assign("substation_cost", var_data(cost));
return cost;
}
double transmissionCost(double voltage, double distInter, int newSwitchyardRequired)
{
double cost = (1176 * voltage + 218257)*pow(distInter, 0.8937);
if (newSwitchyardRequired){
cost += 18115 * voltage + 165944;
}
assign("transmission_cost", var_data(cost));
return cost;
}
double projectMgmtCost(int constructionTime)
{
double cost;
if (constructionTime < 28){
cost = (53.333*constructionTime*constructionTime - 3442 * constructionTime
+ 209542)*(constructionTime + 2);
}
else{
cost = (constructionTime + 2) * 155000;
}
assign("project_mgmt_cost", var_data(cost));
return cost;
}
double developmentCost(double developmentFee)
{
double cost = developmentFee * 1000000;
assign("development_cost", var_data(cost));
return cost;
}
double insuranceMultiplierAndCost(double cost, double tcc, double farmSize, double foundationCost, int performanceBond)
{
double ins;
double pb_rate = 0;
if (performanceBond)
pb_rate = 10.0;
ins = cost / 1000 * (3.5 + 0.7 + 0.4 + 1.0 + pb_rate) //rates are per $1000
+ (tcc * farmSize) * (0.7 + 0.4 + 1.0 + pb_rate) //tcc in $/kW times farmSize in MW is equal to per $1000
+ 0.02 * foundationCost
+ 20000;
assign("insurance_cost", var_data(ins));
return ins;
}
double markupMultiplierAndCost(double cost, double contingency, double warranty, double useTax, double overhead, double profitMargin)
{
double markup;
markup = cost * (contingency + warranty + useTax + overhead + profitMargin) / 100.0; //convert from percentages to decimal
assign("markup_cost", var_data(markup));
return markup;
}
double totalCost(double rating, double diameter, double hubHt,
int nTurb, double voltage, double distInter,
SiteTerrain terrain, TurbineLayout layout, SoilCondition soil,
double farmSize, double tcc, double topMass,
int constructionTime, double buildingSize, double temporary,
double permanent, int weatherDelayDays, int craneBreakdowns,
int accessRoadEntrances,
int deliveryAssistRequired, int padMountTransformer,
int newSwitchyardRequired, double rockTrenchingLength,
double thermalBackfill, double overheadCollector,
int performanceBond, double contingency, double warranty,
double useTax, double overhead, double profitMargin,
double developmentFee, double transportDist)
{
//compute cost for all items EXCEPT turbine & transport- markup and insurance do not apply to turbine & transport costs
double cost = 0.0;
cost += engineeringCost(nTurb, farmSize);
cost += powerPerformanceCost(hubHt, permanent, temporary);
cost += siteCompoundCost(accessRoadEntrances, constructionTime, farmSize);
cost += buildingCost(buildingSize);
cost += transmissionCost(voltage, distInter, newSwitchyardRequired);
cost += developmentCost(developmentFee);
cost += accessRoadsCost(terrain, layout, nTurb, diameter, constructionTime, accessRoadEntrances);
double foundCost = foundationCost(rating, diameter, topMass, hubHt, soil, nTurb);
cost += foundCost;
cost += erectionCost(rating, hubHt, nTurb, weatherDelayDays, craneBreakdowns, deliveryAssistRequired);
cost += electricalMaterialsCost(terrain, layout, farmSize, diameter, nTurb, padMountTransformer, thermalBackfill);
cost += electricalInstallationCost(terrain, layout, farmSize, diameter, nTurb, rockTrenchingLength, overheadCollector);
cost += substationCost(voltage, farmSize);
cost += projectMgmtCost(constructionTime);
//now find insurance costs and markup costs using the current cost (before including turbine & transport)
double ins = insuranceMultiplierAndCost(cost, tcc, farmSize, foundCost, performanceBond);
double markup = markupMultiplierAndCost(cost, contingency, warranty, useTax, overhead, profitMargin);
cost += ins + markup;
//finally, add turbine & transport cost
cost += transportationCost(tcc, rating, nTurb, hubHt, transportDist);
//return the total cost
return cost;
}
void exec( ) throw( general_error )
{
// get values
double rating = (double) as_number("machine_rating");
double diameter = (double)as_number("rotor_diameter");
double hubHt = (double)as_number("hub_height");
int nTurb = as_integer("number_of_turbines");
double voltage = (double)as_number("interconnect_voltage");
double distInter = (double)as_number("distance_to_interconnect");
SiteTerrain terrain = (SiteTerrain) as_integer("site_terrain");
TurbineLayout layout = (TurbineLayout)as_integer("turbine_layout");
SoilCondition soil = (SoilCondition)as_integer("soil_condition");
double farmSize = cm_windbos::farmSize(rating, nTurb);
int constructionTime = (int)as_number("construction_time");
double buildingSize = (double)as_number("om_building_size");
double temporary = (double)as_number("quantity_test_met_towers");
double permanent = (double)as_number("quantity_permanent_met_towers");
int weatherDelayDays = (int)as_number("weather_delay_days");
int craneBreakdowns = (int)as_number("crane_breakdowns");
int accessRoadEntrances = (int)as_number("access_road_entrances");
double tcc = (double)as_number("turbine_capital_cost");
double topMass = (double)as_number("tower_top_mass");
int deliveryAssistRequired = as_integer("delivery_assist_required");
int padMountTransformer = as_integer("pad_mount_transformer_required");
int newSwitchyardRequired = as_integer("new_switchyard_required");
double rockTrenchingLength = (double)as_number("rock_trenching_required");
double thermalBackfill = (double)as_number("mv_thermal_backfill");
double overheadCollector = (double)as_number("mv_overhead_collector");
double performanceBond = (double)as_number("performance_bond");
double contingency = (double)as_number("contingency");
double warranty = (double)as_number("warranty_management");
double useTax = (double)as_number("sales_and_use_tax");
double overhead = (double)as_number("overhead");
double profitMargin = (double)as_number("profit_margin");
double developmentFee = (double)as_number("development_fee");
double transportDist = (double)as_number("turbine_transportation");
// run model (execute functions)
ssc_number_t output = totalCost(rating, diameter, hubHt, nTurb, voltage, distInter, terrain, layout, soil,
farmSize, tcc, topMass, constructionTime, buildingSize, temporary, permanent, weatherDelayDays, craneBreakdowns, accessRoadEntrances,
deliveryAssistRequired, padMountTransformer, newSwitchyardRequired, rockTrenchingLength, thermalBackfill, overheadCollector,
performanceBond, contingency, warranty, useTax, overhead, profitMargin, developmentFee, transportDist);
// assign outputs
assign( "project_total_budgeted_cost", var_data(output) );
}
};
DEFINE_MODULE_ENTRY( windbos, "Wind Balance of System cost model", 1 )
| 49.666081 | 255 | 0.498018 | [
"model"
] |
40dfcfde8800ea3b1ae0f4ffe619e6ecd3f50df3 | 3,890 | hpp | C++ | src/trigger_factory.hpp | ibm-openbmc/telemetry | 620c65ad386ea542bcc18122577a3aab6dbac96d | [
"Apache-2.0"
] | null | null | null | src/trigger_factory.hpp | ibm-openbmc/telemetry | 620c65ad386ea542bcc18122577a3aab6dbac96d | [
"Apache-2.0"
] | 2 | 2021-10-04T20:12:53.000Z | 2021-12-14T18:13:03.000Z | src/trigger_factory.hpp | ibm-openbmc/telemetry | 620c65ad386ea542bcc18122577a3aab6dbac96d | [
"Apache-2.0"
] | 2 | 2021-09-28T06:45:53.000Z | 2021-12-13T15:30:33.000Z | #pragma once
#include "interfaces/report_manager.hpp"
#include "interfaces/sensor.hpp"
#include "interfaces/threshold.hpp"
#include "interfaces/trigger_factory.hpp"
#include "sensor_cache.hpp"
#include "utils/dbus_mapper.hpp"
#include <sdbusplus/asio/object_server.hpp>
class TriggerFactory : public interfaces::TriggerFactory
{
public:
TriggerFactory(std::shared_ptr<sdbusplus::asio::connection> bus,
std::shared_ptr<sdbusplus::asio::object_server> objServer,
SensorCache& sensorCache);
std::unique_ptr<interfaces::Trigger>
make(const std::string& id, const std::string& name,
const std::vector<std::string>& triggerActions,
const std::vector<std::string>& reportIds,
interfaces::TriggerManager& triggerManager,
interfaces::JsonStorage& triggerStorage,
const LabeledTriggerThresholdParams& labeledThresholdParams,
const std::vector<LabeledSensorInfo>& labeledSensorsinfo)
const override;
std::vector<LabeledSensorInfo>
getLabeledSensorsInfo(boost::asio::yield_context& yield,
const SensorsInfo& sensorsInfo) const override;
std::vector<LabeledSensorInfo>
getLabeledSensorsInfo(const SensorsInfo& sensorsInfo) const override;
void updateThresholds(
std::vector<std::shared_ptr<interfaces::Threshold>>& currentThresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors,
const LabeledTriggerThresholdParams& newParams) const override;
void updateSensors(Sensors& currentSensors,
const std::vector<LabeledSensorInfo>& labeledSensorsInfo)
const override;
private:
std::shared_ptr<sdbusplus::asio::connection> bus;
std::shared_ptr<sdbusplus::asio::object_server> objServer;
SensorCache& sensorCache;
Sensors getSensors(
const std::vector<LabeledSensorInfo>& labeledSensorsInfo) const;
static std::vector<LabeledSensorInfo>
parseSensorTree(const std::vector<utils::SensorTree>& tree,
const SensorsInfo& sensorsInfo);
void updateDiscreteThresholds(
std::vector<std::shared_ptr<interfaces::Threshold>>& currentThresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors,
const std::vector<discrete::LabeledThresholdParam>& newParams) const;
void updateNumericThresholds(
std::vector<std::shared_ptr<interfaces::Threshold>>& currentThresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors,
const std::vector<numeric::LabeledThresholdParam>& newParams) const;
void makeDiscreteThreshold(
std::vector<std::shared_ptr<interfaces::Threshold>>& thresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors,
const discrete::LabeledThresholdParam& thresholdParam) const;
void makeNumericThreshold(
std::vector<std::shared_ptr<interfaces::Threshold>>& thresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors,
const numeric::LabeledThresholdParam& thresholdParam) const;
void makeOnChangeThreshold(
std::vector<std::shared_ptr<interfaces::Threshold>>& thresholds,
const std::vector<TriggerAction>& triggerActions,
const std::shared_ptr<std::vector<std::string>>& reportIds,
const Sensors& sensors) const;
};
| 42.282609 | 80 | 0.695116 | [
"vector"
] |
40e0037f751ed89a1d10ac6816703ea4da2f4d61 | 13,648 | hpp | C++ | Source/MainModule/Dynamics.hpp | seedsw23/MulticopterSim | b8d2d7ff58751229a20a3e619498974b58a80c89 | [
"MIT"
] | null | null | null | Source/MainModule/Dynamics.hpp | seedsw23/MulticopterSim | b8d2d7ff58751229a20a3e619498974b58a80c89 | [
"MIT"
] | null | null | null | Source/MainModule/Dynamics.hpp | seedsw23/MulticopterSim | b8d2d7ff58751229a20a3e619498974b58a80c89 | [
"MIT"
] | null | null | null | /*
* Header-only code for platform-independent flight dynamics
*
* Should work for any simulator, vehicle, or operating system
*
* Based on:
*
* @inproceedings{DBLP:conf/icra/BouabdallahMS04,
* author = {Samir Bouabdallah and Pierpaolo Murrieri and Roland Siegwart},
* title = {Design and Control of an Indoor Micro Quadrotor},
* booktitle = {Proceedings of the 2004 {IEEE} International Conference on Robotics and
* Automation, {ICRA} 2004, April 26 - May 1, 2004, New Orleans, LA, {USA}},
* pages = {4393--4398},
* year = {2004},
* crossref = {DBLP:conf/icra/2004},
* url = {https://doi.org/10.1109/ROBOT.2004.1302409},
* doi = {10.1109/ROBOT.2004.1302409},
* timestamp = {Sun, 04 Jun 2017 01:00:00 +0200},
* biburl = {https://dblp.org/rec/bib/conf/icra/BouabdallahMS04},
* bibsource = {dblp computer science bibliography, https://dblp.org}
* }
*
* Copyright (C) 2019 Simon D. Levy
*
* MIT License
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// #include "Utils.hpp"
#include "Transforms.hpp"
class Dynamics {
public:
/**
* Vehicle parameters
*/
typedef struct {
double b; // force constatnt [F=b*w^2]
double d; // torque constant [T=d*w^2]
double m; // mass [kg]
double Ix; // [kg*m^2]
double Iy; // [kg*m^2]
double Iz; // [kg*m^2]
double Jr; // prop inertial [kg*m^2]
double l; // arm length [m]
uint16_t maxrpm; // maxrpm
} vehicle_params_t;
/**
* World parameters
*/
typedef struct {
double g; // gravitational constant
} world_params_t;
/**
* Position map for state vector
*/
enum {
STATE_X,
STATE_X_DOT,
STATE_Y,
STATE_Y_DOT,
STATE_Z,
STATE_Z_DOT,
STATE_PHI,
STATE_PHI_DOT,
STATE_THETA,
STATE_THETA_DOT,
STATE_PSI,
STATE_PSI_DOT,
STATE_SIZE
};
/**
* Updates state.
*
* @param dt time in seconds since previous update
*/
void update(double dt)
{
// Use the current Euler angles to rotate the orthogonal thrust vector into the inertial frame.
// Negate to use NED.
double euler[3] = { _x[6], _x[8], _x[10] };
double accelNED[3] = {};
Transforms::bodyZToInertial(-_U1 / _vparams.m, euler, accelNED);
// We're airborne once net downward acceleration goes below zero
double netz = accelNED[2] + g;
// If we're airborne, check for low AGL on descent
if (_airborne) {
if (_agl <= 0 && netz >= 0) {
_airborne = false;
_x[STATE_PHI_DOT] = 0;
_x[STATE_THETA_DOT] = 0;
_x[STATE_PSI_DOT] = 0;
_x[STATE_X_DOT] = 0;
_x[STATE_Y_DOT] = 0;
_x[STATE_Z_DOT] = 0;
_x[STATE_PHI] = 0;
_x[STATE_THETA] = 0;
_x[STATE_Z] += _agl;
}
}
// If we're not airborne, we become airborne when downward acceleration has become negative
else {
_airborne = netz < 0;
}
// Once airborne, we can update dynamics
if (_airborne) {
// Compute the state derivatives using Equation 12
computeStateDerivative(accelNED, netz);
// Compute state as first temporal integral of first temporal derivative
for (uint8_t i = 0; i < 12; ++i) {
_x[i] += dt * _dxdt[i];
}
// Once airborne, inertial-frame acceleration is same as NED acceleration
_inertialAccel[0] = accelNED[0];
_inertialAccel[1] = accelNED[1];
_inertialAccel[2] = accelNED[2];
}
else {
//"fly" to agl=0
double vz = 5 * _agl;
_x[STATE_Z] += vz * dt;
}
updateGimbalDynamics(dt);
} // update
// State-vector accessor
double x(uint8_t k)
{
return _x[k];
}
private:
static constexpr world_params_t EARTH_PARAMS = {
9.80665 // g graviational constant
};
void construct(uint8_t motorCount, vehicle_params_t & vparams)
{
_motorCount = motorCount;
_rotorCount = motorCount; // can be overridden for thrust-vectoring
memcpy(&_vparams, &vparams, sizeof(vehicle_params_t));
for (uint8_t i = 0; i < 12; ++i) {
_x[i] = 0;
}
_omegas = new double[motorCount]();
_omegas2 = new double[motorCount]();
}
protected:
vehicle_params_t _vparams;
world_params_t _wparams;
Dynamics(uint8_t motorCount, vehicle_params_t & vparams)
{
construct(motorCount, vparams);
memcpy(&_wparams, &EARTH_PARAMS, sizeof(world_params_t));
}
Dynamics(uint8_t motorCount, vehicle_params_t & vparams, world_params_t & wparams)
{
construct(motorCount, vparams);
memcpy(&_wparams, &wparams, sizeof(world_params_t));
}
// Flag for whether we're airborne and can update dynamics
bool _airborne = false;
// Inertial-frame acceleration
double _inertialAccel[3] = {};
// y = Ax + b helper for frame-of-reference conversion methods
static void dot(double A[3][3], double x[3], double y[3])
{
for (uint8_t j = 0; j < 3; ++j) {
y[j] = 0;
for (uint8_t k = 0; k < 3; ++k) {
y[j] += A[j][k] * x[k];
}
}
}
// bodyToInertial method optimized for body X=Y=0
static void bodyZToInertial(double bodyZ, const double rotation[3], double inertial[3])
{
double phi = rotation[0];
double theta = rotation[1];
double psi = rotation[2];
double cph = cos(phi);
double sph = sin(phi);
double cth = cos(theta);
double sth = sin(theta);
double cps = cos(psi);
double sps = sin(psi);
// This is the rightmost column of the body-to-inertial rotation matrix
double R[3] = { sph * sps + cph * cps * sth,
cph * sps * sth - cps * sph,
cph * cth };
for (uint8_t i = 0; i < 3; ++i) {
inertial[i] = bodyZ * R[i];
}
}
// Height above ground, set by kinematics
double _agl = 0;
// universal constants
static constexpr double g = 9.80665; // might want to allow this to vary!
// state vector (see Eqn. 11) and its first temporal derivative
double _x[12] = {};
double _dxdt[12] = {};
// Values computed in Equation 6
double _U1 = 0; // total thrust
double _U2 = 0; // roll thrust right
double _U3 = 0; // pitch thrust forward
double _U4 = 0; // yaw thrust clockwise
double _Omega = 0; // torque clockwise
// Torques about Euler angles. We need motorvals for thrust vectoring.
virtual void computeTorques(double * motorvals, double & u2, double & u3, double & u4) = 0;
// radians per second for each motor, and their squared values
double* _omegas = NULL;
double* _omegas2 = NULL;
// quad, hexa, octo, etc.
uint8_t _rotorCount = 0;
// For thrust vectoring, we can have four motors: two rotors and two servos. For multirotors,
// rotorCount = motorCount
uint8_t _motorCount = 0;
virtual void updateGimbalDynamics(double dt) {}
/**
* Implements Equation 12 computing temporal first derivative of state.
* Should fill _dxdx[0..11] with appropriate values.
* @param accelNED acceleration in NED inertial frame
* @param netz accelNED[2] with gravitational constant added in
*/
void computeStateDerivative(double accelNED[3], double netz)
{
double phidot = _x[STATE_PHI_DOT];
double thedot = _x[STATE_THETA_DOT];
double psidot = _x[STATE_PSI_DOT];
double Ix = _vparams.Ix;
double Iy = _vparams.Iy;
double Iz = _vparams.Iz;
double Jr = _vparams.Jr;
_dxdt[0] = _x[STATE_X_DOT]; // x'
_dxdt[1] = accelNED[0]; // x''
_dxdt[2] = _x[STATE_Y_DOT]; // y'
_dxdt[3] = accelNED[1]; // y''
_dxdt[4] = _x[STATE_Z_DOT]; // z'
_dxdt[5] = netz; // z''
_dxdt[6] = phidot; // phi'
_dxdt[7] = psidot * thedot * (Iy - Iz) / Ix - Jr / Ix * thedot * _Omega + _U2 / Ix; // phi''
_dxdt[8] = thedot; // theta'
_dxdt[9] = -(psidot * phidot * (Iz - Ix) / Iy + Jr / Iy * phidot * _Omega + _U3 / Iy); // theta''
_dxdt[10] = psidot; // psi'
_dxdt[11] = thedot * phidot * (Ix - Iy) / Iz + _U4 / Iz; // psi''
}
/**
* Computes motor speed base on motor value
* @param motorval motor value in [0,1]
* @return motor speed in rad/s
*/
virtual double computeMotorSpeed(double motorval)
{
return motorval * _vparams.maxrpm * 3.14159 / 30;
}
public:
/**
* Destructor
*/
virtual ~Dynamics(void)
{
delete _omegas;
delete _omegas2;
}
/**
* Initializes kinematic pose, with flag for whether we're airbone (helps with testing gravity).
*
* @param rotation initial rotation
* @param airborne allows us to start on the ground (default) or in the air (e.g., gravity test)
*/
void init(double rotation[3], bool airborne = false)
{
// Always start at location (0,0,0)
_x[STATE_X] = 0;
_x[STATE_Y] = 0;
_x[STATE_Z] = 0;
_x[STATE_PHI] = rotation[0];
_x[STATE_THETA] = rotation[1];
_x[STATE_PSI] = rotation[2];
// Initialize velocities and airborne flag
_airborne = airborne;
_x[STATE_X_DOT] = 0;
_x[STATE_Y_DOT] = 0;
_x[STATE_Z_DOT] = 0;
_x[STATE_PHI_DOT] = 0;
_x[STATE_THETA_DOT] = 0;
_x[STATE_PSI_DOT] = 0;
// Initialize inertial frame acceleration in NED coordinates
bodyZToInertial(-g, rotation, _inertialAccel);
// We usuall start on ground, but can start in air for testing
_airborne = airborne;
}
/**
* Uses motor values to implement Equation 6.
*
* @param motorvals in interval [0,1] (rotors) or [-0.5,+0.5] (servos)
*/
void setMotors(double* motorvals)
{
// Convert the motor values to radians per second
for (unsigned int i = 0; i < _rotorCount; ++i) {
_omegas[i] = computeMotorSpeed(motorvals[i]); //rad/s
}
// Overall thrust U1 is sum of squared omegas
_U1 = 0;
for (unsigned int i = 0; i < _rotorCount; ++i) {
_omegas2[i] = _omegas[i] * _omegas[i];
_U1 += _vparams.b * _omegas2[i];
}
// Torque forces are computed differently for each vehicle configuration
double u2=0, u3=0, u4=0;
computeTorques(motorvals, u2, u3, u4);
_U2 = _vparams.l * _vparams.b * u2;
_U3 = _vparams.l * _vparams.b * u3;
_U4 = _vparams.b * u4;
}
/**
* Sets height above ground level (AGL).
* This method can be called by the kinematic visualization.
*/
void setAgl(double agl)
{
_agl = agl;
}
// Rotor direction for animation
virtual int8_t rotorDirection(uint8_t i) { (void)i; return 0; }
/**
* Gets motor count set by constructor.
* @return motor count
*/
uint8_t motorCount(void)
{
return _motorCount;
}
/**
* Gets rotor count set by constructor.
* @return rotor count
*/
uint8_t rotorCount(void)
{
return _rotorCount;
}
}; // class Dynamics
| 32.495238 | 109 | 0.486298 | [
"vector"
] |
40e0c61e776db08bbc7877954f5b38d3c7816ba7 | 553 | cpp | C++ | Codeforces/Gym/101170H.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2017-10-25T13:33:27.000Z | 2017-10-25T13:33:27.000Z | Codeforces/Gym/101170H.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | null | null | null | Codeforces/Gym/101170H.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2018-01-22T08:06:11.000Z | 2018-01-22T08:06:11.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef set<int> si;
ll solve(const string& num) {
ll ans = num[0] - '0';
for (int i = 1; i < num.size(); i++) {
ans <<= 1;
ans += (ans >> 1 & 1) ^ (num[i] - '0');
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
string a, b;
cin >> n >> a >> b;
cout << solve(b) - solve(a) - 1 << endl;
return 0;
} | 17.28125 | 43 | 0.564195 | [
"vector"
] |
40e7f5c909db34e09324d0f5ee10db99749aba5e | 1,164 | cpp | C++ | libs/pika/command_line_handling_local/tests/regressions/ignore_aliases_local.cpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | libs/pika/command_line_handling_local/tests/regressions/ignore_aliases_local.cpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | libs/pika/command_line_handling_local/tests/regressions/ignore_aliases_local.cpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 Nanmiao Wu
//
// SPDX-License-Identifier: BSL-1.0
// 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 <pika/local/config.hpp>
#include <pika/local/init.hpp>
#include <pika/modules/testing.hpp>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
int pika_main(int argc, char* argv[])
{
PIKA_TEST_EQ(argc, 2);
PIKA_TEST_EQ(std::string(argv[1]), std::string("-wobble=1"));
return pika::local::finalize();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// pass unknown command line option that would conflict with predefined
// alias (-w)
std::vector<std::string> const cfg = {
"--pika:ini=pika.commandline.allow_unknown!=1",
"--pika:ini=pika.commandline.aliasing!=0"};
pika::local::init_params init_args;
init_args.cfg = cfg;
PIKA_TEST_EQ(pika::local::init(pika_main, argc, argv, init_args), 0);
return pika::util::report_errors();
}
| 30.631579 | 80 | 0.585052 | [
"vector"
] |
40ee118966d7aa67c854f505babf3631dec3fd7f | 2,450 | hpp | C++ | include/fe/subsystems/scripting/functionHander.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 1 | 2018-06-15T23:49:37.000Z | 2018-06-15T23:49:37.000Z | include/fe/subsystems/scripting/functionHander.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 5 | 2017-04-23T03:25:10.000Z | 2018-02-23T07:48:16.000Z | include/fe/subsystems/scripting/functionHander.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | null | null | null | // functionHandler.hpp
// Handles the registration of functions
#pragma once
#include "fe/flatEngineExport.hpp"
#include "fe/objectManagement/str.hpp"
#include "fe/typeDefines.hpp"
#include <string>
#include <sol.hpp>
#include <vector>
#include "scriptHelpers.hpp"
#include "luaFunctionReference.hpp"
namespace fe
{
class functionHandler
{
private:
sol::state &m_state;
std::vector<fe::luaFunctionReference*> m_registeredFunctions;
public:
FLAT_ENGINE_API functionHandler(sol::state &state);
template<typename ...Functions, typename T>
void registerCPPObjectFunction(const std::string &functionName, T *objRef, Functions &&...funcs);
template<typename ...Functions>
void registerCPPFunction(const std::string &functionName, Functions &&...funcs);
template<typename ...Args>
decltype(auto) call(const std::string &functionName, Args &&...args);
FLAT_ENGINE_API void reloadAllLuaFunctions();
FLAT_ENGINE_API void reloadLuaFunction(fe::luaFunctionReference &function);
FLAT_ENGINE_API fe::luaFunctionReference &getLuaFunction(const std::string &functionName);
FLAT_ENGINE_API fe::luaFunctionReference &getLuaFunction(const std::string &luaPathName, const std::string &functionName);
FLAT_ENGINE_API void shutDown();
};
template<typename ...Functions, typename T>
void functionHandler::registerCPPObjectFunction(const std::string &functionName, T *objRef, Functions &&...funcs)
{
m_state.set_function(functionName, fe::imp::getFunctionOverload(std::forward<Functions>(funcs)...), objRef);
}
template<typename ...Functions>
void functionHandler::registerCPPFunction(const std::string &functionName, Functions &&...funcs)
{
m_state.set_function(functionName, fe::imp::getFunctionOverload(std::forward<Functions>(funcs)...));
}
template<typename ...Args>
decltype(auto) functionHandler::call(const std::string &functionName, Args &&...args)
{
return m_registeredFunctions[functionName]->call(std::forward<Args>(args)...);
}
}
| 40.833333 | 142 | 0.615102 | [
"vector"
] |
40ef1b9cb9013fc1ff9327f682a1b95741d1e169 | 9,698 | cc | C++ | content/renderer/media/webrtc_audio_renderer.cc | leiferikb/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-15T15:17:43.000Z | 2021-11-15T15:17:43.000Z | content/renderer/media/webrtc_audio_renderer.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media/webrtc_audio_renderer.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:24:02.000Z | 2020-11-04T07:24:02.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/webrtc_audio_renderer.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "content/renderer/media/audio_device_factory.h"
#include "content/renderer/media/audio_hardware.h"
#include "content/renderer/media/renderer_audio_output_device.h"
#include "content/renderer/media/webrtc_audio_device_impl.h"
#include "media/audio/audio_util.h"
#include "media/audio/sample_rates.h"
#if defined(OS_WIN)
#include "media/audio/win/core_audio_util_win.h"
#endif
namespace content {
namespace {
// Supported hardware sample rates for output sides.
#if defined(OS_WIN) || defined(OS_MACOSX)
// media::GetAudioOutputHardwareSampleRate() asks the audio layer
// for its current sample rate (set by the user) on Windows and Mac OS X.
// The listed rates below adds restrictions and Initialize()
// will fail if the user selects any rate outside these ranges.
int kValidOutputRates[] = {96000, 48000, 44100};
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
int kValidOutputRates[] = {48000, 44100};
#elif defined(OS_ANDROID)
// On Android, the most popular sampling rate is 16000.
int kValidOutputRates[] = {48000, 44100, 16000};
#else
int kValidOutputRates[] = {44100};
#endif
// TODO(xians): Merge the following code to WebRtcAudioCapturer, or remove.
enum AudioFramesPerBuffer {
k160,
k320,
k440, // WebRTC works internally with 440 audio frames at 44.1kHz.
k480,
k640,
k880,
k960,
k1440,
k1920,
kUnexpectedAudioBufferSize // Must always be last!
};
// Helper method to convert integral values to their respective enum values
// above, or kUnexpectedAudioBufferSize if no match exists.
AudioFramesPerBuffer AsAudioFramesPerBuffer(int frames_per_buffer) {
switch (frames_per_buffer) {
case 160: return k160;
case 320: return k320;
case 440: return k440;
case 480: return k480;
case 640: return k640;
case 880: return k880;
case 960: return k960;
case 1440: return k1440;
case 1920: return k1920;
}
return kUnexpectedAudioBufferSize;
}
void AddHistogramFramesPerBuffer(int param) {
AudioFramesPerBuffer afpb = AsAudioFramesPerBuffer(param);
if (afpb != kUnexpectedAudioBufferSize) {
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
afpb, kUnexpectedAudioBufferSize);
} else {
// Report unexpected sample rates using a unique histogram name.
UMA_HISTOGRAM_COUNTS("WebRTC.AudioOutputFramesPerBufferUnexpected", param);
}
}
} // namespace
WebRtcAudioRenderer::WebRtcAudioRenderer(int source_render_view_id)
: state_(UNINITIALIZED),
source_render_view_id_(source_render_view_id),
source_(NULL),
play_ref_count_(0) {
}
WebRtcAudioRenderer::~WebRtcAudioRenderer() {
DCHECK_EQ(state_, UNINITIALIZED);
buffer_.reset();
}
bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
// Ask the browser for the default audio output hardware sample-rate.
// This request is based on a synchronous IPC message.
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
// Verify that the reported output hardware sample rate is supported
// on the current platform.
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
// Windows
#if defined(OS_WIN)
// Always use stereo rendering on Windows.
channel_layout = media::CHANNEL_LAYOUT_STEREO;
// Render side: AUDIO_PCM_LOW_LATENCY is based on the Core Audio (WASAPI)
// API which was introduced in Windows Vista. For lower Windows versions,
// a callback-driven Wave implementation is used instead. An output buffer
// size of 10ms works well for WASAPI but 30ms is needed for Wave.
// Use different buffer sizes depending on the current hardware sample rate.
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
// We do run at 44.1kHz at the actual audio layer, but ask for frames
// at 44.0kHz to ensure that we can feed them to the webrtc::VoiceEngine.
// TODO(henrika): figure out why we seem to need 20ms here for glitch-
// free audio.
buffer_size = 2 * 440;
}
// Windows XP and lower can't cope with 10 ms output buffer size.
// It must be extended to 30 ms (60 ms will be used internally by WaveOut).
if (!media::CoreAudioUtil::IsSupported()) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
// Render side: AUDIO_PCM_LOW_LATENCY on Mac OS X is based on a callback-
// driven Core Audio implementation. Tests have shown that 10ms is a suitable
// frame size to use for 96kHz, 48kHz and 44.1kHz.
// Use different buffer sizes depending on the current hardware sample rate.
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
// We do run at 44.1kHz at the actual audio layer, but ask for frames
// at 44.0kHz to ensure that we can feed them to the webrtc::VoiceEngine.
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
// Based on tests using the current ALSA implementation in Chrome, we have
// found that 10ms buffer size on the output side works fine.
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
// Store utilized parameters to ensure that we can check them
// after a successful initialization.
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
// Allocate local audio buffers based on the parameters above.
// It is assumed that each audio sample contains 16 bits and each
// audio frame contains one or two audio samples depending on the
// number of channels.
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
// Configure the audio rendering client and start the rendering.
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
void WebRtcAudioRenderer::Start() {
// TODO(xians): refactor to make usage of Start/Stop more symmetric.
NOTIMPLEMENTED();
}
void WebRtcAudioRenderer::Play() {
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
DCHECK(play_ref_count_ == 0 || state_ == PLAYING);
++play_ref_count_;
state_ = PLAYING;
}
void WebRtcAudioRenderer::Pause() {
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
DCHECK_EQ(state_, PLAYING);
DCHECK_GT(play_ref_count_, 0);
if (!--play_ref_count_)
state_ = PAUSED;
}
void WebRtcAudioRenderer::Stop() {
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
source_->RemoveRenderer(this);
source_ = NULL;
sink_->Stop();
state_ = UNINITIALIZED;
}
void WebRtcAudioRenderer::SetVolume(float volume) {
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
sink_->SetVolume(volume);
}
base::TimeDelta WebRtcAudioRenderer::GetCurrentRenderTime() const {
return base::TimeDelta();
}
bool WebRtcAudioRenderer::IsLocalRenderer() const {
return false;
}
int WebRtcAudioRenderer::Render(media::AudioBus* audio_bus,
int audio_delay_milliseconds) {
{
base::AutoLock auto_lock(lock_);
if (!source_)
return 0;
// We need to keep render data for the |source_| reglardless of |state_|,
// otherwise the data will be buffered up inside |source_|.
source_->RenderData(reinterpret_cast<uint8*>(buffer_.get()),
audio_bus->channels(), audio_bus->frames(),
audio_delay_milliseconds);
// Return 0 frames to play out silence if |state_| is not PLAYING.
if (state_ != PLAYING)
return 0;
}
// Deinterleave each channel and convert to 32-bit floating-point
// with nominal range -1.0 -> +1.0 to match the callback format.
audio_bus->FromInterleaved(buffer_.get(), audio_bus->frames(),
params_.bits_per_sample() / 8);
return audio_bus->frames();
}
void WebRtcAudioRenderer::OnRenderError() {
NOTIMPLEMENTED();
LOG(ERROR) << "OnRenderError()";
}
} // namespace content
| 32.986395 | 79 | 0.712621 | [
"render"
] |
40efeaa333c4a4786599539494053e899075ff7f | 3,741 | cc | C++ | sources/Program.cc | castel/castel | 84f022537c1dd201e41937b795487e52402f8627 | [
"Unlicense"
] | null | null | null | sources/Program.cc | castel/castel | 84f022537c1dd201e41937b795487e52402f8627 | [
"Unlicense"
] | null | null | null | sources/Program.cc | castel/castel | 84f022537c1dd201e41937b795487e52402f8627 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <castel/ast/tools/List.hh>
#include <castel/ast/Statement.hh>
#include <castel/runtime/boxes/Boolean.hh>
#include <castel/runtime/boxes/Class.hh>
#include <castel/runtime/boxes/Dict.hh>
#include <castel/runtime/boxes/Function.hh>
#include <castel/runtime/boxes/List.hh>
#include <castel/runtime/boxes/Null.hh>
#include <castel/runtime/boxes/Number.hh>
#include <castel/runtime/boxes/Object.hh>
#include <castel/runtime/boxes/String.hh>
#include <castel/runtime/boxes/Undefined.hh>
#include <castel/runtime/Box.hh>
#include <castel/toolchain/Source.hh>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Module.h>
#include "Evaluator.hh"
#include "Program.hh"
#include "REPL.hh"
castel::toolchain::Source Program::makeSource( std::string const & from ) const
{
if ( from == "-" ) {
return castel::toolchain::Source::fromStream( std::cin );
} else {
return castel::toolchain::Source::fromFile( from );
}
}
std::string Program::formatBox( castel::runtime::Box * box ) const
{
std::ostringstream ss;
if ( dynamic_cast< castel::runtime::boxes::Class * >( box ) )
ss << "<Class>";
if ( dynamic_cast< castel::runtime::boxes::Function * >( box ) )
ss << "<Function>";
if ( dynamic_cast< castel::runtime::boxes::Number * >( box ) )
ss << "<Number : " << static_cast< castel::runtime::boxes::Number * >( box )->value( ) << ">";
if ( dynamic_cast< castel::runtime::boxes::Boolean * >( box ) )
ss << "<Boolean : " << static_cast< castel::runtime::boxes::Boolean * >( box )->value( ) << ">";
if ( dynamic_cast< castel::runtime::boxes::String * >( box ) )
ss << "<String : " << static_cast< castel::runtime::boxes::String * >( box )->value( ) << ">";
if ( dynamic_cast< castel::runtime::boxes::Null * >( box ) )
ss << "<Null>";
if ( dynamic_cast< castel::runtime::boxes::Undefined * >( box ) )
ss << "<Undefined>";
if ( dynamic_cast< castel::runtime::boxes::Dict * >( box ) )
ss << "<Dict>";
if ( dynamic_cast< castel::runtime::boxes::List * >( box ) )
ss << "<List>";
if ( dynamic_cast< castel::runtime::boxes::Object * >( box ) )
ss << "<Instance>";
return ss.str( );
}
int Program::help( void ) const
{
std::cerr << mOptionBag.usageString( );
return 1;
}
int Program::checkSyntax( void ) const
{
std::cerr << "Not yet implemented." << std::endl;
return 1;
}
int Program::emitLLVM( void ) const
{
Evaluator evaluator;
castel::toolchain::Source source = this->makeSource( mOptionBag.inputFile( ) );
llvm::Module * module = evaluator.compile( source );
llvm::legacy::PassManager passManager;
passManager.add( llvm::createPrintModulePass( llvm::outs( ) ) );
passManager.run( * module );
return 0;
}
int Program::interpret( void ) const
{
Evaluator evaluator;
castel::toolchain::Source source = this->makeSource( mOptionBag.inputFile( ) );
castel::runtime::Box * box = evaluator.run( source );
if ( dynamic_cast< castel::runtime::boxes::Undefined * >( box ) == nullptr )
std::cout << "Program returned " << this->formatBox( box ) << std::endl;
return 0;
}
int Program::run( void ) const
{
if ( mOptionBag.help( ) ) {
return this->help( );
} else if ( mOptionBag.checkSyntax( ) ) {
return this->checkSyntax( );
} else if ( mOptionBag.emitLLVM( ) ) {
return this->emitLLVM( );
} else if ( mOptionBag.inputFile( ) != "" ) {
return this->interpret( );
} else {
return REPL( ).run( );
}
}
| 27.91791 | 104 | 0.618284 | [
"object"
] |
40f268f889bd538f73b8d6597502161670a3844d | 19,331 | cc | C++ | tensorflow/compiler/xla/service/while_loop_analysis.cc | Harry-Zhi/tensorflow | e0f06df3841562abfe17598fd86dcb59f2e1398c | [
"Apache-2.0"
] | 6 | 2019-02-05T22:36:51.000Z | 2022-01-14T03:50:57.000Z | tensorflow/compiler/xla/service/while_loop_analysis.cc | dipu989/tensorflow | 3e21fe5faedab3a8258d344c8ad1cec2612a8aa8 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xla/service/while_loop_analysis.cc | dipu989/tensorflow | 3e21fe5faedab3a8258d344c8ad1cec2612a8aa8 | [
"Apache-2.0"
] | 8 | 2016-01-14T13:12:56.000Z | 2021-04-09T10:20:53.000Z | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/while_loop_analysis.h"
#include "absl/base/casts.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
namespace xla {
using absl::nullopt;
using absl::optional;
namespace m = match;
// Finds and returns the non-constant operand in instr.
//
// CHECK-fails if instr doesn't have exactly one unique non-constant operand.
static const HloInstruction* NonConstantOperand(const HloInstruction* instr) {
const HloInstruction* result = nullptr;
for (const HloInstruction* operand : instr->operands()) {
if (!operand->IsConstant()) {
if (result != nullptr) {
CHECK_EQ(result, operand);
}
result = operand;
}
}
CHECK_NE(result, nullptr);
return result;
}
// If all of instr's operands are either constants or have the form
// get-tuple-element(gte_operand, N)
// for the same value N, returns N. Otherwise, returns nullopt.
static optional<int64> GetGTEOperandIndex(const HloInstruction* instr,
const HloInstruction* gte_operand) {
VLOG(2) << "GetGTEOperandIndex(" << instr->ToString() << ", "
<< gte_operand->ToString() << ")";
// Among the operands of `instr`, find one that is a get-tuple-element op.
auto gte_it = c_find_if(instr->operands(), [](const HloInstruction* instr) {
return instr->opcode() == HloOpcode::kGetTupleElement;
});
if (gte_it == instr->operands().end()) {
VLOG(2) << "instr does not have a gte operand.";
return nullopt;
}
// All operands of `instr` must be either constants or of the form
// get-tuple-element(gte_operand, tuple_idx)
// for the same value tuple_idx.
int64 tuple_idx = (*gte_it)->tuple_index();
for (const HloInstruction* operand : instr->operands()) {
if (!Match(operand, m::Constant()) &&
!Match(operand,
m::GetTupleElement(m::Op().Is(gte_operand), tuple_idx))) {
VLOG(2)
<< "instr uses something other than a constant or gte(gte_operand, "
<< tuple_idx << "): " << operand->ToString();
return nullopt;
}
}
return tuple_idx;
}
// Tries to get the tuple index of the induction variable of a while loop.
//
// Checks that the loop condition and root both plumb the induction variable
// through the same tuple index, and that they both apply exactly one op to the
// induction variable before deciding whether to do another loop iteration (in
// the loop condition's case) or packing the induction variable into the result
// tuple (in the loop body's case).
//
// Specifically, checks that the loop condition has structure
//
// root = op(constants, get-tuple-elem(param0, N), constants)
//
// and the loop body has the structure
//
// inc = op(constants, get-tuple-elem(param0, N), constants)
// root = tuple(..., inc, ...) // inc is N'th operand of tuple().
//
// If so, returns N. Otherwise, returns nullopt.
static optional<int64> GetLoopInductionVarTupleIdx(
const HloInstruction* while_op) {
CHECK_EQ(while_op->opcode(), HloOpcode::kWhile);
VLOG(2) << "Finding induction variable for loop "
<< while_op->ToShortString();
// The while_cond computation should have the form
//
// while_cond_root =
// op(constants, get-tuple-elem(while_cond_param, N), constants).
//
// If it does, set indvar_tuple_idx to N.
auto* while_cond = while_op->while_condition();
auto* while_cond_root = while_cond->root_instruction();
auto* while_cond_param = while_cond->parameter_instruction(0);
optional<int64> indvar_tuple_idx =
GetGTEOperandIndex(while_cond_root, while_cond_param);
if (!indvar_tuple_idx) {
VLOG(2) << "Induction variable not found in loop condition: "
<< while_cond->root_instruction()->ToString();
return nullopt;
}
// The while_body computation should have the form
//
// while_body_inc =
// op(constants, get-tuple-elem(while_body_param, N), constants)
// while_body_root = tuple(..., while_body_inc, ...)
//
// where while_body_inc is operand N of while_body_root.
auto* while_body = while_op->while_body();
auto* while_body_root = while_body->root_instruction();
if (while_body_root->opcode() != HloOpcode::kTuple) {
VLOG(2) << "While body's root is not a tuple instruction: "
<< while_body_root->ToString();
return nullopt;
}
auto* while_body_inc = while_body_root->operand(*indvar_tuple_idx);
auto* while_body_param = while_body->parameter_instruction(0);
optional<int64> while_body_indvar_tuple_idx =
GetGTEOperandIndex(while_body_inc, while_body_param);
if (!while_body_indvar_tuple_idx) {
VLOG(2)
<< "Induction variable not found in while body increment instruction: "
<< while_body_inc->ToString();
return nullopt;
}
if (while_body_indvar_tuple_idx != indvar_tuple_idx) {
VLOG(2) << "Tuple index of induction variable does not match between loop "
"condition ("
<< *indvar_tuple_idx << ") and while body ("
<< *while_body_indvar_tuple_idx << ")";
return nullopt;
}
// Finally, check that the while loop's initial value is a tuple with enough
// elements.
auto* while_init = while_op->operand(0);
if (while_init->opcode() != HloOpcode::kTuple) {
VLOG(2) << "While init expected to be a tuple: " << while_init->ToString();
return nullopt;
}
VLOG(2) << "Induction variable's tuple index: " << *indvar_tuple_idx;
return indvar_tuple_idx;
}
// Converts the given literal to a scalar int64, if possible.
//
// Fails if the literal is not an integral type or if the value it contains
// cannot be represented in an int64.
static optional<int64> LiteralAsScalarInt64(const Literal& l) {
if (!ShapeUtil::IsEffectiveScalar(l.shape())) {
VLOG(2) << "literal is not an effective scalar: " << l.ToString();
return nullopt;
}
switch (l.shape().element_type()) {
case S8:
return l.GetFirstElement<int8>();
case S16:
return l.GetFirstElement<int16>();
case S32:
return l.GetFirstElement<int32>();
case S64:
return l.GetFirstElement<int64>();
case U8:
return l.GetFirstElement<uint8>();
case U16:
return l.GetFirstElement<uint16>();
case U32:
return l.GetFirstElement<uint32>();
case U64: {
uint64 v = l.GetFirstElement<uint64>();
if (v > static_cast<uint64>(std::numeric_limits<int64>::max())) {
VLOG(2) << "uint64 literal is out of range for int64: " << v;
return nullopt;
}
return v;
}
default:
VLOG(2) << "literal is of non-integral type " << l.shape().ToString();
return nullopt;
}
}
// Computes a + b, returning nullopt if it overflows.
optional<int64> CheckedAdd(int64 a, int64 b) {
// Overflow occurred iff `a` and `b` have the same sign and `a + b` has a
// different sign, see Hacker's Delignt 2nd Ed. pp 28.
uint64 aa = absl::bit_cast<uint64>(a);
uint64 bb = absl::bit_cast<uint64>(b);
int64 result = absl::bit_cast<int64>(aa + bb);
if (a >= 0 == b >= 0 && result >= 0 != a >= 0) {
return nullopt;
}
return result;
}
// Computes a - b, returning nullopt if it overflows.
optional<int64> CheckedSubtract(int64 a, int64 b) {
uint64 aa = absl::bit_cast<uint64>(a);
uint64 bb = absl::bit_cast<uint64>(b);
int64 result = absl::bit_cast<int64>(aa - bb);
// Overflow occurred iff `a` and `b` have different signs and the sign of
// `a - b` is the same as that of `b`, see Hacker's Delight 2nd Ed. pp 29.
if (a >= 0 != b >= 0 && result >= 0 == b >= 0) {
return nullopt;
}
return result;
}
// Check if
// - `i` is initialized to a scalar constant K (namely, `indvar_init`),
// - the while condition does `i < N` or `i <= N`, and
// - the while body does `i++`.
// If so, it's trivial to compute the loop bound.
static optional<int64> PatternMatchLoopTripCount(HloInstruction* while_op,
int64 indvar_tuple_idx,
const Literal& indvar_init) {
// First, find the scalar constant K that `i` is initialized to.
optional<int64> indvar_init_val = LiteralAsScalarInt64(indvar_init);
if (!indvar_init_val) {
VLOG(2) << "Pattern-match failed: induction variable init is not a "
"constant scalar representable as an int64: "
<< indvar_init.ToString();
return nullopt;
}
// Check that `i` goes as `i++` in the while body.
//
// TODO(jlebar): We could also handle i-- and other idioms.
auto* while_body = while_op->while_body();
auto* while_body_indvar_update =
while_body->root_instruction()->operand(indvar_tuple_idx);
auto* while_body_indvar = NonConstantOperand(while_body_indvar_update);
if (!Match(while_body_indvar_update,
m::AddAnyOrder(m::Op().Is(while_body_indvar),
m::ConstantEffectiveScalar(1)))) {
VLOG(2) << "Pattern-match failed: induction variable does not go as i++: "
<< while_body_indvar_update->ToString();
return nullopt;
}
// Check that we do op(i, N) or op(N, i) as the while condition. Capture the
// value N.
auto* while_cond = while_op->while_condition();
auto* while_cond_root = while_cond->root_instruction();
auto* while_cond_indvar = NonConstantOperand(while_cond_root);
HloInstruction* while_cond_bound = nullptr;
if (!Match(while_cond_root,
m::Op().WithBinaryOperandsAnyOrder(
m::Op().Is(while_cond_indvar),
m::ConstantEffectiveScalar(&while_cond_bound)))) {
VLOG(2) << "Pattern-match failed: while condition is not of the form "
"op(i, N) or op(N, i).";
return nullopt;
}
// Note: If this succeeds, the constant `N` is representable as an int64 --
// that is, if it's an XLA U64, it fits within an int64.
optional<int64> while_cond_bound_val =
LiteralAsScalarInt64(while_cond_bound->literal());
if (!while_cond_bound_val) {
VLOG(2) << "Pattern-match failed: while condition induction variable is "
"not a constant scalar representable as an int64.";
return nullopt;
}
// Handle `i = K; i < N; ++i`.
if (Match(while_cond_root,
m::Op()
.WithOpcode(HloOpcode::kLt)
.WithOperand(0, m::Op().Is(while_cond_indvar)))) {
VLOG(2) << "Pattern-match succeeded: loop condition is i < N: "
<< while_cond_root->ToString();
optional<int64> trips =
CheckedSubtract(*while_cond_bound_val, *indvar_init_val);
if (trips) {
return std::max(int64{0}, *trips);
} else {
VLOG(2) << "Pattern-match failed: Trip count exceeds INT64_MAX.";
return nullopt;
}
}
// Handle `i = K; i <= N; ++i`.
if (Match(while_cond_root,
m::Op()
.WithOpcode(HloOpcode::kLe)
.WithOperand(0, m::Op().Is(while_cond_indvar)))) {
VLOG(2) << "Pattern-match succeeded: loop condition is i <= N: "
<< while_cond_root->ToString();
optional<int64> trips =
CheckedSubtract(*while_cond_bound_val, *indvar_init_val);
if (!trips) {
VLOG(2) << "Pattern-match failed: Trip count exceeds INT64_MAX";
return nullopt;
}
trips = CheckedAdd(*trips, 1);
if (!trips) {
VLOG(2) << "Pattern-match failed: Trip count exceeds INT64_MAX";
return nullopt;
}
return std::max<int64>(0, *trips);
}
VLOG(2) << "Pattern-match failed: while condition follows unknown pattern: "
<< while_cond_root->ToString();
return nullopt;
}
optional<int64> ComputeWhileLoopTripCount(HloInstruction* while_op,
int64 max_brute_force_iters) {
VLOG(2) << "Getting trip count for loop " << while_op->ToString();
// The loop's induction variable is found at
//
// get-tuple-elem(comp->parameter_instruction(0), *indvar_tuple_idx),
//
// where comp is while_op->while_body() or while_op->while_condition().
optional<int64> indvar_tuple_idx = GetLoopInductionVarTupleIdx(while_op);
if (!indvar_tuple_idx) {
return nullopt;
}
// Now that we know the index of the induction variable, we can we can try to
// compute how many times the loop executes. Start by computing the induction
// variable's initial value.
HloEvaluator evaluator(/*max_loop_iterations=*/0);
auto* while_init = while_op->mutable_operand(0);
auto* indvar_init = while_init->mutable_operand(*indvar_tuple_idx);
StatusOr<Literal> indvar_init_result = evaluator.Evaluate(indvar_init);
if (!indvar_init_result.ok()) {
VLOG(2) << "Couldn't evaluate induction variable init, "
<< indvar_init_result.status() << ", " << indvar_init->ToString();
return nullopt;
}
Literal indvar_iter_val = std::move(indvar_init_result).ValueOrDie();
// First, try to pattern-match.
if (auto trip_count = PatternMatchLoopTripCount(while_op, *indvar_tuple_idx,
indvar_iter_val)) {
return trip_count;
}
// If our pattern-match failed, try brute-forcing the loop trip count.
auto* while_body = while_op->while_body();
auto* while_body_indvar_update =
while_body->root_instruction()->operand(*indvar_tuple_idx);
auto* while_body_indvar = NonConstantOperand(while_body_indvar_update);
auto* while_cond = while_op->while_condition();
auto* while_cond_root = while_cond->root_instruction();
auto* while_cond_indvar = NonConstantOperand(while_cond_root);
for (int64 trip_count = 0; trip_count != max_brute_force_iters + 1;
++trip_count) {
StatusOr<Literal> result = evaluator.EvaluateWithSubstitutions(
while_cond_root, {{while_cond_indvar, &indvar_iter_val}});
if (!result.ok()) {
VLOG(2) << "Couldn't evaluate while cond: " << result.status();
return nullopt;
}
if (result.ValueOrDie().data<bool>() == absl::Span<const bool>{false}) {
VLOG(2) << "Loop has static trip count of " << trip_count;
return trip_count;
}
// Calculate the value of the induction variable after one iteration of the
// loop, and check whether the while condition is true with this new value.
StatusOr<Literal> indvar_next_result = evaluator.EvaluateWithSubstitutions(
while_body_indvar_update, {{while_body_indvar, &indvar_iter_val}});
if (!indvar_next_result.ok()) {
VLOG(2) << "Couldn't evaluate induction variable update: "
<< indvar_next_result.status();
return nullopt;
}
indvar_iter_val = std::move(indvar_next_result).ValueOrDie();
}
VLOG(2) << "Loop has unknown trip count.";
return nullopt;
}
// If the only user of this instruction is a get-tuple-element, return that
// get-tuple-element, otherwise return null. If this runs before CSE/DCE, we may
// get a false negative if there are several copies of the same GTE, or there
// are unused GTEs, but we can live with this.
static HloInstruction* GetOnlyGTE(HloInstruction* inst) {
if (inst->user_count() != 1) {
return nullptr;
}
HloInstruction* user = inst->users().back();
if (user->opcode() != HloOpcode::kGetTupleElement) {
return nullptr;
}
return user;
}
optional<int64> ComputeWhileLoopTripCountUpperBound(HloInstruction* while_op) {
// If we know the exact trip count, it's also the upper bound.
auto exact_trip_count = ComputeWhileLoopTripCount(while_op);
if (exact_trip_count) {
VLOG(2) << "Loop has exact trip count.";
return exact_trip_count;
}
// There is one more case we know how to handle. If the loop condition only
// looks at one element of the tuple, and the loop body sets this element to a
// constant, there are two options:
// 1) Evaluating the condition on this constant returns true. In this case,
// the loop either executes 0 times, or is an infinite loop, depending on the
// init value.
// 2) Evaluating the condition on this constant returns false. In this case,
// the loop executes 0 or 1 times, depending on the init value. This means
// that, regardless of the init value, the upper bound on the trip count is 1.
// Check whether the condition depends on a single parameter, and find out
// which.
auto* while_cond = while_op->while_condition();
auto* while_cond_param = while_cond->parameter_instruction(0);
auto* cond_gte = GetOnlyGTE(while_cond_param);
if (!cond_gte) {
VLOG(2) << "Induction variable not found in loop condition: "
<< while_cond->root_instruction()->ToString();
return nullopt;
}
// Now check whether this gets set to a constant by the while body.
auto* while_body = while_op->while_body();
auto* while_body_root = while_body->root_instruction();
if (while_body_root->opcode() != HloOpcode::kTuple) {
VLOG(3) << "While body's root is not a tuple instruction: "
<< while_body_root->ToString();
return nullopt;
}
int64 indvar_index = cond_gte->tuple_index();
auto* while_body_indvar = while_body_root->operand(indvar_index);
if (while_body_indvar->opcode() != HloOpcode::kConstant) {
VLOG(3) << "While body does not set the IV to a constant: "
<< while_body_indvar->ToString();
return nullopt;
}
// We have a constant. Evaluate the condition on this constant.
HloEvaluator evaluator(/*max_loop_iterations=*/0);
Literal fake_input = Literal::CreateFromShape(while_cond_param->shape());
TF_CHECK_OK(fake_input.CopyFrom(while_body_indvar->literal(),
/*dest_shape_index=*/{indvar_index},
/*src_shape_index=*/{}));
StatusOr<Literal> eval_result =
evaluator.Evaluate(*while_cond, {std::move(fake_input)});
if (!eval_result.ok()) {
VLOG(2) << "Couldn't evaluate while loop condition.";
return nullopt;
}
Literal cond_result_pred = std::move(eval_result.ValueOrDie());
CHECK(ShapeUtil::Equal(cond_result_pred.shape(),
ShapeUtil::MakeShape(PRED, {})));
// Per the explanation above, if the evaluated condition returns false, the
// loop executes at most once.
bool cond_returns_true = cond_result_pred.GetFirstElement<bool>();
if (!cond_returns_true) {
VLOG(2) << "Upper bound on the trip count is 1";
return 1;
}
VLOG(2) << "Loop has no known upper bound on the trip count.";
return nullopt;
}
} // namespace xla
| 38.97379 | 80 | 0.665098 | [
"shape"
] |
40f308ba5855a933a58a46aafa39f342aa08d15b | 49,712 | hpp | C++ | KFR/include/kfr/base/vec.hpp | Asifadam93/FiltreMusical | dcd53bc41934f219fb9b3d5aef281099fb572a49 | [
"BSD-3-Clause"
] | null | null | null | KFR/include/kfr/base/vec.hpp | Asifadam93/FiltreMusical | dcd53bc41934f219fb9b3d5aef281099fb572a49 | [
"BSD-3-Clause"
] | null | null | null | KFR/include/kfr/base/vec.hpp | Asifadam93/FiltreMusical | dcd53bc41934f219fb9b3d5aef281099fb572a49 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (C) 2016 D Levin (http://www.kfrlib.com)
* This file is part of KFR
*
* KFR 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.
*
* KFR 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 KFR.
*
* If GPL is not suitable for your project, you must purchase a commercial license to use KFR.
* Buying a commercial license is mandatory as soon as you develop commercial activities without
* disclosing the source code of your own applications.
* See http://www.kfrlib.com for details.
*/
#pragma once
#include "kfr.h"
#include "types.hpp"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
#pragma clang diagnostic ignored "-Wc++98-compat-local-type-template-args"
#pragma clang diagnostic ignored "-Wshadow"
#pragma clang diagnostic ignored "-Wpacked"
namespace kfr
{
template <typename T, size_t N>
struct vec;
template <typename T, size_t N>
struct mask;
using simdindex = int;
template <typename T, simdindex N>
using simd = T __attribute__((ext_vector_type(N)));
namespace internal
{
template <typename T>
struct is_vec_impl : std::false_type
{
};
template <typename T, size_t N>
struct is_vec_impl<vec<T, N>> : std::true_type
{
};
template <typename T, size_t N>
struct is_vec_impl<mask<T, N>> : std::true_type
{
};
template <typename T, bool A>
struct struct_with_alignment
{
T value;
KFR_INTRIN void operator=(T value) { this->value = value; }
};
template <typename T>
struct struct_with_alignment<T, false>
{
T value;
KFR_INTRIN void operator=(T value) { this->value = value; }
} __attribute__((__packed__, __may_alias__)); //
}
template <typename T>
using is_vec = internal::is_vec_impl<T>;
template <typename T, size_t N, bool A>
using vec_algn = internal::struct_with_alignment<simd<T, N>, A>;
template <typename T, size_t N, bool A>
struct vec_ptr
{
constexpr CMT_INLINE vec_ptr(T* data) noexcept : data(data) {}
constexpr CMT_INLINE vec_ptr(const T* data) noexcept : data(const_cast<T*>(data)) {}
CMT_INLINE const vec_algn<T, N, A>& operator[](size_t i) const
{
return *static_cast<vec_algn<T, N, A>*>(data + i);
}
CMT_INLINE vec_algn<T, N, A>& operator[](size_t i) { return *static_cast<vec_algn<T, N, A>*>(data + i); }
T* data;
};
template <typename To, typename From, size_t N,
KFR_ENABLE_IF(std::is_same<subtype<From>, subtype<To>>::value),
size_t Nout = N* compound_type_traits<From>::width / compound_type_traits<To>::width>
constexpr CMT_INLINE vec<To, Nout> compcast(const vec<From, N>& value) noexcept
{
return *value;
}
namespace internal
{
template <typename Fn, size_t index>
constexpr enable_if<std::is_same<size_t, decltype(std::declval<Fn>().operator()(size_t()))>::value, size_t>
get_vec_index()
{
constexpr Fn fn{};
return fn(index);
}
template <typename Fn, size_t index>
constexpr enable_if<
std::is_same<size_t, decltype(std::declval<Fn>().template operator() < index > ())>::value, size_t>
get_vec_index(int = 0)
{
constexpr Fn fn{};
return fn.template operator()<index>();
}
constexpr size_t index_undefined = static_cast<size_t>(-1);
template <typename T, size_t N, size_t... Indices, KFR_ENABLE_IF(!is_compound<T>::value)>
CMT_INLINE vec<T, sizeof...(Indices)> shufflevector(csizes_t<Indices...>, const vec<T, N>& x,
const vec<T, N>& y)
{
vec<T, sizeof...(Indices)> result = __builtin_shufflevector(
*x, *y, static_cast<intptr_t>(Indices == index_undefined ? -1 : static_cast<intptr_t>(Indices))...);
return result;
}
template <size_t... indices, size_t... counter, size_t groupsize = sizeof...(counter) / sizeof...(indices)>
constexpr auto inflate_impl(csizes_t<indices...> ind, csizes_t<counter...> cnt)
-> csizes_t<(ind.get(csize<counter / groupsize>) == index_undefined
? index_undefined
: (counter % groupsize + groupsize * ind.get(csize<counter / groupsize>)))...>
{
return {};
}
template <size_t groupsize, size_t... indices>
constexpr auto inflate(csize_t<groupsize>, csizes_t<indices...>)
{
return inflate_impl(csizes<indices...>, csizeseq<sizeof...(indices)*groupsize>);
}
template <typename T, size_t N, size_t... Indices, KFR_ENABLE_IF(is_compound<T>::value)>
CMT_INLINE vec<T, sizeof...(Indices)> shufflevector(csizes_t<Indices...> indices, const vec<T, N>& x,
const vec<T, N>& y)
{
return compcast<T>(shufflevector(inflate(csize<widthof<T>()>, indices), compcast<subtype<T>>(x),
compcast<subtype<T>>(y)));
}
template <size_t... Indices, size_t Nout = sizeof...(Indices), typename T, size_t N>
CMT_INLINE vec<T, Nout> shufflevector(csizes_t<Indices...>, const vec<T, N>& x)
{
return internal::shufflevector<T, N>(csizes<Indices...>, x, x);
}
template <typename Fn, size_t groupsize, typename T, size_t N, size_t... Indices,
size_t Nout = sizeof...(Indices)>
CMT_INLINE vec<T, Nout> shufflevector(const vec<T, N>& x, const vec<T, N>& y, cvals_t<size_t, Indices...>)
{
static_assert(N % groupsize == 0, "N % groupsize == 0");
return internal::shufflevector<T, N>(
csizes<(get_vec_index<Fn, Indices / groupsize>() * groupsize + Indices % groupsize)...>, x, y);
}
}
template <size_t Nout, typename Fn, size_t groupsize = 1, typename T, size_t N>
CMT_INLINE vec<T, Nout> shufflevector(const vec<T, N>& x, const vec<T, N>& y)
{
return internal::shufflevector<Fn, groupsize>(x, y, csizeseq<Nout>);
}
template <size_t Nout, typename Fn, size_t groupsize = 1, typename T, size_t N>
CMT_INLINE vec<T, Nout> shufflevector(const vec<T, N>& x)
{
return internal::shufflevector<Fn, groupsize>(x, x, csizeseq<Nout>);
}
namespace swizzle
{
template <size_t>
struct swiz
{
constexpr swiz() {}
};
constexpr swiz<0> x{};
constexpr swiz<1> y{};
constexpr swiz<2> z{};
constexpr swiz<3> w{};
constexpr swiz<0> r{};
constexpr swiz<1> g{};
constexpr swiz<2> b{};
constexpr swiz<3> a{};
constexpr swiz<0> s{};
constexpr swiz<1> t{};
constexpr swiz<2> p{};
constexpr swiz<3> q{};
constexpr swiz<0> s0{};
constexpr swiz<1> s1{};
constexpr swiz<2> s2{};
constexpr swiz<3> s3{};
constexpr swiz<4> s4{};
constexpr swiz<5> s5{};
constexpr swiz<6> s6{};
constexpr swiz<7> s7{};
constexpr swiz<8> s8{};
constexpr swiz<9> s9{};
constexpr swiz<10> s10{};
constexpr swiz<11> s11{};
constexpr swiz<12> s12{};
constexpr swiz<13> s13{};
constexpr swiz<14> s14{};
constexpr swiz<15> s15{};
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
template <size_t N, typename T>
constexpr CMT_INLINE vec<T, N> broadcast(T x)
{
return (simd<T, N>)(x);
}
#pragma clang diagnostic pop
namespace internal
{
template <typename To, typename From, size_t N, typename Tsub = deep_subtype<To>,
size_t Nout = N* compound_type_traits<To>::deep_width>
constexpr CMT_INLINE vec<To, N> builtin_convertvector(const vec<From, N>& value) noexcept
{
return __builtin_convertvector(*value, simd<Tsub, Nout>);
}
// scalar to scalar
template <typename To, typename From>
struct conversion
{
static_assert(std::is_convertible<From, To>::value, "");
static To cast(const From& value) { return value; }
};
// vector to vector
template <typename To, typename From, size_t N>
struct conversion<vec<To, N>, vec<From, N>>
{
static_assert(!is_compound<To>::value, "");
static_assert(!is_compound<From>::value, "");
static vec<To, N> cast(const vec<From, N>& value) { return builtin_convertvector<To>(value); }
};
// vector<vector> to vector<vector>
template <typename To, typename From, size_t N1, size_t N2>
struct conversion<vec<vec<To, N1>, N2>, vec<vec<From, N1>, N2>>
{
static_assert(!is_compound<To>::value, "");
static_assert(!is_compound<From>::value, "");
static vec<vec<To, N1>, N2> cast(const vec<vec<From, N1>, N2>& value)
{
return builtin_convertvector<vec<To, N1>>(value);
}
};
// scalar to vector
template <typename To, typename From, size_t N>
struct conversion<vec<To, N>, From>
{
static_assert(std::is_convertible<From, To>::value, "");
static vec<To, N> cast(const From& value) { return broadcast<N>(static_cast<To>(value)); }
};
// mask to mask
template <typename To, typename From, size_t N>
struct conversion<mask<To, N>, mask<From, N>>
{
static_assert(sizeof(To) == sizeof(From), "");
static mask<To, N> cast(const mask<From, N>& value) { return reinterpret_cast<simd<To, N>>(*value); }
};
}
template <typename T>
constexpr size_t size_of() noexcept
{
return sizeof(deep_subtype<T>) * compound_type_traits<T>::deep_width;
}
template <typename From, size_t N, typename Tsub = deep_subtype<From>,
size_t Nout = N* size_of<From>() / size_of<Tsub>()>
constexpr CMT_INLINE vec<Tsub, Nout> flatten(const vec<From, N>& value) noexcept
{
return *value;
}
template <typename To, typename From, typename Tout = deep_rebind<From, To>>
constexpr CMT_INLINE Tout cast(const From& value) noexcept
{
return static_cast<Tout>(value);
}
template <typename To, typename From>
constexpr CMT_INLINE To bitcast(const From& value) noexcept
{
static_assert(sizeof(From) == sizeof(To), "bitcast: Incompatible types");
union {
From from;
To to;
} u{ value };
return u.to;
}
template <typename To, typename From, size_t N, size_t Nout = N* size_of<From>() / size_of<To>()>
constexpr CMT_INLINE vec<To, Nout> bitcast(const vec<From, N>& value) noexcept
{
return reinterpret_cast<typename vec<To, Nout>::simd_t>(*value);
}
template <typename To, typename From, size_t N, size_t Nout = N* size_of<From>() / size_of<To>()>
constexpr CMT_INLINE mask<To, Nout> bitcast(const mask<From, N>& value) noexcept
{
return reinterpret_cast<typename mask<To, Nout>::simd_t>(*value);
}
template <typename From, typename To = utype<From>, KFR_ENABLE_IF(!is_compound<From>::value)>
constexpr CMT_INLINE To ubitcast(const From& value) noexcept
{
return bitcast<To>(value);
}
template <typename From, typename To = itype<From>, KFR_ENABLE_IF(!is_compound<From>::value)>
constexpr CMT_INLINE To ibitcast(const From& value) noexcept
{
return bitcast<To>(value);
}
template <typename From, typename To = ftype<From>, KFR_ENABLE_IF(!is_compound<From>::value)>
constexpr CMT_INLINE To fbitcast(const From& value) noexcept
{
return bitcast<To>(value);
}
template <typename From, size_t N, typename To = utype<From>,
size_t Nout = size_of<From>() * N / size_of<To>()>
constexpr CMT_INLINE vec<To, Nout> ubitcast(const vec<From, N>& value) noexcept
{
return reinterpret_cast<simd<To, Nout>>(*value);
}
template <typename From, size_t N, typename To = itype<From>,
size_t Nout = size_of<From>() * N / size_of<To>()>
constexpr CMT_INLINE vec<To, Nout> ibitcast(const vec<From, N>& value) noexcept
{
return reinterpret_cast<simd<To, Nout>>(*value);
}
template <typename From, size_t N, typename To = ftype<From>,
size_t Nout = size_of<From>() * N / size_of<To>()>
constexpr CMT_INLINE vec<To, Nout> fbitcast(const vec<From, N>& value) noexcept
{
return reinterpret_cast<simd<To, Nout>>(*value);
}
constexpr CMT_INLINE size_t vector_alignment(size_t size) { return next_poweroftwo(size); }
template <typename T, size_t N, size_t... Sizes>
CMT_INLINE vec<T, N + csum(csizes<Sizes...>)> concat(const vec<T, N>& x, const vec<T, Sizes>&... rest);
namespace internal
{
template <size_t start = 0, size_t stride = 1>
struct shuffle_index
{
constexpr CMT_INLINE size_t operator()(size_t index) const { return start + index * stride; }
};
template <size_t count, size_t start = 0, size_t stride = 1>
struct shuffle_index_wrap
{
constexpr inline size_t operator()(size_t index) const { return (start + index * stride) % count; }
};
}
template <size_t count, typename T, size_t N, size_t Nout = N* count>
CMT_INLINE vec<T, Nout> repeat(const vec<T, N>& x)
{
return shufflevector<Nout, internal::shuffle_index_wrap<N, 0, 1>>(x);
}
KFR_FN(repeat)
template <size_t Nout, typename T, size_t N, KFR_ENABLE_IF(Nout != N)>
CMT_INLINE vec<T, Nout> resize(const vec<T, N>& x)
{
return shufflevector<Nout, internal::shuffle_index_wrap<N, 0, 1>>(x);
}
template <size_t Nout, typename T, size_t N, KFR_ENABLE_IF(Nout == N)>
constexpr CMT_INLINE vec<T, Nout> resize(const vec<T, N>& x)
{
return x;
}
KFR_FN(resize)
namespace internal_read_write
{
template <size_t N, bool A = false, typename T, KFR_ENABLE_IF(is_poweroftwo(N))>
CMT_INLINE vec<T, N> read(const T* src)
{
return ptr_cast<vec_algn<subtype<T>, vec<T, N>::scalar_size(), A>>(src)->value;
}
template <size_t N, bool A = false, typename T, KFR_ENABLE_IF(!is_poweroftwo(N))>
CMT_INLINE vec<T, N> read(const T* src)
{
constexpr size_t first = prev_poweroftwo(N);
constexpr size_t rest = N - first;
return concat(internal_read_write::read<first, A>(src),
internal_read_write::read<rest, false>(src + first));
}
template <bool A = false, size_t N, typename T, KFR_ENABLE_IF(is_poweroftwo(N))>
CMT_INLINE void write(T* dest, const vec<T, N>& value)
{
ptr_cast<vec_algn<subtype<T>, vec<T, N>::scalar_size(), A>>(dest)->value = *value;
}
template <bool A = false, size_t N, typename T, KFR_ENABLE_IF(!is_poweroftwo(N))>
CMT_INLINE void write(T* dest, const vec<T, N>& value)
{
constexpr size_t first = prev_poweroftwo(N);
constexpr size_t rest = N - first;
internal_read_write::write<A, first>(dest, shufflevector<first, internal::shuffle_index<0>>(value));
internal_read_write::write<false, rest>(dest + first,
shufflevector<rest, internal::shuffle_index<first>>(value));
}
}
template <typename T, size_t N>
struct pkd_vec
{
constexpr pkd_vec() noexcept {}
pkd_vec(const vec<T, N>& value) noexcept { internal_read_write::write(v, value); }
template <typename... Ts>
constexpr pkd_vec(Ts... init) noexcept : v{ static_cast<T>(init)... }
{
static_assert(N <= sizeof...(Ts), "Too few initializers for pkd_vec");
}
private:
T v[N];
friend struct vec<T, N>;
} __attribute__((packed));
template <typename T>
struct vec_op
{
using scalar_type = subtype<T>;
using uscalar_type = utype<scalar_type>;
template <simdindex N>
constexpr static simd<scalar_type, N> add(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x + y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> sub(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x - y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> mul(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x * y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> div(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x / y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> rem(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x % y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> shl(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x << y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> shr(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return x >> y;
}
template <simdindex N>
constexpr static simd<scalar_type, N> neg(simd<scalar_type, N> x) noexcept
{
return -x;
}
template <simdindex N>
constexpr static simd<scalar_type, N> band(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(reinterpret_cast<simd<uscalar_type, N>>(x) &
reinterpret_cast<simd<uscalar_type, N>>(y));
}
template <simdindex N>
constexpr static simd<scalar_type, N> bor(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(reinterpret_cast<simd<uscalar_type, N>>(x) |
reinterpret_cast<simd<uscalar_type, N>>(y));
}
template <simdindex N>
constexpr static simd<scalar_type, N> bxor(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(reinterpret_cast<simd<uscalar_type, N>>(x) ^
reinterpret_cast<simd<uscalar_type, N>>(y));
}
template <simdindex N>
constexpr static simd<scalar_type, N> bnot(simd<scalar_type, N> x) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(~reinterpret_cast<simd<uscalar_type, N>>(x));
}
template <simdindex N>
constexpr static simd<scalar_type, N> eq(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x == y);
}
template <simdindex N>
constexpr static simd<scalar_type, N> ne(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x != y);
}
template <simdindex N>
constexpr static simd<scalar_type, N> lt(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x < y);
}
template <simdindex N>
constexpr static simd<scalar_type, N> gt(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x > y);
}
template <simdindex N>
constexpr static simd<scalar_type, N> le(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x <= y);
}
template <simdindex N>
constexpr static simd<scalar_type, N> ge(simd<scalar_type, N> x, simd<scalar_type, N> y) noexcept
{
return reinterpret_cast<simd<scalar_type, N>>(x >= y);
}
};
namespace internal
{
template <typename T, typename... Args, size_t... indices, size_t N = 1 + sizeof...(Args)>
constexpr CMT_INLINE vec<T, N> make_vector_impl(csizes_t<indices...>, const T& x, const Args&... rest)
{
constexpr size_t width = compound_type_traits<T>::width;
const T list[] = { x, rest... };
typename vec<T, N>::simd_t result{ compound_type_traits<T>::at(list[indices / width],
indices % width)... };
return result;
}
}
/// Create vector from scalar values
/// @code
/// CHECK( make_vector( 1, 2, 3, 4 ) == i32x4{1, 2, 3, 4} );
/// @encode
template <typename Type = void, typename Arg, typename... Args, size_t N = (sizeof...(Args) + 1),
typename SubType = conditional<is_void<Type>::value, common_type<Arg, Args...>, Type>>
constexpr CMT_INLINE vec<SubType, N> make_vector(const Arg& x, const Args&... rest)
{
return internal::make_vector_impl<SubType>(csizeseq<N * widthof<SubType>()>, static_cast<SubType>(x),
static_cast<SubType>(rest)...);
}
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> make_vector(const vec<T, N>& x)
{
return x;
}
template <typename T, T... Values, size_t N = sizeof...(Values)>
constexpr CMT_INLINE vec<T, N> make_vector(cvals_t<T, Values...>)
{
return make_vector<T>(Values...);
}
KFR_FN(make_vector)
template <typename Type = void, typename Arg, typename... Args, size_t N = (sizeof...(Args) + 1),
typename SubType = conditional<is_void<Type>::value, common_type<Arg, Args...>, Type>,
KFR_ENABLE_IF(is_numeric<SubType>::value)>
constexpr CMT_INLINE vec<SubType, N> pack(const Arg& x, const Args&... rest)
{
return internal::make_vector_impl<SubType>(csizeseq<N * widthof<SubType>()>, static_cast<SubType>(x),
static_cast<SubType>(rest)...);
}
KFR_FN(pack)
namespace operators
{
struct empty
{
};
}
template <typename T, size_t N>
struct vec : vec_t<T, N>, operators::empty
{
static_assert(N > 0 && N <= 256, "Invalid vector size");
static_assert(!is_vec<T>::value || is_poweroftwo(size_of<T>()),
"Inner vector size must be a power of two");
using UT = utype<T>;
using value_type = T;
using scalar_type = subtype<T>;
constexpr static size_t scalar_size() noexcept { return N * compound_type_traits<T>::width; }
using simd_t = simd<scalar_type, scalar_size()>;
using ref = vec&;
using cref = const vec&;
constexpr static bool is_pod = true;
constexpr CMT_INLINE vec() noexcept {}
constexpr CMT_INLINE vec(simd_t value) noexcept : v(value) {}
constexpr CMT_INLINE vec(const array_ref<T>& value) noexcept
: v(*internal_read_write::read<N, false>(value.data()))
{
}
constexpr CMT_INLINE vec(const array_ref<const T>& value) noexcept
: v(*internal_read_write::read<N, false>(value.data()))
{
}
template <typename U,
KFR_ENABLE_IF(std::is_convertible<U, T>::value&& compound_type_traits<T>::width > 1)>
constexpr CMT_INLINE vec(const U& value) noexcept
: v(*resize<scalar_size()>(bitcast<scalar_type>(make_vector(static_cast<T>(value)))))
{
}
template <typename U,
KFR_ENABLE_IF(std::is_convertible<U, T>::value&& compound_type_traits<T>::width == 1)>
constexpr CMT_INLINE vec(const U& value) noexcept : v(static_cast<T>(value))
{
}
template <typename... Ts>
constexpr CMT_INLINE vec(const T& x, const T& y, const Ts&... rest) noexcept
: v(*make_vector<T>(x, y, rest...))
{
static_assert(N <= 2 + sizeof...(Ts), "Too few initializers for vec");
}
template <size_t N1, size_t N2, size_t... Ns>
constexpr CMT_INLINE vec(const vec<T, N1>& v1, const vec<T, N2>& v2,
const vec<T, Ns>&... vectors) noexcept : v(*concat(v1, v2, vectors...))
{
static_assert(csum(csizes<N1, N2, Ns...>) == N, "Can't concat vectors: invalid csizes");
}
constexpr CMT_INLINE vec(const vec&) noexcept = default;
constexpr CMT_INLINE vec(vec&&) noexcept = default;
constexpr CMT_INLINE vec& operator=(const vec&) noexcept = default;
constexpr CMT_INLINE vec& operator=(vec&&) noexcept = default;
friend constexpr CMT_INLINE vec operator+(const vec& x, const vec& y) { return vec_op<T>::add(x.v, y.v); }
friend constexpr CMT_INLINE vec operator-(const vec& x, const vec& y) { return vec_op<T>::sub(x.v, y.v); }
friend constexpr CMT_INLINE vec operator*(const vec& x, const vec& y) { return vec_op<T>::mul(x.v, y.v); }
friend constexpr CMT_INLINE vec operator/(const vec& x, const vec& y) { return vec_op<T>::div(x.v, y.v); }
friend constexpr CMT_INLINE vec operator%(const vec& x, const vec& y) { return vec_op<T>::rem(x.v, y.v); }
friend constexpr CMT_INLINE vec operator-(const vec& x) { return vec_op<T>::neg(x.v); }
friend constexpr CMT_INLINE vec operator&(const vec& x, const vec& y)
{
return vec_op<T>::band(x.v, y.v);
}
friend constexpr CMT_INLINE vec operator|(const vec& x, const vec& y) { return vec_op<T>::bor(x.v, y.v); }
friend constexpr CMT_INLINE vec operator^(const vec& x, const vec& y)
{
return vec_op<T>::bxor(x.v, y.v);
}
friend constexpr CMT_INLINE vec operator~(const vec& x) { return vec_op<T>::bnot(x.v); }
friend constexpr CMT_INLINE vec operator<<(const vec& x, const vec& y)
{
return vec_op<T>::shl(x.v, y.v);
}
friend constexpr CMT_INLINE vec operator>>(const vec& x, const vec& y)
{
return vec_op<T>::shr(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator==(const vec& x, const vec& y)
{
return vec_op<T>::eq(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator!=(const vec& x, const vec& y)
{
return vec_op<T>::ne(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator<(const vec& x, const vec& y)
{
return vec_op<T>::lt(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator>(const vec& x, const vec& y)
{
return vec_op<T>::gt(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator<=(const vec& x, const vec& y)
{
return vec_op<T>::le(x.v, y.v);
}
friend constexpr CMT_INLINE mask<T, N> operator>=(const vec& x, const vec& y)
{
return vec_op<T>::ge(x.v, y.v);
}
#define KFR_ASGN_OP(aop, op) \
friend CMT_INLINE vec& operator aop(vec& x, const vec& y) \
{ \
x = x op y; \
return x; \
}
KFR_ASGN_OP(+=, +)
KFR_ASGN_OP(-=, -)
KFR_ASGN_OP(*=, *)
KFR_ASGN_OP(/=, /)
KFR_ASGN_OP(%=, %)
KFR_ASGN_OP(&=, &)
KFR_ASGN_OP(|=, |)
KFR_ASGN_OP(^=, ^)
KFR_ASGN_OP(<<=, <<)
KFR_ASGN_OP(>>=, >>)
#undef KFR_ASGN_OP
constexpr CMT_INLINE simd_t operator*() const { return v; }
constexpr CMT_INLINE simd_t& operator*() { return v; }
CMT_INLINE mask<T, N>& asmask() { return ref_cast<mask<T, N>>(*this); }
CMT_INLINE const mask<T, N>& asmask() const { return ref_cast<mask<T, N>>(*this); }
CMT_INLINE value_type operator[](size_t index) const { return data()[index]; }
CMT_INLINE value_type* data() { return ptr_cast<T>(&v); }
CMT_INLINE const T* data() const { return ptr_cast<T>(&v); }
using array_t = T (&)[N];
CMT_INLINE array_t arr() { return ref_cast<array_t>(v); }
template <typename U, KFR_ENABLE_IF(std::is_convertible<T, U>::value && !std::is_same<U, vec>::value)>
constexpr operator vec<U, N>() const noexcept
{
return internal::conversion<vec<U, N>, vec<T, N>>::cast(*this);
}
private:
struct getter_setter;
public:
getter_setter operator()(size_t index) { return { v, index }; }
scalar_type operator()(size_t index) const { return v[index]; }
protected:
template <typename U, size_t M>
friend struct vec;
template <typename U, size_t M>
friend struct mask;
simd_t v;
private:
struct getter_setter
{
constexpr getter_setter(simd_t& v, size_t index) noexcept : v(v), index(index) {}
CMT_INLINE getter_setter& operator=(scalar_type value) noexcept
{
v[index] = value;
return *this;
}
CMT_INLINE operator scalar_type() const { return v[index]; }
private:
friend struct vec;
simd_t& v;
const size_t index;
};
};
namespace operators
{
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator+(const vec<T1, N>& x, const T2& y)
{
return vec_op<C>::add(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator-(const vec<T1, N>& x, const T2& y)
{
return vec_op<C>::sub(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator*(const vec<T1, N>& x, const T2& y)
{
return vec_op<C>::mul(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator/(const vec<T1, N>& x, const T2& y)
{
return vec_op<C>::div(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator+(const T1& x, const vec<T2, N>& y)
{
return vec_op<C>::add(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator-(const T1& x, const vec<T2, N>& y)
{
return vec_op<C>::sub(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator*(const T1& x, const vec<T2, N>& y)
{
return vec_op<C>::mul(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator/(const T1& x, const vec<T2, N>& y)
{
return vec_op<C>::div(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator+(const vec<T1, N>& x, const vec<T2, N>& y)
{
return vec_op<C>::add(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator-(const vec<T1, N>& x, const vec<T2, N>& y)
{
return vec_op<C>::sub(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator*(const vec<T1, N>& x, const vec<T2, N>& y)
{
return vec_op<C>::mul(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
template <typename T1, typename T2, size_t N, typename C = common_type<T1, T2>>
constexpr CMT_INLINE vec<C, N> operator/(const vec<T1, N>& x, const vec<T2, N>& y)
{
return vec_op<C>::div(*static_cast<vec<C, N>>(x), *static_cast<vec<C, N>>(y));
}
}
template <typename T, size_t N>
struct mask : public vec<T, N>
{
using UT = utype<T>;
using type = T;
constexpr static size_t width = N;
using base = vec<T, N>;
constexpr CMT_INLINE mask() noexcept : base() {}
constexpr CMT_INLINE mask(simd<T, N> value) noexcept : base(value) {}
template <size_t N1, size_t... Ns>
constexpr CMT_INLINE mask(const mask<T, N1>& mask1, const mask<T, Ns>&... masks) noexcept
: base(*concat(mask1, masks...))
{
}
template <typename... Ts, typename = enable_if<sizeof...(Ts) + 2 == N>>
constexpr CMT_INLINE mask(bool x, bool y, Ts... rest) noexcept
: base{ internal::maskbits<T>(x), internal::maskbits<T>(y), internal::maskbits<T>(rest)... }
{
}
constexpr CMT_INLINE mask(const mask&) noexcept = default;
constexpr CMT_INLINE mask(mask&&) noexcept = default;
CMT_INLINE mask& operator=(const mask&) noexcept = default;
CMT_INLINE mask& operator=(mask&&) noexcept = default;
template <typename M, KFR_ENABLE_IF(sizeof(T) == sizeof(M))>
constexpr CMT_INLINE mask(const vec<M, N>& value) : base(bitcast<T>(value))
{
}
friend constexpr CMT_INLINE mask operator&(const mask& x, const mask& y)
{
return vec_op<T>::band(x.v, y.v);
}
friend constexpr CMT_INLINE mask operator|(const mask& x, const mask& y)
{
return vec_op<T>::bor(x.v, y.v);
}
friend constexpr CMT_INLINE mask operator^(const mask& x, const mask& y)
{
return vec_op<T>::bxor(x.v, y.v);
}
friend constexpr CMT_INLINE mask operator~(const mask& x) { return vec_op<T>::bnot(x.v); }
constexpr CMT_INLINE mask operator&&(const mask& x) const { return *this & x; }
constexpr CMT_INLINE mask operator||(const mask& x) const { return *this | x; }
constexpr CMT_INLINE mask operator!() const { return ~*this; }
constexpr CMT_INLINE simd<T, N> operator*() const { return this->v; }
CMT_INLINE vec<T, N>& asvec() { return ref_cast<mask>(*this); }
CMT_INLINE const vec<T, N>& asvec() const { return ref_cast<mask>(*this); }
template <typename U, KFR_ENABLE_IF(sizeof(T) == sizeof(U))>
CMT_INLINE operator mask<U, N>() const
{
return bitcast<U>(*this);
}
CMT_INLINE bool operator[](size_t index) const { return ibitcast(this->v[index]) < 0; }
};
template <typename T, size_t N1, size_t N2 = N1>
using mat = vec<vec<T, N1>, N2>;
namespace internal
{
template <size_t start, size_t count>
struct shuffle_index_extend
{
constexpr CMT_INLINE size_t operator()(size_t index) const
{
return index >= start && index < start + count ? index - start : index_undefined;
}
};
template <size_t start, size_t count, typename T, size_t N>
CMT_INLINE vec<T, count> concatexact(const vec<T, N>& x, const vec<T, N>& y)
{
return kfr::shufflevector<count, internal::shuffle_index<start>>(x, y);
}
template <size_t start, size_t count, typename T, size_t N1, size_t N2>
CMT_INLINE enable_if<(N1 == N2), vec<T, count>> concattwo(const vec<T, N1>& x, const vec<T, N2>& y)
{
return concatexact<start, count>(x, y);
}
template <size_t start, size_t count, typename T, size_t N1, size_t N2>
CMT_INLINE enable_if<(N1 > N2), vec<T, count>> concattwo(const vec<T, N1>& x, const vec<T, N2>& y)
{
return concatexact<start, count>(x, shufflevector<N1, internal::shuffle_index_extend<0, N2>>(y));
}
template <size_t start, size_t count, typename T, size_t N1, size_t N2>
CMT_INLINE enable_if<(N1 < N2), vec<T, count>> concattwo(const vec<T, N1>& x, const vec<T, N2>& y)
{
return concatexact<N2 - N1 + start, count>(
shufflevector<N2, internal::shuffle_index_extend<N2 - N1, N1>>(x), y);
}
template <typename T, size_t Nout, size_t N1, size_t... indices>
constexpr mask<T, Nout> partial_mask_helper(csizes_t<indices...>)
{
return make_vector(maskbits<T>(indices < N1)...);
}
template <typename T, size_t Nout, size_t N1>
constexpr mask<T, Nout> partial_mask()
{
return internal::partial_mask_helper<T, Nout, N1>(csizeseq<Nout>);
}
template <typename T, size_t N>
CMT_INLINE vec<T, N> concat(const vec<T, N>& x)
{
return x;
}
template <typename T, size_t N1, size_t N2>
CMT_INLINE vec<T, N1 + N2> concat(const vec<T, N1>& x, const vec<T, N2>& y)
{
return concattwo<0, N1 + N2>(x, y);
}
template <typename T, size_t N1, size_t N2, size_t... Sizes>
CMT_INLINE auto concat(const vec<T, N1>& x, const vec<T, N2>& y, const vec<T, Sizes>&... args)
{
return concat(x, concat(y, args...));
}
}
template <typename T, size_t N, size_t... Sizes>
CMT_INLINE vec<T, N + csum(csizes<Sizes...>)> concat(const vec<T, N>& x, const vec<T, Sizes>&... rest)
{
return internal::concat(x, rest...);
}
KFR_FN(concat)
using f32x1 = vec<f32, 1>;
using f32x2 = vec<f32, 2>;
using f32x3 = vec<f32, 3>;
using f32x4 = vec<f32, 4>;
using f32x8 = vec<f32, 8>;
using f32x16 = vec<f32, 16>;
using f32x32 = vec<f32, 32>;
using f64x1 = vec<f64, 1>;
using f64x2 = vec<f64, 2>;
using f64x3 = vec<f64, 3>;
using f64x4 = vec<f64, 4>;
using f64x8 = vec<f64, 8>;
using f64x16 = vec<f64, 16>;
using f64x32 = vec<f64, 32>;
using i8x1 = vec<i8, 1>;
using i8x2 = vec<i8, 2>;
using i8x3 = vec<i8, 3>;
using i8x4 = vec<i8, 4>;
using i8x8 = vec<i8, 8>;
using i8x16 = vec<i8, 16>;
using i8x32 = vec<i8, 32>;
using i16x1 = vec<i16, 1>;
using i16x2 = vec<i16, 2>;
using i16x3 = vec<i16, 3>;
using i16x4 = vec<i16, 4>;
using i16x8 = vec<i16, 8>;
using i16x16 = vec<i16, 16>;
using i16x32 = vec<i16, 32>;
using i32x1 = vec<i32, 1>;
using i32x2 = vec<i32, 2>;
using i32x3 = vec<i32, 3>;
using i32x4 = vec<i32, 4>;
using i32x8 = vec<i32, 8>;
using i32x16 = vec<i32, 16>;
using i32x32 = vec<i32, 32>;
using i64x1 = vec<i64, 1>;
using i64x2 = vec<i64, 2>;
using i64x3 = vec<i64, 3>;
using i64x4 = vec<i64, 4>;
using i64x8 = vec<i64, 8>;
using i64x16 = vec<i64, 16>;
using i64x32 = vec<i64, 32>;
using u8x1 = vec<u8, 1>;
using u8x2 = vec<u8, 2>;
using u8x3 = vec<u8, 3>;
using u8x4 = vec<u8, 4>;
using u8x8 = vec<u8, 8>;
using u8x16 = vec<u8, 16>;
using u8x32 = vec<u8, 32>;
using u16x1 = vec<u16, 1>;
using u16x2 = vec<u16, 2>;
using u16x3 = vec<u16, 3>;
using u16x4 = vec<u16, 4>;
using u16x8 = vec<u16, 8>;
using u16x16 = vec<u16, 16>;
using u16x32 = vec<u16, 32>;
using u32x1 = vec<u32, 1>;
using u32x2 = vec<u32, 2>;
using u32x3 = vec<u32, 3>;
using u32x4 = vec<u32, 4>;
using u32x8 = vec<u32, 8>;
using u32x16 = vec<u32, 16>;
using u32x32 = vec<u32, 32>;
using u64x1 = vec<u64, 1>;
using u64x2 = vec<u64, 2>;
using u64x3 = vec<u64, 3>;
using u64x4 = vec<u64, 4>;
using u64x8 = vec<u64, 8>;
using u64x16 = vec<u64, 16>;
using u64x32 = vec<u64, 32>;
using mf32x1 = mask<f32, 1>;
using mf32x2 = mask<f32, 2>;
using mf32x3 = mask<f32, 3>;
using mf32x4 = mask<f32, 4>;
using mf32x8 = mask<f32, 8>;
using mf32x16 = mask<f32, 16>;
using mf32x32 = mask<f32, 32>;
using mf64x1 = mask<f64, 1>;
using mf64x2 = mask<f64, 2>;
using mf64x3 = mask<f64, 3>;
using mf64x4 = mask<f64, 4>;
using mf64x8 = mask<f64, 8>;
using mf64x16 = mask<f64, 16>;
using mf64x32 = mask<f64, 32>;
using mi8x1 = mask<i8, 1>;
using mi8x2 = mask<i8, 2>;
using mi8x3 = mask<i8, 3>;
using mi8x4 = mask<i8, 4>;
using mi8x8 = mask<i8, 8>;
using mi8x16 = mask<i8, 16>;
using mi8x32 = mask<i8, 32>;
using mi16x1 = mask<i16, 1>;
using mi16x2 = mask<i16, 2>;
using mi16x3 = mask<i16, 3>;
using mi16x4 = mask<i16, 4>;
using mi16x8 = mask<i16, 8>;
using mi16x16 = mask<i16, 16>;
using mi16x32 = mask<i16, 32>;
using mi32x1 = mask<i32, 1>;
using mi32x2 = mask<i32, 2>;
using mi32x4 = mask<i32, 3>;
using mi32x3 = mask<i32, 4>;
using mi32x8 = mask<i32, 8>;
using mi32x16 = mask<i32, 16>;
using mi32x32 = mask<i32, 32>;
using mi64x1 = mask<i64, 1>;
using mi64x2 = mask<i64, 2>;
using mi64x3 = mask<i64, 3>;
using mi64x4 = mask<i64, 4>;
using mi64x8 = mask<i64, 8>;
using mi64x16 = mask<i64, 16>;
using mi64x32 = mask<i64, 32>;
using mu8x1 = mask<u8, 1>;
using mu8x2 = mask<u8, 2>;
using mu8x3 = mask<u8, 3>;
using mu8x4 = mask<u8, 4>;
using mu8x8 = mask<u8, 8>;
using mu8x16 = mask<u8, 16>;
using mu8x32 = mask<u8, 32>;
using mu16x1 = mask<u16, 1>;
using mu16x2 = mask<u16, 2>;
using mu16x3 = mask<u16, 3>;
using mu16x4 = mask<u16, 4>;
using mu16x8 = mask<u16, 8>;
using mu16x16 = mask<u16, 16>;
using mu16x32 = mask<u16, 32>;
using mu32x1 = mask<u32, 1>;
using mu32x2 = mask<u32, 2>;
using mu32x3 = mask<u32, 3>;
using mu32x4 = mask<u32, 4>;
using mu32x8 = mask<u32, 8>;
using mu32x16 = mask<u32, 16>;
using mu32x32 = mask<u32, 32>;
using mu64x1 = mask<u64, 1>;
using mu64x2 = mask<u64, 2>;
using mu64x3 = mask<u64, 3>;
using mu64x4 = mask<u64, 4>;
using mu64x8 = mask<u64, 8>;
using mu64x16 = mask<u64, 16>;
using mu64x32 = mask<u64, 32>;
using u8x2x2 = vec<vec<u8, 2>, 2>;
using i8x2x2 = vec<vec<i8, 2>, 2>;
using u16x2x2 = vec<vec<u16, 2>, 2>;
using i16x2x2 = vec<vec<i16, 2>, 2>;
using u32x2x2 = vec<vec<u32, 2>, 2>;
using i32x2x2 = vec<vec<i32, 2>, 2>;
using u64x2x2 = vec<vec<u64, 2>, 2>;
using i64x2x2 = vec<vec<i64, 2>, 2>;
using f32x2x2 = vec<vec<f32, 2>, 2>;
using f64x2x2 = vec<vec<f64, 2>, 2>;
using u8x4x4 = vec<vec<u8, 4>, 4>;
using i8x4x4 = vec<vec<i8, 4>, 4>;
using u16x4x4 = vec<vec<u16, 4>, 4>;
using i16x4x4 = vec<vec<i16, 4>, 4>;
using u32x4x4 = vec<vec<u32, 4>, 4>;
using i32x4x4 = vec<vec<i32, 4>, 4>;
using u64x4x4 = vec<vec<u64, 4>, 4>;
using i64x4x4 = vec<vec<i64, 4>, 4>;
using f32x4x4 = vec<vec<f32, 4>, 4>;
using f64x4x4 = vec<vec<f64, 4>, 4>;
namespace glsl_names
{
using vec2 = f32x2;
using vec3 = f32x3;
using vec4 = f32x4;
using dvec2 = f64x2;
using dvec3 = f64x3;
using dvec4 = f64x4;
using ivec2 = i32x2;
using ivec3 = i32x3;
using ivec4 = i32x4;
using uvec2 = u32x2;
using uvec3 = u32x3;
using uvec4 = u32x4;
}
namespace opencl_names
{
using char2 = i8x2;
using char3 = i8x3;
using char4 = i8x4;
using char8 = i8x8;
using char16 = i8x16;
using uchar2 = u8x2;
using uchar3 = u8x3;
using uchar4 = u8x4;
using uchar8 = u8x8;
using uchar16 = u8x16;
using short2 = i16x2;
using short3 = i16x3;
using short4 = i16x4;
using short8 = i16x8;
using short16 = i16x16;
using ushort2 = u16x2;
using ushort3 = u16x3;
using ushort4 = u16x4;
using ushort8 = u16x8;
using ushort16 = u16x16;
using int2 = i32x2;
using int3 = i32x3;
using int4 = i32x4;
using int8 = i32x8;
using int16 = i32x16;
using uint2 = u32x2;
using uint3 = u32x3;
using uint4 = u32x4;
using uint8 = u32x8;
using uint16 = u32x16;
using long2 = i64x2;
using long3 = i64x3;
using long4 = i64x4;
using long8 = i64x8;
using long16 = i64x16;
using ulong2 = u64x2;
using ulong3 = u64x3;
using ulong4 = u64x4;
using ulong8 = u64x8;
using ulong16 = u64x16;
using float2 = f32x2;
using float3 = f32x3;
using float4 = f32x4;
using float8 = f32x8;
using float16 = f32x16;
using double2 = f64x2;
using double3 = f64x3;
using double4 = f64x4;
using double8 = f64x8;
using double16 = f64x16;
}
namespace internal
{
template <typename T, size_t N>
struct vec_type
{
using type = vec<T, N>;
};
template <typename T, size_t Nmax>
struct maxvec
{
constexpr static size_t size = Nmax;
vec<T, size> vmax;
maxvec(T initial) : vmax(initial) {}
template <int N>
vec<T, N>& v()
{
static_assert(N <= size, "N <= size");
return reinterpret_cast<vec<T, N>&>(*this);
}
template <int N>
const vec<T, N>& v() const
{
static_assert(N <= size, "N <= size");
return reinterpret_cast<const vec<T, N>&>(*this);
}
};
template <size_t Index, typename T, size_t N, typename Fn, typename... Args,
typename Tout = result_of<Fn(subtype<decay<Args>>...)>>
constexpr CMT_INLINE Tout applyfn_helper(Fn&& fn, Args&&... args)
{
return fn(args[Index]...);
}
template <typename T, size_t N, typename Fn, typename... Args,
typename Tout = result_of<Fn(subtype<decay<Args>>...)>, size_t... Indices>
constexpr CMT_INLINE vec<Tout, N> apply_helper(Fn&& fn, csizes_t<Indices...>, Args&&... args)
{
return make_vector(applyfn_helper<Indices, T, N>(std::forward<Fn>(fn), std::forward<Args>(args)...)...);
}
template <typename T, size_t N, typename Fn, size_t... Indices>
constexpr CMT_INLINE vec<T, N> apply0_helper(Fn&& fn, csizes_t<Indices...>)
{
return make_vector(((void)Indices, void(), fn())...);
}
}
template <typename T, size_t N, typename Fn, typename... Args,
typename Tout = result_of<Fn(T, subtype<decay<Args>>...)>>
constexpr CMT_INLINE vec<Tout, N> apply(Fn&& fn, const vec<T, N>& arg, Args&&... args)
{
return internal::apply_helper<T, N>(std::forward<Fn>(fn), csizeseq<N>, arg, std::forward<Args>(args)...);
}
template <size_t N, typename Fn, typename T = result_of<Fn()>>
constexpr CMT_INLINE vec<T, N> apply(Fn&& fn)
{
return internal::apply0_helper<T, N>(std::forward<Fn>(fn), csizeseq<N>);
}
template <typename T, int N>
CMT_INLINE vec<T, N> tovec(const simd<T, N>& x)
{
return x;
}
template <typename T, size_t N>
CMT_INLINE vec<T, N> tovec(const mask<T, N>& x)
{
return *x;
}
#ifdef CMT_ARCH_SSE2
CMT_INLINE f32x4 tovec(__m128 x) { return f32x4(x); }
CMT_INLINE f64x2 tovec(__m128d x) { return f64x2(x); }
#endif
template <typename T, typename... Args, size_t Nout = (sizeof...(Args) + 1)>
constexpr CMT_INLINE mask<T, Nout> make_mask(bool arg, Args... args)
{
simd<T, Nout> temp{ internal::maskbits<T>(arg), internal::maskbits<T>(static_cast<bool>(args))... };
return temp;
}
KFR_FN(make_mask)
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> zerovector()
{
constexpr size_t width = N * compound_type_traits<T>::width;
return compcast<T>(vec<subtype<T>, width>(simd<subtype<T>, width>()));
}
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> zerovector(vec_t<T, N>)
{
return zerovector<T, N>();
}
KFR_FN(zerovector)
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> allonesvector()
{
return zerovector<T, N>() == zerovector<T, N>();
}
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> allonesvector(vec_t<T, N>)
{
return allonesvector<T, N>();
}
KFR_FN(allonesvector)
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> undefinedvector()
{
return vec<T, N>{};
}
template <typename T, size_t N>
constexpr CMT_INLINE vec<T, N> undefinedvector(vec_t<T, N>)
{
return undefinedvector<T, N>();
}
KFR_FN(undefinedvector)
template <typename T, size_t N, size_t Nout = prev_poweroftwo(N - 1)>
CMT_INLINE vec<T, Nout> low(const vec<T, N>& x)
{
return shufflevector<Nout, internal::shuffle_index<>>(x);
}
template <typename T, size_t N, size_t Nout = prev_poweroftwo(N - 1)>
CMT_INLINE vec_t<T, Nout> low(vec_t<T, N>)
{
return {};
}
template <typename T, size_t N, size_t Nout = N - prev_poweroftwo(N - 1)>
CMT_INLINE vec<T, Nout> high(const vec<T, N>& x)
{
return shufflevector<Nout, internal::shuffle_index<prev_poweroftwo(N - 1)>>(x);
}
template <typename T, size_t N, size_t Nout = N - prev_poweroftwo(N - 1)>
CMT_INLINE vec_t<T, Nout> high(vec_t<T, N>)
{
return {};
}
KFR_FN(low)
KFR_FN(high)
namespace internal
{
template <typename Fn>
struct expression_lambda : input_expression
{
CMT_INLINE expression_lambda(Fn&& fn) : fn(std::move(fn)) {}
template <typename T, size_t N, KFR_ENABLE_IF(N&& is_callable<Fn, cinput_t, size_t, vec_t<T, N>>::value)>
CMT_INLINE vec<T, N> operator()(cinput_t, size_t index, vec_t<T, N> y) const
{
return fn(cinput, index, y);
}
template <typename T, size_t N, KFR_ENABLE_IF(N&& is_callable<Fn, size_t>::value)>
CMT_INLINE vec<T, N> operator()(cinput_t, size_t index, vec_t<T, N>) const
{
vec<T, N> result;
for (size_t i = 0; i < N; i++)
{
result(i) = fn(index + i);
}
return result;
}
template <typename T, size_t N, KFR_ENABLE_IF(N&& is_callable<Fn>::value)>
CMT_INLINE vec<T, N> operator()(cinput_t, size_t, vec_t<T, N>) const
{
vec<T, N> result;
for (size_t i = 0; i < N; i++)
{
result(i) = fn();
}
return result;
}
Fn fn;
};
}
template <typename Fn>
internal::expression_lambda<decay<Fn>> lambda(Fn&& fn)
{
return internal::expression_lambda<Fn>(std::move(fn));
}
}
#pragma clang diagnostic pop
namespace cometa
{
template <typename T, size_t N>
struct compound_type_traits<kfr::simd<T, N>>
{
using subtype = T;
using deep_subtype = cometa::deep_subtype<T>;
constexpr static size_t width = N;
constexpr static size_t deep_width = width * compound_type_traits<T>::width;
constexpr static bool is_scalar = false;
constexpr static size_t depth = cometa::compound_type_traits<T>::depth + 1;
template <typename U>
using rebind = kfr::simd<U, N>;
template <typename U>
using deep_rebind = kfr::simd<cometa::deep_rebind<subtype, U>, N>;
static constexpr const subtype& at(const kfr::simd<T, N>& value, size_t index) { return value[index]; }
};
template <typename T, size_t N>
struct compound_type_traits<kfr::vec<T, N>>
{
using subtype = T;
using deep_subtype = cometa::deep_subtype<T>;
constexpr static size_t width = N;
constexpr static size_t deep_width = width * compound_type_traits<T>::width;
constexpr static bool is_scalar = false;
constexpr static size_t depth = cometa::compound_type_traits<T>::depth + 1;
template <typename U>
using rebind = kfr::vec<U, N>;
template <typename U>
using deep_rebind = kfr::vec<cometa::deep_rebind<subtype, U>, N>;
static constexpr subtype at(const kfr::vec<T, N>& value, size_t index) { return value[index]; }
};
template <typename T, size_t N>
struct compound_type_traits<kfr::mask<T, N>>
{
using subtype = T;
using deep_subtype = cometa::deep_subtype<T>;
constexpr static size_t width = N;
constexpr static size_t deep_width = width * compound_type_traits<T>::width;
constexpr static bool is_scalar = false;
constexpr static size_t depth = cometa::compound_type_traits<T>::depth + 1;
template <typename U>
using rebind = kfr::mask<U, N>;
template <typename U>
using deep_rebind = kfr::mask<cometa::deep_rebind<subtype, U>, N>;
static constexpr subtype at(const kfr::mask<T, N>& value, size_t index) { return value[index]; }
};
}
namespace std
{
template <typename T1, typename T2, size_t N>
struct common_type<kfr::vec<T1, N>, kfr::vec<T2, N>>
{
using type = kfr::vec<typename common_type<T1, T2>::type, N>;
};
template <typename T1, typename T2, size_t N>
struct common_type<kfr::vec<T1, N>, T2>
{
using type = kfr::vec<typename common_type<T1, T2>::type, N>;
};
template <typename T1, typename T2, size_t N>
struct common_type<T1, kfr::vec<T2, N>>
{
using type = kfr::vec<typename common_type<T1, T2>::type, N>;
};
template <typename T1, typename T2, size_t N>
struct common_type<kfr::mask<T1, N>, kfr::mask<T2, N>>
{
using type = kfr::mask<typename common_type<T1, T2>::type, N>;
};
}
| 32.813201 | 110 | 0.646041 | [
"vector"
] |
40f37cd0d71e0461d88c92b70620267ac76c4706 | 24,822 | cpp | C++ | src/parser.cpp | rikushoney/aavm | 42e088078915b1973fae20ceb055680da5fbef6b | [
"MIT"
] | 1 | 2020-10-26T02:07:05.000Z | 2020-10-26T02:07:05.000Z | src/parser.cpp | rikushoney/aavm | 42e088078915b1973fae20ceb055680da5fbef6b | [
"MIT"
] | null | null | null | src/parser.cpp | rikushoney/aavm | 42e088078915b1973fae20ceb055680da5fbef6b | [
"MIT"
] | null | null | null | #include "parser.h"
#include "compiler.h"
#include "instructions.h"
#include "operand2.h"
#include "register.h"
#include "token.h"
#include <memory>
using namespace aavm;
using namespace aavm::parser;
using namespace aavm::ir;
using namespace std::string_view_literals;
static constexpr auto map_token(token::Kind token) -> unsigned {
using namespace aavm::token;
switch (token) {
case kw_eq:
return Condition::EQ;
case kw_ne:
return Condition::NE;
case kw_cs:
case kw_hs:
return Condition::CS;
case kw_cc:
case kw_lo:
return Condition::CC;
case kw_mi:
return Condition::MI;
case kw_pl:
return Condition::PL;
case kw_vs:
return Condition::VS;
case kw_vc:
return Condition::VC;
case kw_hi:
return Condition::HI;
case kw_ls:
return Condition::LS;
case kw_ge:
return Condition::GE;
case kw_lt:
return Condition::LT;
case kw_gt:
return Condition::GT;
case kw_le:
return Condition::LE;
case kw_al:
return Condition::AL;
case kw_r0:
return Register::R0;
case kw_r1:
return Register::R1;
case kw_r2:
return Register::R2;
case kw_r3:
return Register::R3;
case kw_r4:
return Register::R4;
case kw_r5:
return Register::R5;
case kw_r6:
return Register::R6;
case kw_r7:
return Register::R7;
case kw_r8:
return Register::R8;
case kw_r9:
return Register::R9;
case kw_r10:
return Register::R10;
case kw_r11:
return Register::R11;
case kw_r12:
return Register::R12;
case kw_r13:
case kw_sp:
return Register::SP;
case kw_r14:
case kw_lr:
return Register::LR;
case kw_r15:
case kw_pc:
return Register::PC;
case kw_add:
return Instruction::Add;
case kw_adc:
return Instruction::Adc;
case kw_sub:
return Instruction::Sub;
case kw_sbc:
return Instruction::Sbc;
case kw_rsb:
return Instruction::Rsb;
case kw_rsc:
return Instruction::Rsc;
case kw_and:
return Instruction::And;
case kw_eor:
return Instruction::Eor;
case kw_orr:
return Instruction::Orr;
case kw_bic:
return Instruction::Bic;
case kw_adr:
return Instruction::Adr;
case kw_asr:
return Instruction::Asr;
case kw_lsl:
return Instruction::Lsl;
case kw_lsr:
return Instruction::Lsr;
case kw_ror:
return Instruction::Ror;
case kw_rrx:
return Instruction::Rrx;
case kw_mul:
return Instruction::Mul;
case kw_mla:
return Instruction::Mla;
case kw_mls:
return Instruction::Mls;
case kw_umull:
return Instruction::Umull;
case kw_umlal:
return Instruction::Umlal;
case kw_smull:
return Instruction::Smull;
case kw_smlal:
return Instruction::Smlal;
case kw_sdiv:
return Instruction::Sdiv;
case kw_udiv:
return Instruction::Udiv;
case kw_mov:
return Instruction::Mov;
case kw_mvn:
return Instruction::Mvn;
case kw_movt:
return Instruction::Movt;
case kw_movw:
return Instruction::Movw;
case kw_cmp:
return Instruction::Cmp;
case kw_cmn:
return Instruction::Cmn;
case kw_tst:
return Instruction::Tst;
case kw_teq:
return Instruction::Teq;
case kw_bfc:
return Instruction::Bfc;
case kw_bfi:
return Instruction::Bfi;
case kw_sbfx:
return Instruction::Sbfx;
case kw_ubfx:
return Instruction::Ubfx;
case kw_rbit:
return Instruction::Rbit;
case kw_rev:
return Instruction::Rev;
case kw_rev16:
return Instruction::Rev16;
case kw_revsh:
return Instruction::Revsh;
case kw_b:
return Instruction::B;
case kw_bl:
return Instruction::Bl;
case kw_bx:
return Instruction::Bx;
case kw_cbz:
return Instruction::Cbz;
case kw_cbnz:
return Instruction::Cbnz;
case kw_ldr:
return Instruction::Ldr;
case kw_ldrb:
return Instruction::Ldrb;
case kw_ldrsb:
return Instruction::Ldrsb;
case kw_ldrh:
return Instruction::Ldrh;
case kw_ldrsh:
return Instruction::Ldrsh;
case kw_str:
return Instruction::Str;
case kw_strb:
return Instruction::Strb;
case kw_strh:
return Instruction::Strh;
case kw_ldm:
return Instruction::Ldm;
case kw_ldmia:
return Instruction::Ldmia;
case kw_ldmib:
return Instruction::Ldmib;
case kw_ldmda:
return Instruction::Ldmda;
case kw_ldmdb:
return Instruction::Ldmdb;
case kw_stm:
return Instruction::Stm;
case kw_stmia:
return Instruction::Stmia;
case kw_stmib:
return Instruction::Stmib;
case kw_stmda:
return Instruction::Stmda;
case kw_stmdb:
return Instruction::Stmdb;
case kw_push:
return Instruction::Push;
case kw_pop:
return Instruction::Pop;
default:
return 0;
}
aavm_unreachable();
}
std::unique_ptr<Instruction> Parser::parse_instruction() {
const auto tok = lexer_.token_kind();
if (!token::is_instruction(tok)) {
return {};
}
if (tok != token::kw_nop) {
const auto op = map_token(tok);
if (op > 0) {
if (Instruction::is_arithmetic_operation(op)) {
return parse_arithmetic(
static_cast<Instruction::ArithmeticOperation>(op),
lexer_.source_location());
} else if (Instruction::is_shift_operation(op)) {
return parse_shift(static_cast<Instruction::ShiftOperation>(op),
lexer_.source_location());
} else if (Instruction::is_multiply_operation(op)) {
return parse_multiply(static_cast<Instruction::MultiplyOperation>(op),
lexer_.source_location());
} else if (Instruction::is_divide_operation(op)) {
return parse_divide(static_cast<Instruction::DivideOperation>(op),
lexer_.source_location());
} else if (Instruction::is_move_operation(op)) {
return parse_move(static_cast<Instruction::MoveOperation>(op),
lexer_.source_location());
} else if (Instruction::is_comparison_operation(op)) {
return parse_comparison(
static_cast<Instruction::ComparisonOperation>(op),
lexer_.source_location());
} else if (Instruction::is_bitfield_operation(op)) {
return parse_bitfield(static_cast<Instruction::BitfieldOperation>(op),
lexer_.source_location());
} else if (Instruction::is_reverse_operation(op)) {
return parse_reverse(static_cast<Instruction::ReverseOperation>(op),
lexer_.source_location());
} else if (Instruction::is_branch_operation(op)) {
return parse_branch(static_cast<Instruction::BranchOperation>(op),
lexer_.source_location());
} else if (Instruction::is_single_memory_operation(op)) {
return parse_single_memory(
static_cast<Instruction::SingleMemoryOperation>(op),
lexer_.source_location());
} else if (Instruction::is_block_memory_operation(op)) {
return parse_block_memory(
static_cast<Instruction::BlockMemoryOperation>(op),
lexer_.source_location());
} else {
return {};
}
}
}
// return mov r0, r0
return std::make_unique<MoveInstruction>(
Instruction::Mov, Condition::AL, false, Register::Kind::R0,
Operand2{ShiftedRegister{Register::Kind::R0, Instruction::Lsl, 0u}});
}
const Label *Parser::find_label_or_insert(std::string_view name) {
for (const auto &l : labels_) {
if (name == l.name()) {
return &l;
}
}
return &labels_.emplace_back(
Label{static_cast<LabelID>(labels_.size() + 1), name});
}
bool Parser::parse_update_flag(const SourceLocation & /*srcloc*/) {
const auto update = lexer_.token_kind() == token::UpdateFlag;
if (update) {
lexer_.get_token();
}
return update;
}
Condition::Kind Parser::parse_condition(const SourceLocation & /*srcloc*/) {
if (is_condition(lexer_.token_kind())) {
const auto cond = map_token(lexer_.token_kind());
lexer_.get_token();
return static_cast<Condition::Kind>(cond);
}
return Condition::AL;
}
std::optional<unsigned>
Parser::parse_immediate(bool numbersym, const SourceLocation & /*srcloc*/) {
if (numbersym && !ensure(token::Numbersym, "expected '#'"sv)) {
return std::nullopt;
}
const auto negate = lexer_.token_kind() == token::Minus;
if (negate) {
lexer_.get_token();
}
const auto imm = lexer_.int_value();
if (!ensure(token::Integer, "expected integer"sv)) {
return std::nullopt;
}
// we want to compute the two's compliment of the number but keep the value
// unsigned since it's up to interpretation at an assembly level anyway
#if AAVM_MSVC
#pragma warning(push)
#pragma warning(disable : 4146)
#endif
return negate ? static_cast<unsigned>(-imm) : imm;
#if AAVM_MSVC
#pragma warning(pop)
#endif
}
std::optional<Register::Kind>
Parser::parse_register(const SourceLocation & /*srcloc*/) {
const auto reg = map_token(lexer_.token_kind());
if (!ensure(token::is_register, "expected register"sv)) {
return std::nullopt;
}
return static_cast<Register::Kind>(reg);
}
std::optional<Operand2>
Parser::parse_operand2(const SourceLocation & /*srcloc*/) {
if (lexer_.token_kind() == token::Numbersym) {
const auto imm =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return imm ? std::optional{Operand2{*imm}} : std::nullopt;
}
const auto rm = parse_register(lexer_.source_location());
if (!rm) {
return std::nullopt;
}
if (lexer_.token_kind() != token::Comma) {
return Operand2{ShiftedRegister{*rm, Instruction::Lsl, 0}};
}
if (!expect(token::is_instruction, "expected shift operation"sv)) {
return std::nullopt;
}
const auto sh = map_token(lexer_.token_kind());
if (!Instruction::is_shift_operation(sh)) {
return std::nullopt;
}
lexer_.get_token();
if (lexer_.token_kind() == token::Numbersym) {
const auto shamt5 =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return shamt5 ? std::optional{Operand2{ShiftedRegister{
*rm, static_cast<Instruction::ShiftOperation>(sh),
*shamt5}}}
: std::nullopt;
} else {
const auto rs = parse_register(lexer_.source_location());
return rs ? std::optional{Operand2{ShiftedRegister{
*rm, static_cast<Instruction::ShiftOperation>(sh), *rs}}}
: std::nullopt;
}
}
std::optional<const Label *>
Parser::parse_label(const SourceLocation & /*srcloc*/) {
const auto label = lexer_.string_value();
if (!ensure(token::Label, "expected label"sv)) {
return std::nullopt;
}
return find_label_or_insert(label);
}
std::unique_ptr<ArithmeticInstruction>
Parser::parse_arithmetic(Instruction::ArithmeticOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto updates = parse_update_flag(lexer_.source_location());
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
// special case for ADR
if (op == Instruction::Adr) {
const auto label = parse_label(lexer_.source_location());
return label
? std::make_unique<ArithmeticInstruction>(op, cond, *rd, *label)
: nullptr;
}
const auto rn = parse_register(lexer_.source_location());
if (!rn) {
return nullptr;
}
if (!ensure_comma()) {
return nullptr;
}
const auto src2 = parse_operand2(lexer_.source_location());
return src2 ? std::make_unique<ArithmeticInstruction>(op, cond, updates, *rd,
*rn, *src2)
: nullptr;
}
std::unique_ptr<MoveInstruction>
Parser::parse_shift(Instruction::ShiftOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto updates = parse_update_flag(lexer_.source_location());
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
const auto rm = parse_register(lexer_.source_location());
if (!rm) {
return nullptr;
}
if (op == Instruction::Rrx) {
return std::make_unique<MoveInstruction>(
Instruction::Mov, cond, updates, *rd,
Operand2{ShiftedRegister{*rm, op, 0}});
}
if (!ensure_comma()) {
return nullptr;
}
if (lexer_.token_kind() == token::Numbersym) {
const auto shamt5 =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return shamt5 ? std::make_unique<MoveInstruction>(
Instruction::Mov, cond, updates, *rd,
Operand2{ShiftedRegister{*rm, op, *shamt5}})
: nullptr;
}
const auto rs = parse_register(lexer_.source_location());
return rs ? std::make_unique<MoveInstruction>(
Instruction::Mov, cond, updates, *rd,
Operand2{ShiftedRegister{*rm, op, *rs}})
: nullptr;
}
std::unique_ptr<MultiplyInstruction>
Parser::parse_multiply(Instruction::MultiplyOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto updates = parse_update_flag(lexer_.source_location());
const auto cond = parse_condition(lexer_.source_location());
switch (op) {
case Instruction::Mul:
case Instruction::Mla:
case Instruction::Mls: {
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
break;
}
const auto rm = parse_register(lexer_.source_location());
if (!rm || !ensure_comma()) {
break;
}
const auto rs = parse_register(lexer_.source_location());
if (op == Instruction::Mul) {
return rs ? std::make_unique<MultiplyInstruction>(op, cond, updates, *rd,
*rm, *rs)
: nullptr;
}
if (!rs || !ensure_comma()) {
break;
}
const auto rn = parse_register(lexer_.source_location());
return rn ? std::make_unique<MultiplyInstruction>(op, cond, updates, *rs,
*rm, *rs, *rn)
: nullptr;
}
case Instruction::Umull:
case Instruction::Smull:
case Instruction::Umlal:
case Instruction::Smlal: {
const auto rdlo = parse_register(lexer_.source_location());
if (!rdlo || !ensure_comma()) {
break;
}
const auto rdhi = parse_register(lexer_.source_location());
if (!rdhi || !ensure_comma()) {
break;
}
const auto rm = parse_register(lexer_.source_location());
if (!rm || !ensure_comma()) {
break;
}
const auto rs = parse_register(lexer_.source_location());
return rs ? std::make_unique<MultiplyInstruction>(
op, cond, updates, std::pair{*rdlo, *rdhi}, *rm, *rs)
: nullptr;
}
default:
break;
}
return nullptr;
}
std::unique_ptr<DivideInstruction>
Parser::parse_divide(Instruction::DivideOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
const auto rn = parse_register(lexer_.source_location());
if (!rn || !ensure_comma()) {
return nullptr;
}
const auto rm = parse_register(lexer_.source_location());
return rm ? std::make_unique<DivideInstruction>(op, cond, *rd, *rn, *rm)
: nullptr;
}
std::unique_ptr<MoveInstruction>
Parser::parse_move(Instruction::MoveOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
switch (op) {
case Instruction::Mov:
case Instruction::Mvn: {
const auto updates = parse_update_flag(lexer_.source_location());
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
break;
}
const auto src2 = parse_operand2(lexer_.source_location());
return src2 ? std::make_unique<MoveInstruction>(op, cond, updates, *rd,
*src2)
: nullptr;
}
case Instruction::Movt:
case Instruction::Movw: {
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
break;
}
const auto imm16 =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return imm16 ? std::make_unique<MoveInstruction>(op, cond, *rd, *imm16)
: nullptr;
}
default:
break;
}
return nullptr;
}
std::unique_ptr<ComparisonInstruction>
Parser::parse_comparison(Instruction::ComparisonOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
const auto rn = parse_register(lexer_.source_location());
if (!rn || !ensure_comma()) {
return nullptr;
}
const auto src2 = parse_operand2(lexer_.source_location());
return src2 ? std::make_unique<ComparisonInstruction>(op, cond, *rn, *src2)
: nullptr;
}
std::unique_ptr<BitfieldInstruction>
Parser::parse_bitfield(Instruction::BitfieldOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
if (op == Instruction::Bfc) {
const auto lsb =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
if (!lsb || !ensure_comma()) {
return nullptr;
}
const auto width =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return width ? std::make_unique<BitfieldInstruction>(op, cond, *rd, *lsb,
*width)
: nullptr;
}
const auto rn = parse_register(lexer_.source_location());
if (!rn || !ensure_comma()) {
return nullptr;
}
const auto lsb =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
if (!lsb || !ensure_comma()) {
return nullptr;
}
const auto width =
parse_immediate(/*numbersym*/ true, lexer_.source_location());
return width ? std::make_unique<BitfieldInstruction>(op, cond, *rd, *rn, *lsb,
*width)
: nullptr;
}
std::unique_ptr<ReverseInstruction>
Parser::parse_reverse(Instruction::ReverseOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
const auto rm = parse_register(lexer_.source_location());
return rm ? std::make_unique<ReverseInstruction>(op, cond, *rd, *rm)
: nullptr;
}
std::unique_ptr<BranchInstruction>
Parser::parse_branch(Instruction::BranchOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
switch (op) {
case Instruction::B:
case Instruction::Bl: {
const auto label = parse_label(lexer_.source_location());
return label ? std::make_unique<BranchInstruction>(op, cond, *label)
: nullptr;
}
case Instruction::Bx: {
const auto rm = parse_register(lexer_.source_location());
return rm ? std::make_unique<BranchInstruction>(op, cond, *rm) : nullptr;
}
case Instruction::Cbz:
case Instruction::Cbnz: {
const auto rn = parse_register(lexer_.source_location());
if (!rn || !ensure_comma()) {
break;
}
const auto label = parse_label(lexer_.source_location());
return label ? std::make_unique<BranchInstruction>(op, cond, *label)
: nullptr;
}
default:
break;
}
return nullptr;
}
std::unique_ptr<SingleMemoryInstruction>
Parser::parse_single_memory(Instruction::SingleMemoryOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
const auto rd = parse_register(lexer_.source_location());
if (!rd || !ensure_comma()) {
return nullptr;
}
if (lexer_.token_kind() == token::Equal) {
lexer_.get_token();
const auto imm32 =
parse_immediate(/* numbersym */ false, lexer_.source_location());
return imm32 ? std::make_unique<SingleMemoryInstruction>(op, cond, *rd,
*imm32)
: nullptr;
} else if (lexer_.token_kind() == token::Label) {
const auto label = parse_label(lexer_.source_location());
return label ? std::make_unique<SingleMemoryInstruction>(op, cond, *rd,
*label)
: nullptr;
}
if (!ensure(token::Lbracket, "expected opening bracket"sv)) {
return nullptr;
}
const auto rn = parse_register(lexer_.source_location());
if (!rn) {
return nullptr;
}
if (lexer_.token_kind() == token::Rbracket) {
lexer_.get_token();
if (lexer_.token_kind() != token::Comma) {
return std::make_unique<SingleMemoryInstruction>(
op, cond, *rd, *rn, Operand2{0u},
SingleMemoryInstruction::IndexMode::PostIndex, false);
}
lexer_.get_token();
const auto subtract = lexer_.token_kind() == token::Minus;
if (subtract) {
lexer_.get_token();
}
const auto src2 = parse_operand2(lexer_.source_location());
return src2 ? std::make_unique<SingleMemoryInstruction>(
op, cond, *rd, *rn, *src2,
SingleMemoryInstruction::IndexMode::PostIndex, subtract)
: nullptr;
}
if (!ensure_comma()) {
return nullptr;
}
const auto subtract = lexer_.token_kind() == token::Minus;
if (subtract) {
lexer_.get_token();
}
const auto src2 = parse_operand2(lexer_.source_location());
if (!src2 || !ensure(token::Rbracket, "expected closing bracket"sv)) {
return nullptr;
}
const auto indexmode = lexer_.token_kind() == token::Exclaim
? SingleMemoryInstruction::IndexMode::PreIndex
: SingleMemoryInstruction::IndexMode::Offset;
return std::make_unique<SingleMemoryInstruction>(op, cond, *rd, *rn, *src2,
indexmode, subtract);
}
std::unique_ptr<BlockMemoryInstruction>
Parser::parse_block_memory(Instruction::BlockMemoryOperation op,
const SourceLocation & /*srcloc*/) {
lexer_.get_token();
const auto cond = parse_condition(lexer_.source_location());
auto rn = std::optional<Register::Kind>{};
auto writeback = false;
switch (op) {
case Instruction::Ldm:
case Instruction::Ldmia:
case Instruction::Ldmib:
case Instruction::Ldmda:
case Instruction::Ldmdb:
case Instruction::Stm:
case Instruction::Stmia:
case Instruction::Stmib:
case Instruction::Stmda:
case Instruction::Stmdb:
rn = parse_register(lexer_.source_location());
if (!rn) {
return nullptr;
}
writeback = lexer_.token_kind() == token::Exclaim;
if (writeback) {
lexer_.get_token();
}
if (!ensure_comma()) {
return nullptr;
}
break;
case Instruction::Push:
case Instruction::Pop:
rn = Register::SP;
writeback = true;
break;
}
if (!ensure(token::Lbrace, "expected opening brace"sv)) {
return nullptr;
}
auto registers = std::vector<Register::Kind>{};
while (lexer_.token_kind() != token::Rbrace) {
const auto reg = parse_register(lexer_.source_location());
if (!reg) {
return nullptr;
}
if (lexer_.token_kind() == token::Minus) {
lexer_.get_token();
const auto reg2 = parse_register(lexer_.source_location());
if (!reg2) {
return nullptr;
}
const auto last = static_cast<unsigned>(*reg2);
for (auto i = static_cast<unsigned>(*reg); i <= last; ++i) {
registers.push_back(static_cast<Register::Kind>(i));
}
} else {
registers.push_back(*reg);
}
if (lexer_.token_kind() != token::Rbrace && !ensure_comma()) {
return nullptr;
}
}
return std::make_unique<BlockMemoryInstruction>(op, cond, *rn, writeback,
registers);
}
| 29.133803 | 80 | 0.635444 | [
"vector"
] |
40f3d9e8746d56963a49e881a88b4505d83a40b2 | 9,741 | cpp | C++ | lab_08/lab8.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | lab_08/lab8.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | lab_08/lab8.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | /*--- lab8.cpp -------------------------------------------------------
A study of STL's vector container
Lab #8
Add your name(s) here and other info requested by your instructor.
--------------------------------------------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
ostream & operator<<(ostream & out, const vector<T> & v)
/*-------------------------------------------------------------------------
Overloaded output operator for vector<T>s.
Precondition: ostream out is open.
Postcondition: Elements of v have been output to out and out is returned.
--------------------------------------------------------------------------*/
{
for (int i = 0; i < v.size(); i++)
out << v.operator[](i) << " ";
return out;
}
int main()
{
// Declare 6 vectors v1, v2, v3, v4, v5, v6 to illustrate the
// various types of declarations (and constructors)
vector<int> v1;
vector<int> v2(4);
int numInts;
cout << "Enter capacity of v3: ";
cin >> numInts;
vector<int> v3(numInts);
//vector<int> v4(3, 50);
//The preceding declaration should work, but it may not in some
// versions of some compilers. The following is a work-around:
vector<int> v4(3);
for (int i = 0; i < 3; i++) v4[i] = 50;
//--- End of work-around
int a[] = {1, 12, 30, 52, 66};
vector<int> v5(a, (a + 5));
vector<int> v6;
//--- 1 --- Add:
// Statements to display the capacity and size of each vector<int>
// and whether it is empty
cout << "Part 1" << endl;
cout << "Size of Vector 1: " << v1.capacity() << endl;
if (v1.empty()){
cout << "Vector 1 is empty." << endl;
}
cout << "Size of Vector 2: " << v2.capacity() << endl;
if (v2.empty()){
cout << "Vector 2 is empty." << endl;
}
cout << "Size of Vector 3: " << v3.capacity() << endl;
if (v3.empty()){
cout << "Vector 3 is empty." << endl;
}
cout << "Size of Vector 4: " << v4.capacity() << endl;
if (v4.empty()){
cout << "Vector 4 is empty." << endl;
}
cout << "Size of Vector 5: " << v5.capacity() << endl;
if (v5.empty()){
cout << "Vector 5 is empty." << endl;
}
cout << "---------------------------------" << endl;
//--- 2 --- Add:
// Statement to display the maximum capacity of a vector<int>
cout << "Part 2" << endl;
cout << "Max size of Vector 1: " << v1.max_size() << endl;
cout << "Capacity of Vector 1: " << v1.capacity() << endl;
cout << "---------------------------------" << endl;
//--- 3 --- Add:
// Statements to see the effect of the reserve() member function
cout << "Part 3" << endl;
v4.reserve(6);
cout << "Capacity of v4:" << v4.capacity() << endl;
cout << "Size of v4:" << v4.size() << endl;
//--- 4 --- Add:
// Output statements of the form cout << vector-variable << endl;
// to display the contents of each vector
cout << "Contents of v1: " << v1 << endl;
cout << "Contents of v2: " << v2 << endl;
cout << "Contents of v3: " << v3 << endl;
cout << "Contents of v4: " << v4 << endl;
cout << "Contents of v5: " << v5 << endl;
//--- 5 --- Add:
// Statements to append 111 to v2 and then output v2's size and contents
// append 222 to v2 and then output v2's size and contents
// append 333 to v2 and then output v2's size and contents
// remove the last element of v2 and then output v2's size
// and contents
cout << "Part 5" << endl;
v2.push_back(111);
cout << "Size of v2: " << v2.size() << endl;
cout << "Contents of v2 " << v2 << endl;
v2.push_back(222);
cout << "Size of v2: " << v2.size() << endl;
cout << "Contents of v2 " << v2 << endl;
v2.push_back(333);
cout << "Size of v2: " << v2.size() << endl;
cout << "Contents of v2 " << v2 << endl;
v2.pop_back();
cout << "Size of v2: " << v2.size() << endl;
cout << "Contents of v2 " << v2 << endl;
//--- 6 --- Statements to investigate how capacities grow
// Add statements to append 99 to v1 and then output v1's capacity, size,
// and contents
cout << "Part 6" << endl;
v1.push_back(99);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
//--- 7 --- Statements to investigate how capacities grow
// Add statements to append 101, 202, 303, 404, and 505 to v1 and output
// v1's capacity, size, and contents after each value is appended
v1.push_back(101);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
v1.push_back(202);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
v1.push_back(303);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
v1.push_back(404);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
v1.push_back(505);
cout << "Contents of v1: " << v1 << endl;
cout << "Size of v1: " << v1.size() << endl;
cout << "Capacity of v1: " << v1.capacity() << endl;
//--- 8 --- Statements to investigate how capacities grow
// Remove the comment delimiters from the following:
int oldCapacity = v1.capacity();
cout << "(old) v1.capacity() = " << oldCapacity << endl;
for (int i = v1.size() + 1; i <= 2500; i++)
{
v1.push_back(99);
if (v1.capacity() == v1.size())
cout << "\n*** v1 is full with " << v1.size() << " elements\n";
if (v1.capacity() > oldCapacity)
{
cout << "Adding additional one element increases capacity from "
<< oldCapacity << " to " << v1.capacity() << endl;
oldCapacity = v1.capacity();
}
}
//--- 9 --- Statements to see if element type affects how capacities grow
// Add:
// A declaration of an empty vector<double> v0;
// A loop like the preceding but with v1 replaced by v0
//
vector<double> v0;
oldCapacity = v0.capacity();
cout << "(old) v0.capacity() = " << oldCapacity << endl;
for (int i = v0.size() + 1; i <= 2500; i++)
{
v1.push_back(99);
if (v0.capacity() == v0.size())
cout << "\n*** v0 is full with " << v1.size() << " elements\n";
if (v0.capacity() > oldCapacity)
{
cout << "Adding additional one element increases capacity from "
<< oldCapacity << " to " << v0.capacity() << endl;
oldCapacity = v0.capacity();
}
}
//--- 10 --- Statements to see how initial capacity affects
// how capacities grow
//
// Uncomment the following line:
cout << "Initial capacity of v4 is " << v4.capacity() << endl;
// Add a loop like that in 9 but output changes in v4's capacity
oldCapacity = v4.capacity();
cout << "(old) v4.capacity() = " << oldCapacity << endl;
for (int i = v4.size() + 1; i <= 2500; i++)
{
v1.push_back(99);
if (v4.capacity() == v4.size())
cout << "\n*** v1 is full with " << v1.size() << " elements\n";
if (v4.capacity() > oldCapacity)
{
cout << "Adding additional one element increases capacity from "
<< oldCapacity << " to " << v4.capacity() << endl;
oldCapacity = v4.capacity();
}
}
//--- 11 --- Statements to access the ends of a vector
// Uncomment the following line:
cout << "Original contents of v5: " << v5 << endl;
// Add statements to:
// Output the first and last elements of v5
cout << "First of v5: " << v5.front() << endl;
cout << "Last of v5: " << v5.back() << endl;
// Change the first element to 787 and the last element to 878
v5.front() = 787;
v5.back() = 878;
// Output the contents of v5
cout << "New contents of v5: " << v5 << endl;
//--- 12 --- Statements to demonstrate correct and incorrect
// use of the subscript operator
// Add statements that try using the subscript operator to:
// change the value in location 2 of v2 to 200
// append the value 300 to v2
v2[2] = 200;
cout << "Contents of v2: " << v2 << endl;
v2[5] = 300;
cout << "Contents of v2: " << v2 << endl;
for (int i = 0; i <= v2.size(); i++)
cout << v2[i] << "=";
cout << endl;
cout << v2.size() << endl;
cout << v2.capacity() << endl;
}
| 29.972308 | 80 | 0.470691 | [
"vector"
] |
40f641a666ef401d002406a5697285f749676a7e | 22,451 | cpp | C++ | src/nodejs/unit-http/unit.cpp | mpmc/unit | 64cd10254627fa7db2d44f0494703009e05703b5 | [
"Apache-2.0"
] | 1 | 2019-03-20T06:18:50.000Z | 2019-03-20T06:18:50.000Z | src/nodejs/unit-http/unit.cpp | mpmc/unit | 64cd10254627fa7db2d44f0494703009e05703b5 | [
"Apache-2.0"
] | null | null | null | src/nodejs/unit-http/unit.cpp | mpmc/unit | 64cd10254627fa7db2d44f0494703009e05703b5 | [
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) NGINX, Inc.
*/
#include "unit.h"
napi_ref Unit::constructor_;
Unit::Unit(napi_env env):
env_(env),
wrapper_(nullptr),
unit_ctx_(nullptr)
{
}
Unit::~Unit()
{
napi_delete_reference(env_, wrapper_);
}
napi_value
Unit::init(napi_env env, napi_value exports)
{
napi_value cons, fn;
napi_status status;
napi_property_descriptor properties[] = {
{ "createServer", 0, create_server, 0, 0, 0, napi_default, 0 },
{ "listen", 0, listen, 0, 0, 0, napi_default, 0 }
};
status = napi_define_class(env, "Unit", NAPI_AUTO_LENGTH, create, nullptr,
2, properties, &cons);
if (status != napi_ok) {
goto failed;
}
status = napi_create_reference(env, cons, 1, &constructor_);
if (status != napi_ok) {
goto failed;
}
status = napi_set_named_property(env, exports, "Unit", cons);
if (status != napi_ok) {
goto failed;
}
status = napi_create_function(env, NULL, 0, response_send_headers, NULL,
&fn);
if (status != napi_ok) {
goto failed;
}
status = napi_set_named_property(env, exports,
"unit_response_headers", fn);
if (status != napi_ok) {
goto failed;
}
status = napi_create_function(env, NULL, 0, response_write, NULL, &fn);
if (status != napi_ok) {
goto failed;
}
status = napi_set_named_property(env, exports, "unit_response_write", fn);
if (status != napi_ok) {
goto failed;
}
status = napi_create_function(env, NULL, 0, response_end, NULL, &fn);
if (status != napi_ok) {
goto failed;
}
status = napi_set_named_property(env, exports, "unit_response_end", fn);
if (status != napi_ok) {
goto failed;
}
return exports;
failed:
napi_throw_error(env, NULL, "Failed to define Unit class");
return nullptr;
}
void
Unit::destroy(napi_env env, void *nativeObject, void *finalize_hint)
{
Unit *obj = reinterpret_cast<Unit *>(nativeObject);
delete obj;
}
napi_value
Unit::create(napi_env env, napi_callback_info info)
{
Unit *obj;
napi_value target, cons, instance, jsthis;
napi_status status;
status = napi_get_new_target(env, info, &target);
if (status != napi_ok) {
goto failed;
}
if (target != nullptr) {
/* Invoked as constructor: `new Unit(...)` */
status = napi_get_cb_info(env, info, nullptr, nullptr, &jsthis,
nullptr);
if (status != napi_ok) {
goto failed;
}
obj = new Unit(env);
status = napi_wrap(env, jsthis, reinterpret_cast<void *>(obj),
destroy, nullptr, &obj->wrapper_);
if (status != napi_ok) {
goto failed;
}
return jsthis;
}
/* Invoked as plain function `Unit(...)`, turn into construct call. */
status = napi_get_reference_value(env, constructor_, &cons);
if (status != napi_ok) {
goto failed;
}
status = napi_new_instance(env, cons, 0, nullptr, &instance);
if (status != napi_ok) {
goto failed;
}
return instance;
failed:
napi_throw_error(env, NULL, "Failed to create Unit object");
return nullptr;
}
napi_value
Unit::create_server(napi_env env, napi_callback_info info)
{
Unit *obj;
size_t argc;
napi_value jsthis;
napi_status status;
napi_value argv[1];
nxt_unit_init_t unit_init;
argc = 1;
status = napi_get_cb_info(env, info, &argc, argv, &jsthis, nullptr);
if (status != napi_ok) {
goto failed;
}
status = napi_unwrap(env, jsthis, reinterpret_cast<void **>(&obj));
if (status != napi_ok) {
goto failed;
}
memset(&unit_init, 0, sizeof(nxt_unit_init_t));
unit_init.data = obj;
unit_init.callbacks.request_handler = request_handler;
obj->unit_ctx_ = nxt_unit_init(&unit_init);
if (obj->unit_ctx_ == NULL) {
goto failed;
}
return nullptr;
failed:
napi_throw_error(env, NULL, "Failed to create Unit object");
return nullptr;
}
napi_value
Unit::listen(napi_env env, napi_callback_info info)
{
int ret;
Unit *obj;
napi_value jsthis;
napi_status status;
status = napi_get_cb_info(env, info, nullptr, nullptr, &jsthis, nullptr);
if (status != napi_ok) {
goto failed;
}
status = napi_unwrap(env, jsthis, reinterpret_cast<void **>(&obj));
if (status != napi_ok) {
goto failed;
}
if (obj->unit_ctx_ == NULL) {
napi_throw_error(env, NULL, "Unit context was not created");
return nullptr;
}
ret = nxt_unit_run(obj->unit_ctx_);
if (ret != NXT_UNIT_OK) {
napi_throw_error(env, NULL, "Failed to run Unit");
return nullptr;
}
nxt_unit_done(obj->unit_ctx_);
return nullptr;
failed:
napi_throw_error(env, NULL, "Failed to listen Unit socket");
return nullptr;
}
void
Unit::request_handler(nxt_unit_request_info_t *req)
{
Unit *obj;
napi_value socket, request, response;
napi_value global, server_obj;
napi_value req_argv[3];
napi_status status;
obj = reinterpret_cast<Unit *>(req->unit->data);
napi_handle_scope scope;
status = napi_open_handle_scope(obj->env_, &scope);
if (status != napi_ok) {
napi_throw_error(obj->env_, NULL, "Failed to create handle scope");
return;
}
server_obj = obj->get_server_object();
if (server_obj == nullptr) {
napi_throw_error(obj->env_, NULL, "Failed to get server object");
return;
}
status = napi_get_global(obj->env_, &global);
if (status != napi_ok) {
napi_throw_error(obj->env_, NULL, "Failed to get global variable");
return;
}
socket = obj->create_socket(server_obj, req);
if (socket == nullptr) {
napi_throw_error(obj->env_, NULL, "Failed to create socket object");
return;
}
request = obj->create_request(server_obj, socket);
if (request == nullptr) {
napi_throw_error(obj->env_, NULL, "Failed to create request object");
return;
}
response = obj->create_response(server_obj, socket, request, req, obj);
if (response == nullptr) {
napi_throw_error(obj->env_, NULL, "Failed to create response object");
return;
}
req_argv[1] = request;
req_argv[2] = response;
status = obj->create_headers(req, request);
if (status != napi_ok) {
napi_throw_error(obj->env_, NULL, "Failed to create headers");
return;
}
obj->emit(server_obj, "request", sizeof("request") - 1, 3, req_argv);
obj->emit_post_data(request, req);
napi_close_handle_scope(obj->env_, scope);
}
napi_value
Unit::get_server_object()
{
napi_value unit_obj, server_obj;
napi_status status;
status = napi_get_reference_value(env_, wrapper_, &unit_obj);
if (status != napi_ok) {
return nullptr;
}
status = napi_get_named_property(env_, unit_obj, "server", &server_obj);
if (status != napi_ok) {
return nullptr;
}
return server_obj;
}
napi_value
Unit::emit(napi_value obj, const char *name, size_t name_len, size_t argc,
napi_value *argv)
{
napi_value emitter, return_val, str;
napi_status status;
status = napi_get_named_property(env_, obj, "emit", &emitter);
if (status != napi_ok) {
return nullptr;
}
status = napi_create_string_latin1(env_, name, name_len, &str);
if (status != napi_ok) {
return nullptr;
}
if (argc != 0) {
argv[0] = str;
} else {
argc = 1;
argv = &str;
}
status = napi_call_function(env_, obj, emitter, argc, argv, &return_val);
if (status != napi_ok) {
return nullptr;
}
return return_val;
}
napi_status
Unit::create_headers(nxt_unit_request_info_t *req, napi_value request)
{
uint32_t i;
const char *p;
napi_value headers, raw_headers, str;
napi_status status;
nxt_unit_field_t *f;
nxt_unit_request_t *r;
r = req->request;
status = napi_create_object(env_, &headers);
if (status != napi_ok) {
return status;
}
status = napi_create_array_with_length(env_, r->fields_count * 2,
&raw_headers);
if (status != napi_ok) {
return status;
}
for (i = 0; i < r->fields_count; i++) {
f = r->fields + i;
status = this->append_header(f, headers, raw_headers, i);
if (status != napi_ok) {
return status;
}
}
status = napi_set_named_property(env_, request, "headers", headers);
if (status != napi_ok) {
return status;
}
status = napi_set_named_property(env_, request, "raw_headers", raw_headers);
if (status != napi_ok) {
return status;
}
p = (const char *) nxt_unit_sptr_get(&r->version);
status = napi_create_string_latin1(env_, p, r->version_length, &str);
if (status != napi_ok) {
return status;
}
status = napi_set_named_property(env_, request, "httpVersion", str);
if (status != napi_ok) {
return status;
}
p = (const char *) nxt_unit_sptr_get(&r->method);
status = napi_create_string_latin1(env_, p, r->method_length, &str);
if (status != napi_ok) {
return status;
}
status = napi_set_named_property(env_, request, "method", str);
if (status != napi_ok) {
return status;
}
p = (const char *) nxt_unit_sptr_get(&r->target);
status = napi_create_string_latin1(env_, p, r->target_length, &str);
if (status != napi_ok) {
return status;
}
status = napi_set_named_property(env_, request, "url", str);
if (status != napi_ok) {
return status;
}
return napi_ok;
}
inline napi_status
Unit::append_header(nxt_unit_field_t *f, napi_value headers,
napi_value raw_headers, uint32_t idx)
{
const char *name, *value;
napi_value str, vstr;
napi_status status;
value = (const char *) nxt_unit_sptr_get(&f->value);
status = napi_create_string_latin1(env_, value, f->value_length, &vstr);
if (status != napi_ok) {
return status;
}
name = (const char *) nxt_unit_sptr_get(&f->name);
status = napi_set_named_property(env_, headers, name, vstr);
if (status != napi_ok) {
return status;
}
status = napi_create_string_latin1(env_, name, f->name_length, &str);
if (status != napi_ok) {
return status;
}
status = napi_set_element(env_, raw_headers, idx * 2, str);
if (status != napi_ok) {
return status;
}
status = napi_set_element(env_, raw_headers, idx * 2 + 1, vstr);
if (status != napi_ok) {
return status;
}
return napi_ok;
}
napi_value
Unit::create_socket(napi_value server_obj, nxt_unit_request_info_t *req)
{
napi_value constructor, return_val;
napi_status status;
status = napi_get_named_property(env_, server_obj, "socket",
&constructor);
if (status != napi_ok) {
return nullptr;
}
status = napi_new_instance(env_, constructor, 0, NULL, &return_val);
if (status != napi_ok) {
return nullptr;
}
return return_val;
}
napi_value
Unit::create_request(napi_value server_obj, napi_value socket)
{
napi_value constructor, return_val;
napi_status status;
status = napi_get_named_property(env_, server_obj, "request",
&constructor);
if (status != napi_ok) {
return nullptr;
}
status = napi_new_instance(env_, constructor, 1, &server_obj,
&return_val);
if (status != napi_ok) {
return nullptr;
}
status = napi_set_named_property(env_, return_val, "socket", socket);
if (status != napi_ok) {
return nullptr;
}
return return_val;
}
napi_value
Unit::create_response(napi_value server_obj, napi_value socket,
napi_value request, nxt_unit_request_info_t *req,
Unit *obj)
{
napi_value constructor, return_val, req_num;
napi_status status;
status = napi_get_named_property(env_, server_obj, "response",
&constructor);
if (status != napi_ok) {
return nullptr;
}
status = napi_new_instance(env_, constructor, 1, &request, &return_val);
if (status != napi_ok) {
return nullptr;
}
status = napi_set_named_property(env_, return_val, "socket", socket);
if (status != napi_ok) {
return nullptr;
}
status = napi_create_int64(env_, (int64_t) (uintptr_t) req, &req_num);
if (status != napi_ok) {
return nullptr;
}
status = napi_set_named_property(env_, return_val, "_req_point", req_num);
if (status != napi_ok) {
return nullptr;
}
return return_val;
}
void
Unit::emit_post_data(napi_value request, nxt_unit_request_info_t *req)
{
void *data;
napi_value req_argv[2];
napi_status status;
status = napi_create_buffer(env_, (size_t) req->content_length,
&data, &req_argv[1]);
if (status != napi_ok) {
napi_throw_error(env_, NULL, "Failed to create request buffer");
return;
}
nxt_unit_request_read(req, data, req->content_length);
emit(request, "data", sizeof("data") - 1, 2, req_argv);
emit(request, "end", sizeof("end") - 1, 0, nullptr);
}
napi_value
Unit::response_send_headers(napi_env env, napi_callback_info info)
{
int ret;
char *ptr, *name_ptr;
bool is_array;
size_t argc, name_len, value_len;
int64_t req_p;
uint32_t status_code, header_len, keys_len, array_len;
uint32_t keys_count, i, j;
uint16_t hash;
napi_value this_arg, headers, keys, name, value, array_val;
napi_value req_num;
napi_status status;
nxt_unit_field_t *f;
nxt_unit_request_info_t *req;
napi_value argv[5];
argc = 5;
status = napi_get_cb_info(env, info, &argc, argv, &this_arg, NULL);
if (status != napi_ok) {
return nullptr;
}
if (argc != 5) {
napi_throw_error(env, NULL, "Wrong args count. Need three: "
"statusCode, headers, headers count, headers length");
return nullptr;
}
status = napi_get_named_property(env, argv[0], "_req_point", &req_num);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
status = napi_get_value_int64(env, req_num, &req_p);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
req = (nxt_unit_request_info_t *) (uintptr_t) req_p;
status = napi_get_value_uint32(env, argv[1], &status_code);
if (status != napi_ok) {
goto failed;
}
status = napi_get_value_uint32(env, argv[3], &keys_count);
if (status != napi_ok) {
goto failed;
}
status = napi_get_value_uint32(env, argv[4], &header_len);
if (status != napi_ok) {
goto failed;
}
/* Need to reserve extra byte for C-string 0-termination. */
header_len++;
headers = argv[2];
ret = nxt_unit_response_init(req, status_code, keys_count, header_len);
if (ret != NXT_UNIT_OK) {
goto failed;
}
status = napi_get_property_names(env, headers, &keys);
if (status != napi_ok) {
goto failed;
}
status = napi_get_array_length(env, keys, &keys_len);
if (status != napi_ok) {
goto failed;
}
ptr = req->response_buf->free;
for (i = 0; i < keys_len; i++) {
status = napi_get_element(env, keys, i, &name);
if (status != napi_ok) {
goto failed;
}
status = napi_get_property(env, headers, name, &value);
if (status != napi_ok) {
goto failed;
}
status = napi_get_value_string_latin1(env, name, ptr, header_len,
&name_len);
if (status != napi_ok) {
goto failed;
}
name_ptr = ptr;
ptr += name_len;
header_len -= name_len;
hash = nxt_unit_field_hash(name_ptr, name_len);
status = napi_is_array(env, value, &is_array);
if (status != napi_ok) {
goto failed;
}
if (is_array) {
status = napi_get_array_length(env, value, &array_len);
if (status != napi_ok) {
goto failed;
}
for (j = 0; j < array_len; j++) {
status = napi_get_element(env, value, j, &array_val);
if (status != napi_ok) {
goto failed;
}
status = napi_get_value_string_latin1(env, array_val, ptr,
header_len,
&value_len);
if (status != napi_ok) {
goto failed;
}
f = req->response->fields + req->response->fields_count;
f->skip = 0;
nxt_unit_sptr_set(&f->name, name_ptr);
f->name_length = name_len;
f->hash = hash;
nxt_unit_sptr_set(&f->value, ptr);
f->value_length = (uint32_t) value_len;
ptr += value_len;
header_len -= value_len;
req->response->fields_count++;
}
} else {
status = napi_get_value_string_latin1(env, value, ptr, header_len,
&value_len);
if (status != napi_ok) {
goto failed;
}
f = req->response->fields + req->response->fields_count;
f->skip = 0;
nxt_unit_sptr_set(&f->name, name_ptr);
f->name_length = name_len;
f->hash = hash;
nxt_unit_sptr_set(&f->value, ptr);
f->value_length = (uint32_t) value_len;
ptr += value_len;
header_len -= value_len;
req->response->fields_count++;
}
}
req->response_buf->free = ptr;
ret = nxt_unit_response_send(req);
if (ret != NXT_UNIT_OK) {
goto failed;
}
return this_arg;
failed:
req->response->fields_count = 0;
napi_throw_error(env, NULL, "Failed to write headers");
return nullptr;
}
napi_value
Unit::response_write(napi_env env, napi_callback_info info)
{
int ret;
char *ptr;
size_t argc, have_buf_len;
int64_t req_p;
uint32_t buf_len;
napi_value this_arg, req_num;
napi_status status;
nxt_unit_buf_t *buf;
napi_valuetype buf_type;
nxt_unit_request_info_t *req;
napi_value argv[3];
argc = 3;
status = napi_get_cb_info(env, info, &argc, argv, &this_arg, NULL);
if (status != napi_ok) {
goto failed;
}
if (argc != 3) {
napi_throw_error(env, NULL, "Wrong args count. Need two: "
"chunk, chunk length");
return nullptr;
}
status = napi_get_named_property(env, argv[0], "_req_point", &req_num);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
status = napi_get_value_int64(env, req_num, &req_p);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
req = (nxt_unit_request_info_t *) (uintptr_t) req_p;
status = napi_get_value_uint32(env, argv[2], &buf_len);
if (status != napi_ok) {
goto failed;
}
status = napi_typeof(env, argv[1], &buf_type);
if (status != napi_ok) {
goto failed;
}
buf_len++;
buf = nxt_unit_response_buf_alloc(req, buf_len);
if (buf == NULL) {
goto failed;
}
if (buf_type == napi_string) {
/* TODO: will work only for utf8 content-type */
status = napi_get_value_string_utf8(env, argv[1], buf->free,
buf_len, &have_buf_len);
} else {
status = napi_get_buffer_info(env, argv[1], (void **) &ptr,
&have_buf_len);
memcpy(buf->free, ptr, have_buf_len);
}
if (status != napi_ok) {
goto failed;
}
buf->free += have_buf_len;
ret = nxt_unit_buf_send(buf);
if (ret != NXT_UNIT_OK) {
goto failed;
}
return this_arg;
failed:
napi_throw_error(env, NULL, "Failed to write body");
return nullptr;
}
napi_value
Unit::response_end(napi_env env, napi_callback_info info)
{
size_t argc;
int64_t req_p;
napi_value resp, this_arg, req_num;
napi_status status;
nxt_unit_request_info_t *req;
argc = 1;
status = napi_get_cb_info(env, info, &argc, &resp, &this_arg, NULL);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to finalize sending body");
return nullptr;
}
status = napi_get_named_property(env, resp, "_req_point", &req_num);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
status = napi_get_value_int64(env, req_num, &req_p);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to get request pointer");
return nullptr;
}
req = (nxt_unit_request_info_t *) (uintptr_t) req_p;
nxt_unit_request_done(req, NXT_UNIT_OK);
return this_arg;
}
| 24.780353 | 80 | 0.572491 | [
"object"
] |
40f9079eceace850cd2bfdf0ed89431627049203 | 1,732 | hh | C++ | rflib/types/Action.hh | ralph-mikera/routeflow5 | ea4d5c17d70760b15f8597d913414bad7e3a67bd | [
"Apache-2.0"
] | null | null | null | rflib/types/Action.hh | ralph-mikera/routeflow5 | ea4d5c17d70760b15f8597d913414bad7e3a67bd | [
"Apache-2.0"
] | null | null | null | rflib/types/Action.hh | ralph-mikera/routeflow5 | ea4d5c17d70760b15f8597d913414bad7e3a67bd | [
"Apache-2.0"
] | null | null | null | #ifndef __ACTION_HH__
#define __ACTION_HH__
#include "TLV.hh"
enum ActionType {
RFAT_OUTPUT = 1, /* Output port */
RFAT_SET_ETH_SRC = 2, /* Ethernet source address */
RFAT_SET_ETH_DST = 3, /* Ethernet destination address */
RFAT_PUSH_MPLS = 4, /* Push MPLS label */
RFAT_POP_MPLS = 5, /* Pop MPLS label */
RFAT_SWAP_MPLS = 6, /* Swap MPLS label */
RFAT_SET_VLAN_ID = 7, /* Set VLAN ID */
RFAT_STRIP_VLAN_DEFERRED = 8, /* Strip outermost VLAN (defer in write instructions) */
RFAT_SWAP_VLAN_ID = 9, /* Swap VLAN ID */
RFAT_GROUP = 10, /* Output group */
RFAT_GOTO = 11, /* Goto table */
RFAT_DROP = 254, /* Drop packet (Unimplemented) */
RFAT_SFLOW = 255, /* Generate SFlow messages (Unimplemented) */
};
class Action : public TLV {
public:
Action(const Action& other);
Action(ActionType, boost::shared_array<uint8_t> value);
Action(ActionType, const uint8_t* value);
Action(ActionType, const uint32_t value);
Action(ActionType, const MACAddress&);
Action(ActionType, const IPAddress& addr, const IPAddress& mask);
Action& operator=(const Action& other);
bool operator==(const Action& other);
virtual std::string type_to_string() const;
virtual mongo::BSONObj to_BSON() const;
static Action* from_BSON(mongo::BSONObj);
private:
static size_t type_to_length(uint8_t);
static byte_order type_to_byte_order(uint8_t);
};
namespace ActionList {
mongo::BSONArray to_BSON(const std::vector<Action> list);
std::vector<Action> to_vector(std::vector<mongo::BSONElement> array);
}
#endif /* __ACTION_HH__ */
| 36.083333 | 90 | 0.642032 | [
"vector"
] |
40faaaa07c2ac9e0f65bb88e8f372b1925989842 | 12,234 | cpp | C++ | src/parser.cpp | LesleyLai/eml | bb73367c0604005b1d7467c004ca13d328a6bcb6 | [
"MIT"
] | 3 | 2020-11-03T19:22:11.000Z | 2021-05-05T13:16:15.000Z | src/parser.cpp | LesleyLai/eml | bb73367c0604005b1d7467c004ca13d328a6bcb6 | [
"MIT"
] | 2 | 2020-04-01T12:57:24.000Z | 2021-02-19T10:17:30.000Z | src/parser.cpp | LesleyLai/eml | bb73367c0604005b1d7467c004ca13d328a6bcb6 | [
"MIT"
] | 2 | 2020-10-15T18:28:18.000Z | 2020-10-25T16:44:17.000Z | #include "parser.hpp"
#include "ast.hpp"
#include "common.hpp"
#include "debug.hpp"
#include "scanner.hpp"
#include "string.hpp"
#include "type.hpp"
#include <cstdint>
#include <vector>
namespace eml {
// A error node that represents with syntax error
class ErrorExpr final : public Expr, public FactoryMixin<ErrorExpr> {
void accept(AstVisitor& /*visitor*/) override
{
EML_UNREACHABLE();
}
void accept(AstConstVisitor& /*visitor*/) const override
{
EML_UNREACHABLE();
}
};
struct Parser;
auto parse_toplevel(Parser& parser) -> std::unique_ptr<AstNode>;
auto parse_expression(Parser& parser) -> Expr_ptr;
struct Parser {
explicit Parser(std::string_view source, GarbageCollector& gc)
: scanner{source}, current_itr{scanner.begin()}, garbage_collector{gc}
{
check_unsupported_token_type(*current_itr);
}
eml::Scanner scanner;
eml::Scanner::iterator current_itr;
eml::Token previous;
std::vector<CompilationError> errors;
std::reference_wrapper<GarbageCollector> garbage_collector;
bool had_error = false;
bool panic_mode = false; // Ignore errors if in panic
void check_unsupported_token_type(const eml::Token& token)
{
const auto type = token.type;
switch (type) {
case token_type::colon:
case token_type::semicolon:
case token_type::greator_greator:
case token_type::less_less:
error_at(token, "This operator is reserved by EML language for future "
"development, but "
"currently the language does not support it");
break;
case token_type::keyword_and:
case token_type::keyword_async:
case token_type::keyword_await:
case token_type::keyword_case:
case token_type::keyword_class:
case token_type::keyword_def:
case token_type::keyword_extern:
case token_type::keyword_for:
case token_type::keyword_not:
case token_type::keyword_or:
case token_type::keyword_return:
case token_type::keyword_this:
case token_type::keyword_unsafe:
case token_type::keyword_variant:
error_at(token, "This keyword is reserved by EML language for future "
"development, but "
"currently the language does not support it");
break;
default:
return; // Do nothing
}
}
// Check if the current token match a type, produces error otherwise
void check(const eml::token_type type, const char* message)
{
if (current_itr->type == type) {
return;
}
error_at(*current_itr, message);
}
void consume(const eml::token_type type, const char* message)
{
if (current_itr->type == type) {
advance();
return;
}
error_at(*current_itr, message);
}
void error_at(const eml::Token& token, std::string message)
{
if (panic_mode) {
return;
}
panic_mode = true;
errors.emplace_back(std::in_place_type<SyntaxError>, std::move(message),
token);
had_error = true;
}
void error_at_previous(const std::string& message)
{
error_at(previous, message);
}
void advance()
{
previous = *current_itr;
while (true) {
const auto current = *(++current_itr);
check_unsupported_token_type(current);
if (current.type != token_type::error) {
break;
}
// Hits an error token
error_at(current, std::string(current.text));
}
}
};
// clang-format off
/**
* @page precedence Precedence and Associativity
* This page shows which expressions have higher precedence, and their
* associativity.
*
| Precedence | Operators | Description | Associativity |
| ----: | :----: | :---- | :---- |
| 1 | `.` `()` `[]` | Grouping, Subscript, Function call | Left |
| 2 | `!` `-` | Unary | Right |
| 3 | `*` `/` | Multiply, Divide | Left |
| 4 | `+` `-` `++` | Add, Subtract, Append | Left |
| 5 | `<` `>` `<=` `>=` | Comparison | Left |
| 6 | `==` `!=` | Equality comparison | Left |
| 7 | `and` | Logical and | Left |
| 8 | `or` | Logical or | Left |
| 9 | `\` | Lambda | Right |
| 10 | `=` | Definition, Assignment | Right |
*/
// clang-format on
enum Precedence : std::uint8_t {
prec_none,
prec_assignment, // =
prec_lambda, // "\"
prec_or, // or
prec_and, // and
prec_equality, // == !=
prec_comparison, // < > <= >=
prec_term, // + - ++
prec_factor, // * /
prec_unary, // ! -
prec_call, // . () []
prec_primary
};
using PrefixParselet = Expr_ptr (*)(Parser& Parser);
using InfixParselet = Expr_ptr (*)(Parser& Parser, Expr_ptr left);
struct ParseRule {
PrefixParselet prefix;
InfixParselet infix;
Precedence precedence;
};
constexpr auto get_rule(token_type type) -> ParseRule;
auto higher(Precedence p) -> Precedence
{
return static_cast<Precedence>(
static_cast<std::underlying_type_t<Precedence>>(p) + 1);
}
auto parse_block(Parser& parser) -> Expr_ptr
{
auto expr = parse_expression(parser);
parser.consume(token_type::right_brace, "A block must end with \'}\'");
return expr;
}
auto parse_grouping(Parser& parser) -> Expr_ptr
{
auto expr_ptr = parse_expression(parser);
parser.consume(eml::token_type::right_paren,
"Expect `)` at the end of the expression");
return expr_ptr;
}
// if else
auto parse_branch(Parser& parser) -> Expr_ptr
{
parser.consume(eml::token_type::left_paren,
"condition of an if expression must in a group");
auto cond = parse_grouping(parser);
auto If = parse_expression(parser);
parser.consume(token_type::keyword_else,
"if expression must have an else branch");
auto Else = parse_expression(parser);
return IfExpr::create(std::move(cond), std::move(If), std::move(Else));
}
auto parse_number(Parser& parser) -> Expr_ptr
{
const double number = strtod(parser.previous.text.data(), nullptr);
return LiteralExpr::create(Value{number}, NumberType{});
}
auto parse_string(Parser& parser) -> Expr_ptr
{
std::string_view text{parser.previous.text};
text.remove_prefix(1);
text.remove_suffix(1);
auto s_obj = eml::make_string(text, parser.garbage_collector);
return LiteralExpr::create(Value{s_obj}, StringType{});
}
auto parse_definition(Parser& parser) -> std::unique_ptr<AstNode>
{
parser.advance();
const auto id = parser.current_itr->text;
parser.advance();
parser.consume(token_type::equal, "Missing equal sign in let");
auto expr = parse_expression(parser);
parser.advance();
return Definition::create(id, std::move(expr));
}
auto parse_identifier(Parser& parser) -> std::unique_ptr<Expr>
{
return IdentifierExpr::create(std::string{parser.previous.text});
}
auto parse_literal(Parser& parser) -> Expr_ptr
{
switch (parser.previous.type) {
case token_type::keyword_unit:
return LiteralExpr::create(Value{}, UnitType{});
case token_type::keyword_true:
return LiteralExpr::create(Value{true}, BoolType{});
case token_type::keyword_false:
return LiteralExpr::create(Value{false}, BoolType{});
default:
EML_UNREACHABLE();
}
}
// parses any expression of a given precedence level or higher:
auto parse_precedence(Parser& parser, Precedence precedence) -> Expr_ptr
{
parser.advance();
if (parser.previous.type == token_type::error) {
parser.error_at_previous(std::string{parser.previous.text});
return ErrorExpr::create();
}
const auto prefix_rule = get_rule(parser.previous.type).prefix;
if (prefix_rule == nullptr) {
parser.error_at_previous("expect a prefix operator");
return ErrorExpr::create();
}
auto left_ptr = prefix_rule(parser);
while (precedence <= get_rule(parser.current_itr->type).precedence) {
parser.advance();
const auto infix_rule = get_rule(parser.previous.type).infix;
if (infix_rule == nullptr) {
parser.error_at_previous("expect a infix operator");
return ErrorExpr::create();
}
left_ptr = infix_rule(parser, std::move(left_ptr));
}
return left_ptr;
}
auto parse_toplevel(Parser& parser) -> std::unique_ptr<AstNode>
{
switch (parser.current_itr->type) {
case token_type::keyword_let:
return parse_definition(parser);
default:
return parse_expression(parser);
}
}
auto parse_expression(Parser& parser) -> Expr_ptr
{
return parse_precedence(parser, prec_assignment);
}
auto parse_lambda(Parser& parser) -> Expr_ptr
{
std::vector<std::string> args;
for (; parser.current_itr->type == token_type::identifier; parser.advance()) {
args.emplace_back(parser.current_itr->text);
}
parser.consume(token_type::minus_right_arrow, "A lambda must have ->");
if (args.empty()) {
parser.error_at_previous("A lambda should have at least one argument!");
}
auto expr_ptr = parse_expression(parser);
return LambdaExpr::create(std::move(args), std::move(expr_ptr));
}
auto parse_unary(Parser& parser) -> Expr_ptr
{
const token_type operator_type = parser.previous.type;
// Compile the operand.
auto operand_ptr = parse_precedence(parser, prec_unary);
// Emit the operator instruction.
switch (operator_type) {
case token_type::bang:
return UnaryNotExpr::create(std::move(operand_ptr));
case token_type::minus:
return UnaryNegateExpr::create(std::move(operand_ptr));
default:
EML_UNREACHABLE();
}
}
auto parse_binary(Parser& parser, Expr_ptr left_ptr) -> Expr_ptr
{
// Remember the operator.
token_type operator_type = parser.previous.type;
// Compile the right operand.
const ParseRule rule = get_rule(operator_type);
auto rhs_ptr = parse_precedence(parser, higher(rule.precedence));
// Emit the operator instruction.
switch (operator_type) {
case token_type::plus:
return PlusOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::minus:
return MinusOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::star:
return MultOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::slash:
return DivOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::double_equal:
return EqOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::bang_equal:
return NeqOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::less:
return LessOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::less_equal:
return LeOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::greator:
return GreaterOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::greater_equal:
return GeExpr::create(std::move(left_ptr), std::move(rhs_ptr));
case token_type::plus_plus:
return AppendOpExpr::create(std::move(left_ptr), std::move(rhs_ptr));
default:
EML_UNREACHABLE();
}
}
// Get parse Rules
constexpr auto get_rule(token_type type) -> ParseRule
{
switch (type) {
#define TOKEN_TABLE_ENTRY(type, type_name, prefix, infix, precedence) \
case token_type::type: \
return ParseRule{prefix, infix, prec_##precedence};
#include "../src/token_table.inc"
#undef TOKEN_TABLE_ENTRY
}
// Unreachable
return ParseRule{};
}
[[nodiscard]]
auto parse(std::string_view source, GarbageCollector& gc) -> ParseResult
{
Parser parser{source, gc};
auto expr = parse_toplevel(parser);
parser.consume(token_type::eof, "Expect end of expression");
if (parser.had_error) {
return unexpected{std::move(parser.errors)};
}
if constexpr (eml::BuildOptions::debug_print_ast) {
std::cout << eml::to_string(*expr) << '\n';
}
return expr;
}
} // namespace eml
| 27.931507 | 88 | 0.645333 | [
"vector"
] |
40fb9a2a26c7468d163061469af28e0cbaf7253f | 6,487 | cpp | C++ | code/engine/xrEngine/editor_environment_effects_effect.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 58 | 2016-11-20T19:14:35.000Z | 2021-12-27T21:03:35.000Z | code/engine/xrEngine/editor_environment_effects_effect.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 59 | 2016-09-10T10:44:20.000Z | 2018-09-03T19:07:30.000Z | code/engine/xrEngine/editor_environment_effects_effect.cpp | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 39 | 2017-02-05T13:35:37.000Z | 2022-03-14T11:00:12.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : editor_environment_effects_effect.cpp
// Created : 28.12.2007
// Modified : 28.12.2007
// Author : Dmitriy Iassenev
// Description : editor environment effects effect class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#ifdef INGAME_EDITOR
#include "editor_environment_effects_effect.hpp"
#include "editor/property_holder.hpp"
#include "editor_environment_manager.hpp"
#include "ide.hpp"
#include "editor_environment_effects_manager.hpp"
#include "editor_environment_detail.hpp"
using editor::environment::effects::effect;
using editor::environment::effects::manager;
effect::effect(manager const& manager, std::string id)
: m_manager(manager), m_property_holder(0), m_id(std::move(id)), m_sound("") {
particles = "";
}
effect::~effect() {
if (!Device.editor())
return;
::ide().destroy(m_property_holder);
}
void effect::load(CInifile& config) {
// TODO: [imdex] remove shared_str (ini)
life_time = config.r_u32(m_id.c_str(), "life_time");
offset = config.r_fvector3(m_id.c_str(), "offset");
particles = config.r_string(m_id.c_str(), "particles");
m_sound = config.r_string(m_id.c_str(), "sound");
wind_gust_factor = config.r_float(m_id.c_str(), "wind_gust_factor");
}
void effect::save(CInifile& config) {
config.w_u32(m_id.c_str(), "life_time", life_time);
config.w_fvector3(m_id.c_str(), "offset", offset);
config.w_string(m_id.c_str(), "particles", particles.c_str());
config.w_string(m_id.c_str(), "sound", m_sound.c_str());
config.w_float(m_id.c_str(), "wind_gust_factor", wind_gust_factor);
config.w_float(m_id.c_str(), "wind_blast_in_time", wind_blast_in_time);
config.w_float(m_id.c_str(), "wind_blast_out_time", wind_blast_out_time);
config.w_float(m_id.c_str(), "wind_blast_strength", wind_blast_strength);
config.w_float(m_id.c_str(), "wind_blast_longitude", rad2deg(wind_blast_direction.getH()));
}
LPCSTR effect::id_getter() const { return (m_id.c_str()); }
void effect::id_setter(LPCSTR value_) {
std::string value = value_;
if (m_id == value)
return;
m_id = m_manager.unique_id(value);
}
LPCSTR effect::sound_getter() { return (m_sound.c_str()); }
void effect::sound_setter(LPCSTR value) {
m_sound = value;
sound.destroy();
sound.create(value, st_Effect, sg_SourceType);
}
float effect::wind_blast_longitude_getter() const {
float h, p;
wind_blast_direction.getHP(h, p);
return (rad2deg(h));
}
void effect::wind_blast_longitude_setter(float value) {
wind_blast_direction.setHP(deg2rad(value), 0.f);
}
void effect::fill(editor::property_holder_collection* collection) {
VERIFY(!m_property_holder);
m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
typedef editor::property_holder::string_getter_type string_getter_type;
string_getter_type string_getter;
string_getter.bind(this, &effect::id_getter);
typedef editor::property_holder::string_setter_type string_setter_type;
string_setter_type string_setter;
string_setter.bind(this, &effect::id_setter);
m_property_holder->add_property("id", "properties",
"this option is resposible for effect identifier", m_id.c_str(),
string_getter, string_setter);
m_property_holder->add_property(
"life time", "properties",
"this option is resposible for effect life time (in milliseconds)", (int const&)life_time,
(int&)life_time);
m_property_holder->add_property("offset", "properties",
"this option is resposible for effect offset (3D vector)",
(vec3f const&)offset, (vec3f&)offset);
m_property_holder->add_property(
"particles", "properties", "this option is resposible for effect particles",
particles.c_str(), particles, &*m_manager.environment().particle_ids().begin(),
m_manager.environment().particle_ids().size(),
editor::property_holder::value_editor_tree_view,
editor::property_holder::cannot_enter_text);
string_getter.bind(this, &effect::sound_getter);
string_setter.bind(this, &effect::sound_setter);
m_property_holder->add_property(
"sound", "properties", "this option is resposible for effect sound", m_sound.c_str(),
string_getter, string_setter, ".ogg", "Sound files (*.ogg)|*.ogg",
detail::real_path("$game_sounds$", "").c_str(), "Select sound...",
editor::property_holder::cannot_enter_text, editor::property_holder::remove_extension);
m_property_holder->add_property("wind gust factor", "properties",
"this option is resposible for effect wind gust factor",
wind_gust_factor, wind_gust_factor);
m_property_holder->add_property("wind blast strength", "properties",
"this option is resposible for effect wind blast strength",
wind_blast_strength, wind_blast_strength);
m_property_holder->add_property("wind blast start time", "properties",
"this option is resposible for effect wind blast start time",
wind_blast_in_time, wind_blast_in_time, 0.f, 1000.f);
m_property_holder->add_property("wind blast stop time", "properties",
"this option is resposible for effect wind blast stop time",
wind_blast_out_time, wind_blast_out_time, 0.f, 1000.f);
typedef ::editor::property_holder::float_getter_type float_getter_type;
float_getter_type float_getter;
typedef ::editor::property_holder::float_setter_type float_setter_type;
float_setter_type float_setter;
float_getter.bind(this, &effect::wind_blast_longitude_getter);
float_setter.bind(this, &effect::wind_blast_longitude_setter);
m_property_holder->add_property("wind blast longitude", "properties",
"this option is resposible for effect wind blast longitude",
float_getter(), float_getter, float_setter, -360.f, 360.f);
}
editor::property_holder* effect::object() { return (m_property_holder); }
#endif // #ifdef INGAME_EDITOR | 43.831081 | 100 | 0.657777 | [
"object",
"vector",
"3d"
] |
40fc3887c46ac53c5d7e30e984f5ae63895f1567 | 12,465 | cpp | C++ | src/ops/compute.cpp | patriciogonzalezvivo/hilma | e622c849e60c1c7299729b0e70b59765f1f77a58 | [
"BSD-3-Clause"
] | 70 | 2020-04-29T00:44:37.000Z | 2022-01-17T16:54:48.000Z | src/ops/compute.cpp | patriciogonzalezvivo/hilma | e622c849e60c1c7299729b0e70b59765f1f77a58 | [
"BSD-3-Clause"
] | 2 | 2020-05-18T23:26:18.000Z | 2020-06-12T22:20:45.000Z | src/ops/compute.cpp | patriciogonzalezvivo/hilma | e622c849e60c1c7299729b0e70b59765f1f77a58 | [
"BSD-3-Clause"
] | 6 | 2020-05-20T15:22:25.000Z | 2022-01-15T17:19:05.000Z | #include "hilma/ops/compute.h"
#include <algorithm>
#include <map>
#include "../deps/xatlas.h"
namespace hilma {
//This is for polygon/contour simplification - we use it to reduce the number of m_points needed in
//representing the letters as openGL shapes - will soon be moved to ofGraphics.cpp
// From: http://softsurfer.com/Archive/algorithm_0205/algorithm_0205.htm
// Copyright 2002, softSurfer (www.softsurfer.com)
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.
typedef struct{
glm::vec2 P0, P1;
} Segment;
#define norm2(v) glm::dot(v,v) // norm2 = squared length of vector
#define norm(v) sqrt(norm2(v)) // norm = length of vector
#define d2(u,v) norm2(u-v) // distance squared = norm2 of difference
#define d(u,v) norm(u-v) // distance = norm of difference
//--------------------------------------------------
static void simplifyDP(float tol, glm::vec2* v, int j, int k, int* mk ) {
if (k <= j+1) // there is nothing to simplify
return;
// check for adequate approximation by segment S from v[j] to v[k]
int maxi = j; // index of vertex farthest from S
float maxd2 = 0; // distance squared of farthest vertex
float tol2 = tol * tol; // tolerance squared
Segment S = {v[j], v[k]}; // segment from v[j] to v[k]
glm::vec2 u;
u = S.P1 - S.P0; // segment direction vector
float cu = glm::dot(u,u); // segment length squared
// test each vertex v[i] for max distance from S
// compute using the Feb 2001 Algorithm's dist_ofPoint_to_Segment()
// Note: this works in any dimension (2D, 3D, ...)
glm::vec2 w;
glm::vec2 Pb; // base of perpendicular from v[i] to S
float b, cw, dv2; // dv2 = distance v[i] to S squared
for (int i=j+1; i<k; i++) {
// compute distance squared
w = v[i] - S.P0;
cw = glm::dot(w,u);
if ( cw <= 0 ) dv2 = d2(v[i], S.P0);
else if ( cu <= cw ) dv2 = d2(v[i], S.P1);
else {
b = (float)(cw / cu);
Pb = S.P0 + u*b;
dv2 = d2(v[i], Pb);
}
// test with current max distance squared
if (dv2 <= maxd2) continue;
// v[i] is a new max vertex
maxi = i;
maxd2 = dv2;
}
if (maxd2 > tol2) // error is worse than the tolerance
{
// split the polyline at the farthest vertex from S
mk[maxi] = 1; // mark v[maxi] for the simplified polyline
// recursively simplify the two subpolylines at v[maxi]
simplifyDP( tol, v, j, maxi, mk ); // polyline v[j] to v[maxi]
simplifyDP( tol, v, maxi, k, mk ); // polyline v[maxi] to v[k]
}
// else the approximation is OK, so ignore intermediate vertices
return;
}
std::vector<glm::vec2> getSimplify(const std::vector<glm::vec2>& _points, float _tolerance) {
std::vector<glm::vec2> rta;
rta.assign(_points.begin(),_points.end());
simplify(rta, _tolerance);
return rta;
}
void simplify(std::vector<glm::vec2>& _points, float _tolerance) {
if (_points.size() < 2) return;
int n = _points.size();
if (n == 0) {
return;
}
std::vector<glm::vec2> sV;
sV.resize(n);
int i, k, m, pv; // misc counters
float tol2 = _tolerance * _tolerance; // tolerance squared
std::vector<glm::vec2> vt;
std::vector<int> mk;
vt.resize(n);
mk.resize(n,0);
// STAGE 1. Vertex Reduction within tolerance of prior vertex cluster
vt[0] = _points[0]; // start at the beginning
for (i=k=1, pv=0; i<n; i++) {
if (d2(_points[i], _points[pv]) < tol2) continue;
vt[k++] = _points[i];
pv = i;
}
if (pv < n-1) vt[k++] = _points[n-1]; // finish at the end
// STAGE 2. Douglas-Peucker polyline simplification
mk[0] = mk[k-1] = 1; // mark the first and last vertices
simplifyDP( _tolerance, &vt[0], 0, k-1, &mk[0] );
// copy marked vertices to the output simplified polyline
for (i=m=0; i<k; i++) {
if (mk[i]) sV[m++] = vt[i];
}
//get rid of the unused points
if ( m < (int)sV.size() ) {
_points.assign( sV.begin(),sV.begin()+m );
}else{
_points = sV;
}
}
bool lexicalComparison(const glm::vec2& _v1, const glm::vec2& _v2) {
if (_v1.x > _v2.x) return true;
else if (_v1.x < _v2.x) return false;
else if (_v1.y > _v2.y) return true;
else return false;
}
bool isRightTurn(const glm::vec2& _a, const glm::vec2& _b, const glm::vec2& _c) {
// use the cross product to determin if we have a right turn
return ((_b.x - _a.x)*(_c.y - _a.y) - (_b.y - _a.y)*(_c.x - _a.x)) > 0;
}
std::vector<glm::vec2> getConvexHull(const std::vector<glm::vec2>& _points) {
std::vector<glm::vec2> pts;
pts.assign(_points.begin(),_points.end());
std::vector<glm::vec2> hull;
glm::vec2 h1,h2,h3;
if (_points.size() < 3) {
// std::cout << "Error: you need at least three points to calculate the convex hull" << std::endl;
return hull;
}
std::sort(pts.begin(), pts.end(), &lexicalComparison);
hull.push_back(pts.at(0));
hull.push_back(pts.at(1));
size_t currentPoint = 2;
int direction = 1;
for (int i=0; i<3000; i++) { //max 1000 tries
hull.push_back(pts.at(currentPoint));
// look at the turn direction in the last three points
h1 = hull.at(hull.size()-3);
h2 = hull.at(hull.size()-2);
h3 = hull.at(hull.size()-1);
// while there are more than two points in the hull
// and the last three points do not make a right turn
while (!isRightTurn(h1, h2, h3) && hull.size() > 2) {
// remove the middle of the last three points
hull.erase(hull.end() - 2);
if (hull.size() >= 3) {
h1 = hull.at(hull.size()-3);
}
h2 = hull.at(hull.size()-2);
h3 = hull.at(hull.size()-1);
}
// going through left-to-right calculates the top hull
// when we get to the end, we reverse direction
// and go back again right-to-left to calculate the bottom hull
if (currentPoint == pts.size() -1 || currentPoint == 0) {
direction = direction * -1;
}
currentPoint += direction;
if (hull.front()==hull.back()) {
if (currentPoint == 3 && direction == 1) {
currentPoint = 4;
} else {
break;
}
}
}
return hull;
}
float getArea(const std::vector<glm::vec2>& _points) {
float area = 0.0;
for (int i=0;i<(int)_points.size()-1;i++) {
area += _points[i].x * _points[i+1].y - _points[i+1].x * _points[i].y;
}
area += _points[_points.size()-1].x * _points[0].y - _points[0].x * _points[_points.size()-1].y;
area *= 0.5;
return area;
}
glm::vec2 getCentroid(const std::vector<glm::vec2>& _points) {
glm::vec2 centroid;
for (size_t i = 0; i < _points.size(); i++) {
centroid += _points[i] / (float)_points.size();
}
return centroid;
}
glm::vec3 getCentroid(const std::vector<glm::vec3>& _points) {
glm::vec3 centroid;
for (size_t i = 0; i < _points.size(); i++) {
centroid += _points[i] / (float)_points.size();
}
return centroid;
}
BoundingBox getBoundingBox(const Mesh& _mesh) {
return getBoundingBox(_mesh.vertices);
}
BoundingBox getBoundingBox(const std::vector<glm::vec2>& _points ) {
BoundingBox bbox;
for (std::vector<glm::vec2>::const_iterator it = _points.begin(); it != _points.end(); ++it)
bbox.expand(*it);
return bbox;
}
BoundingBox getBoundingBox(const std::vector<glm::vec3>& _points ) {
BoundingBox bbox;
for (std::vector<glm::vec3>::const_iterator it = _points.begin(); it != _points.end(); ++it)
bbox.expand(*it);
return bbox;
}
BoundingBox getBoundingBox(const std::vector<Line>& _lines) {
BoundingBox bbox;
for (std::vector<Line>::const_iterator it = _lines.begin(); it != _lines.end(); ++it) {
bbox.expand(it->getPoint(0));
bbox.expand(it->getPoint(1));
}
return bbox;
}
BoundingBox getBoundingBox(const std::vector<Triangle>& _triangles) {
BoundingBox bbox;
for (std::vector<Triangle>::const_iterator it = _triangles.begin(); it != _triangles.end(); ++it) {
bbox.expand(it->getVertex(0));
bbox.expand(it->getVertex(1));
bbox.expand(it->getVertex(2));
}
return bbox;
}
glm::vec2 getRange(const Image& _image) {
float min = 10000.0f;
float max = -10000.0f;
int total = _image.getWidth() * _image.getHeight() * _image.getChannels();
for (int i = 0; i < total; i++) {
float val = _image[i];
if (min > val) min = val;
if (max < val) max = val;
}
return glm::vec2(min, max);
}
std::vector<float> getMax(const float* _array2D, int _m, int _n) {
std::vector<float> out;
for (int i = 0; i < _n; i++)
out.push_back(-9999999.9);
for (int i = 0; i < _m; i++)
for (int j = 0; j < _n; j++)
if (_array2D[i * _n + j] > out[j])
out[j] = _array2D[i * _n + j];
return out;
}
std::vector<float> getMin(const float* _array2D, int _m, int _n) {
std::vector<float> out;
for (int i = 0; i < _n; i++)
out.push_back(9999999.9);
for (int i = 0; i < _m; i++)
for (int j = 0; j < _n; j++)
if (_array2D[i * _n + j] < out[j])
out[j] = _array2D[i * _n + j];
return out;
}
void textureAtlas(Mesh& _mesh) {
xatlas::Atlas *atlas = xatlas::Create();
xatlas::MeshDecl meshDecl;
meshDecl.vertexCount = (uint32_t)_mesh.getVerticesTotal();
meshDecl.vertexPositionData = &_mesh.getVertices()[0].x;
meshDecl.vertexPositionStride = sizeof(float) * 3;
if (_mesh.haveNormals()) {
meshDecl.vertexNormalData = &_mesh.getNormals()[0].x;
meshDecl.vertexNormalStride = sizeof(float) * 3;
}
if (_mesh.haveTexCoords()) {
meshDecl.vertexUvData = &_mesh.getNormals()[0].x;
meshDecl.vertexUvStride = sizeof(float) * 2;
}
meshDecl.indexCount = (uint32_t)_mesh.getFaceIndicesTotal();
meshDecl.indexData = _mesh.getFaceIndices().data();
meshDecl.indexFormat = xatlas::IndexFormat::UInt32;
xatlas::AddMeshError::Enum error = xatlas::AddMesh(atlas, meshDecl, 1);
if (error != xatlas::AddMeshError::Success) {
xatlas::Destroy(atlas);
printf("\rError adding mesh '%s': %s\n", _mesh.getName().c_str(), xatlas::StringForEnum(error));
}
xatlas::Generate(atlas);
printf(" %d charts\n", atlas->chartCount);
printf(" %d atlases\n", atlas->atlasCount);
for (uint32_t i = 0; i < atlas->atlasCount; i++)
printf(" %d: %0.2f%% utilization\n", i, atlas->utilization[i] * 100.0f);
printf(" %ux%u resolution\n", atlas->width, atlas->height);
int totalVertices = 0;
int totalFaces = 0;
for (uint32_t i = 0; i < atlas->meshCount; i++) {
const xatlas::Mesh &mesh = atlas->meshes[i];
totalVertices += mesh.vertexCount;
totalFaces += mesh.indexCount / 3;
}
printf(" %u total vertices\n", totalVertices);
printf(" %u total triangles\n", totalFaces);
if (atlas->width > 0 &&
atlas->height > 0 &&
atlas->meshCount > 0) {
Mesh out;
const xatlas::Mesh &mesh = atlas->meshes[0];
for (uint32_t v = 0; v < mesh.vertexCount; v++) {
const xatlas::Vertex &vertex = mesh.vertexArray[v];
out.addVertex( _mesh.getVertex(vertex.xref) );
if (_mesh.haveNormals())
out.addNormal( _mesh.getNormal(vertex.xref) );
if (_mesh.haveColors() )
out.addColor( _mesh.getColor(vertex.xref) );
out.addTexCoord( vertex.uv[0] / atlas->width, vertex.uv[1] / atlas->height );
}
for (uint32_t f = 0; f < mesh.indexCount; f++) {
out.addFaceIndex(mesh.indexArray[f]);
}
_mesh = out;
}
}
}
| 32.043702 | 106 | 0.572563 | [
"mesh",
"vector",
"3d"
] |
40ff3a8dcc763c601c5a0157411cf853761efc7d | 4,895 | cpp | C++ | mandelbrot/worker.cpp | AlexeyShik/cpp-course-second-term | 359749722e63b0c1c1a0744a40faabd7e1225107 | [
"MIT"
] | null | null | null | mandelbrot/worker.cpp | AlexeyShik/cpp-course-second-term | 359749722e63b0c1c1a0744a40faabd7e1225107 | [
"MIT"
] | null | null | null | mandelbrot/worker.cpp | AlexeyShik/cpp-course-second-term | 359749722e63b0c1c1a0744a40faabd7e1225107 | [
"MIT"
] | null | null | null | #include "worker.h"
#include <complex>
#include <vector>
#include <algorithm>
const unsigned int worker::N_THREADS = std::thread::hardware_concurrency(); // hardware_concurrency() не constexpr, а жаль
void worker::calculate(size_t local_version) {
calculate_image(local_version, FIRST_PRECISION);
}
void worker::calculate_image(size_t local_version, size_t precision) {
std::unique_lock lock(mutex_);
bool first_iteration = precision == FIRST_PRECISION;
size_t h = img_ptr->height();
size_t w = img_ptr->width();
unsigned char *data = img_ptr->bits();
size_t stride = img_ptr->bytesPerLine();
if (!first_iteration) lock.unlock(); // first iteration always fast, hold lock all iteration
size_t block_size = (h / N_THREADS) - (h / N_THREADS) % precision;
size_t begin = id * block_size;
size_t end = id == N_THREADS - 1 ? h : std::min(h, (id + 1) * block_size);
for (size_t y = begin; y < end; y += precision) {
std::vector<unsigned char> line;
for (size_t y_ = y; y_ < end && y_ < y + precision; ++y_) {
std::vector<unsigned char> calculated_bits;
calculated_bits.resize(3 * w);
unsigned char *p = calculated_bits.data();
for (size_t x = 0; x < w; x += precision) {
if (!first_iteration) lock.lock();
if (local_version != version.load()) {
return;
}
unsigned char color;
if (y_ % precision == 0) {
color = static_cast<unsigned char>(value(x, y_, w, h, power) * 255);
line.push_back(color);
} else {
color = line[x / precision];
}
for (size_t x_ = x; x_ < w && x_ < x + precision; ++x_) {
if (color == 0.0) {
*p++ = 0.0;
*p++ = 0.0;
*p++ = 0.0;
} else {
*p++ = 80.0;
*p++ = color;
*p++ = 120.0;
}
}
if (!first_iteration) lock.unlock();
}
std::lock_guard<std::mutex> guard(*publish_mutex);
memcpy(data + y_ * stride, calculated_bits.data(), 3 * w * sizeof(char));
}
}
if (local_version != version.load()) {
return;
}
emit calculation_finished(img_ptr);
if (precision > 1) {
if (first_iteration) lock.unlock();
calculate_image(local_version, precision / STEP_PRECISION);
}
}
void worker::set_id(size_t id) {
this->id = id;
}
void worker::set_mutex(std::mutex *publish_mutex) {
this->publish_mutex = publish_mutex;
}
size_t worker::set_input(std::shared_ptr<QImage> img_ptr) {
std::lock_guard guard(mutex_);
this->img_ptr = img_ptr;
return ++version;
}
size_t worker::set_center_and_scale(double new_x, double new_y, double factor) {
std::lock_guard guard(mutex_);
double old_scale = scale;
scale *= factor;
double delta_x;
double delta_y;
size_t w = img_ptr->width();
size_t h = img_ptr->height();
if (factor <= 1) {
delta_x = new_x - w / 2;
delta_y = -(new_y - h / 2);
} else {
delta_x = -(new_x - w / 2);
delta_y = new_y - h / 2;
}
double delta_r = abs(hypot(delta_x, delta_y));
double cos_a = delta_x / delta_r;
double sin_a = delta_y / delta_r;
if (factor <= 1) {
x_center += delta_r * (1 - factor) * cos_a * old_scale;
y_center -= delta_r * (1 - factor) * sin_a * old_scale;
} else {
x_center -= delta_r * (1 - factor) * cos_a * old_scale;
y_center += delta_r * (1 - factor) * sin_a * old_scale;
}
return ++version;
}
size_t worker::move_center(double delta_x, double delta_y) {
std::lock_guard guard(mutex_);
x_center += delta_x * scale;
y_center += delta_y * scale;
return ++version;
}
size_t worker::set_power(double power) {
std::lock_guard guard(mutex_);
this->power = power;
return ++version;
}
size_t worker::reset() {
std::lock_guard guard(mutex_);
x_center = 0;
y_center = 0;
scale = 0.005;
return ++version;
}
void worker::cancel() {
std::lock_guard guard(mutex_);
++version;
}
double worker::value(int x, int y, int w, int h, double power) const {
std::complex<double> c(x - w / 2, y - h / 2);
c = c * scale + std::complex(x_center, y_center);
std::complex<double> z = 0;
size_t const MAX_STEPS = 100;
size_t step = 0;
for (;;) {
if (std::abs(z) >= 2.) {
double s = 1.0 * step / MAX_STEPS;
return (1 - s) * 200;
}
if (step == MAX_STEPS) {
return 0;
}
z = std::pow(z, power) + c;
++step;
}
}
| 29.847561 | 123 | 0.539326 | [
"vector"
] |
dc01e6d177d164796e5e9431f475beef6f9188e1 | 22,947 | cc | C++ | chrome/browser/media/media_engagement_contents_observer.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/media/media_engagement_contents_observer.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/media/media_engagement_contents_observer.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/media_engagement_contents_observer.h"
#include <memory>
#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "chrome/browser/media/media_engagement_preloaded_list.h"
#include "chrome/browser/media/media_engagement_service.h"
#include "chrome/browser/media/media_engagement_session.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/recently_audible_helper.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "media/base/media_switches.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/mojom/autoplay/autoplay.mojom.h"
#if !defined(OS_ANDROID)
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#endif // !defined(OS_ANDROID)
namespace {
void SendEngagementLevelToFrame(const url::Origin& origin,
content::RenderFrameHost* render_frame_host) {
mojo::AssociatedRemote<blink::mojom::AutoplayConfigurationClient> client;
render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&client);
client->AddAutoplayFlags(origin,
blink::mojom::kAutoplayFlagHighMediaEngagement);
}
} // namespace.
// This is the minimum size (in px) of each dimension that a media
// element has to be in order to be determined significant.
const gfx::Size MediaEngagementContentsObserver::kSignificantSize =
gfx::Size(200, 140);
const base::TimeDelta MediaEngagementContentsObserver::kMaxShortPlaybackTime =
base::TimeDelta::FromSeconds(3);
const char* const
MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName =
"Media.Engagement.ScoreAtPlayback";
const char* const MediaEngagementContentsObserver::
kHistogramSignificantNotAddedFirstTimeName =
"Media.Engagement.SignificantPlayers.PlayerNotAdded.FirstTime";
const char* const MediaEngagementContentsObserver::
kHistogramSignificantNotAddedAfterFirstTimeName =
"Media.Engagement.SignificantPlayers.PlayerNotAdded.AfterFirstTime";
const char* const
MediaEngagementContentsObserver::kHistogramSignificantRemovedName =
"Media.Engagement.SignificantPlayers.PlayerRemoved";
const int MediaEngagementContentsObserver::kMaxInsignificantPlaybackReason =
static_cast<int>(MediaEngagementContentsObserver::
InsignificantPlaybackReason::kReasonMax);
const base::TimeDelta
MediaEngagementContentsObserver::kSignificantMediaPlaybackTime =
base::TimeDelta::FromSeconds(7);
MediaEngagementContentsObserver::MediaEngagementContentsObserver(
content::WebContents* web_contents,
MediaEngagementService* service)
: WebContentsObserver(web_contents),
service_(service),
task_runner_(nullptr) {}
MediaEngagementContentsObserver::~MediaEngagementContentsObserver() = default;
MediaEngagementContentsObserver::PlaybackTimer::PlaybackTimer(
base::Clock* clock)
: clock_(clock) {}
void MediaEngagementContentsObserver::PlaybackTimer::Start() {
start_time_ = clock_->Now();
}
void MediaEngagementContentsObserver::PlaybackTimer::Stop() {
recorded_time_ = Elapsed();
start_time_.reset();
}
bool MediaEngagementContentsObserver::PlaybackTimer::IsRunning() const {
return start_time_.has_value();
}
base::TimeDelta MediaEngagementContentsObserver::PlaybackTimer::Elapsed()
const {
base::Time now = clock_->Now();
base::TimeDelta duration = now - start_time_.value_or(now);
return recorded_time_ + duration;
}
void MediaEngagementContentsObserver::PlaybackTimer::Reset() {
recorded_time_ = base::TimeDelta();
start_time_.reset();
}
void MediaEngagementContentsObserver::WebContentsDestroyed() {
RegisterAudiblePlayersWithSession();
session_ = nullptr;
ClearPlayerStates();
service_->contents_observers_.erase(web_contents());
delete this;
}
void MediaEngagementContentsObserver::ClearPlayerStates() {
playback_timer_.Stop();
player_states_.clear();
significant_players_.clear();
audio_context_players_.clear();
audio_context_timer_.Stop();
}
void MediaEngagementContentsObserver::RegisterAudiblePlayersWithSession() {
if (!session_)
return;
int32_t significant_players = 0;
int32_t audible_players = 0;
for (const auto& row : audible_players_) {
const PlayerState& player_state = GetPlayerState(row.first);
const base::TimeDelta elapsed = player_state.playback_timer->Elapsed();
if (elapsed < kMaxShortPlaybackTime && player_state.reached_end_of_stream) {
session_->RecordShortPlaybackIgnored(elapsed.InMilliseconds());
continue;
}
significant_players += row.second.first;
++audible_players;
}
session_->RegisterAudiblePlayers(audible_players, significant_players);
audible_players_.clear();
}
void MediaEngagementContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame() ||
!navigation_handle->HasCommitted() ||
navigation_handle->IsSameDocument() || navigation_handle->IsErrorPage()) {
return;
}
RegisterAudiblePlayersWithSession();
ClearPlayerStates();
url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL());
if (session_ && session_->IsSameOriginWith(new_origin))
return;
// Only get the opener if the navigation originated from a link.
// This is done outside of `GetOrCreateSession()` to simplify unit testing.
content::WebContents* opener = nullptr;
if (ui::PageTransitionCoreTypeIs(navigation_handle->GetPageTransition(),
ui::PAGE_TRANSITION_LINK) ||
ui::PageTransitionCoreTypeIs(navigation_handle->GetPageTransition(),
ui::PAGE_TRANSITION_RELOAD)) {
opener = GetOpener();
}
session_ = GetOrCreateSession(navigation_handle, opener);
}
MediaEngagementContentsObserver::PlayerState::PlayerState(base::Clock* clock)
: playback_timer(new PlaybackTimer(clock)) {}
MediaEngagementContentsObserver::PlayerState::~PlayerState() = default;
MediaEngagementContentsObserver::PlayerState::PlayerState(PlayerState&&) =
default;
MediaEngagementContentsObserver::PlayerState&
MediaEngagementContentsObserver::GetPlayerState(
const content::MediaPlayerId& id) {
auto state = player_states_.find(id);
if (state != player_states_.end())
return state->second;
auto iter =
player_states_.insert(std::make_pair(id, PlayerState(service_->clock_)));
return iter.first->second;
}
void MediaEngagementContentsObserver::MediaStartedPlaying(
const MediaPlayerInfo& media_player_info,
const content::MediaPlayerId& media_player_id) {
PlayerState& state = GetPlayerState(media_player_id);
state.playing = true;
state.has_audio = media_player_info.has_audio;
state.has_video = media_player_info.has_video;
// Reset the playback timer if we previously reached the end of the stream.
if (state.reached_end_of_stream) {
state.playback_timer->Reset();
state.reached_end_of_stream = false;
}
state.playback_timer->Start();
MaybeInsertRemoveSignificantPlayer(media_player_id);
UpdatePlayerTimer(media_player_id);
RecordEngagementScoreToHistogramAtPlayback(media_player_id);
}
void MediaEngagementContentsObserver::
RecordEngagementScoreToHistogramAtPlayback(
const content::MediaPlayerId& id) {
if (!session_)
return;
PlayerState& state = GetPlayerState(id);
if (!state.playing.value_or(false) || state.muted.value_or(true) ||
!state.has_audio.value_or(false) || !state.has_video.value_or(false) ||
state.score_recorded) {
return;
}
int percentage =
round(service_->GetEngagementScore(session_->origin()) * 100);
UMA_HISTOGRAM_PERCENTAGE(
MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName,
percentage);
state.score_recorded = true;
}
void MediaEngagementContentsObserver::MediaMutedStatusChanged(
const content::MediaPlayerId& id,
bool muted) {
GetPlayerState(id).muted = muted;
MaybeInsertRemoveSignificantPlayer(id);
UpdatePlayerTimer(id);
RecordEngagementScoreToHistogramAtPlayback(id);
}
void MediaEngagementContentsObserver::MediaResized(
const gfx::Size& size,
const content::MediaPlayerId& id) {
GetPlayerState(id).significant_size =
(size.width() >= kSignificantSize.width() &&
size.height() >= kSignificantSize.height());
MaybeInsertRemoveSignificantPlayer(id);
UpdatePlayerTimer(id);
}
void MediaEngagementContentsObserver::MediaDestroyed(
const content::MediaPlayerId& id) {
player_states_.erase(id);
audible_players_.erase(id);
significant_players_.erase(id);
}
void MediaEngagementContentsObserver::MediaStoppedPlaying(
const MediaPlayerInfo& media_player_info,
const content::MediaPlayerId& media_player_id,
WebContentsObserver::MediaStoppedReason reason) {
PlayerState& state = GetPlayerState(media_player_id);
state.playing = false;
state.reached_end_of_stream =
reason == WebContentsObserver::MediaStoppedReason::kReachedEndOfStream;
// Reset the playback timer if we finished playing.
state.playback_timer->Stop();
MaybeInsertRemoveSignificantPlayer(media_player_id);
UpdatePlayerTimer(media_player_id);
}
void MediaEngagementContentsObserver::AudioContextPlaybackStarted(
const AudioContextId& audio_context_id) {
audio_context_players_.insert(audio_context_id);
UpdateAudioContextTimer();
}
void MediaEngagementContentsObserver::AudioContextPlaybackStopped(
const AudioContextId& audio_context_id) {
audio_context_players_.erase(audio_context_id);
UpdateAudioContextTimer();
}
void MediaEngagementContentsObserver::DidUpdateAudioMutingState(bool muted) {
UpdatePageTimer();
UpdateAudioContextTimer();
}
std::vector<MediaEngagementContentsObserver::InsignificantPlaybackReason>
MediaEngagementContentsObserver::GetInsignificantPlayerReasons(
const PlayerState& state) {
std::vector<MediaEngagementContentsObserver::InsignificantPlaybackReason>
reasons;
if (state.muted.value_or(true)) {
reasons.push_back(MediaEngagementContentsObserver::
InsignificantPlaybackReason::kAudioMuted);
}
if (!state.playing.value_or(false)) {
reasons.push_back(MediaEngagementContentsObserver::
InsignificantPlaybackReason::kMediaPaused);
}
if (!state.significant_size.value_or(false) &&
state.has_video.value_or(false)) {
reasons.push_back(MediaEngagementContentsObserver::
InsignificantPlaybackReason::kFrameSizeTooSmall);
}
if (!state.has_audio.value_or(false)) {
reasons.push_back(MediaEngagementContentsObserver::
InsignificantPlaybackReason::kNoAudioTrack);
}
return reasons;
}
bool MediaEngagementContentsObserver::IsPlayerStateComplete(
const PlayerState& state) {
return state.muted.has_value() && state.playing.has_value() &&
state.has_audio.has_value() && state.has_video.has_value() &&
(!state.has_video.value_or(false) ||
state.significant_size.has_value());
}
void MediaEngagementContentsObserver::OnSignificantMediaPlaybackTimeForPlayer(
const content::MediaPlayerId& id) {
// Clear the timer.
auto audible_row = audible_players_.find(id);
audible_row->second.second = nullptr;
// Check that the tab is not muted.
auto* audible_helper = RecentlyAudibleHelper::FromWebContents(web_contents());
if (web_contents()->IsAudioMuted() || !audible_helper->WasRecentlyAudible())
return;
// Record significant audible playback.
audible_row->second.first = true;
}
void MediaEngagementContentsObserver::OnSignificantMediaPlaybackTimeForPage() {
DCHECK(session_);
if (session_->significant_media_element_playback_recorded())
return;
// Do not record significant playback if the tab did not make
// a sound recently.
auto* audible_helper = RecentlyAudibleHelper::FromWebContents(web_contents());
if (!audible_helper->WasRecentlyAudible())
return;
session_->RecordSignificantMediaElementPlayback();
}
void MediaEngagementContentsObserver::
OnSignificantAudioContextPlaybackTimeForPage() {
DCHECK(session_);
if (session_->significant_audio_context_playback_recorded())
return;
// Do not record significant playback if the tab did not make
// a sound recently.
auto* audible_helper = RecentlyAudibleHelper::FromWebContents(web_contents());
if (!audible_helper->WasRecentlyAudible())
return;
session_->RecordSignificantAudioContextPlayback();
}
void MediaEngagementContentsObserver::RecordInsignificantReasons(
std::vector<MediaEngagementContentsObserver::InsignificantPlaybackReason>
reasons,
const PlayerState& state,
MediaEngagementContentsObserver::InsignificantHistogram histogram) {
DCHECK(IsPlayerStateComplete(state));
std::string histogram_name;
switch (histogram) {
case MediaEngagementContentsObserver::InsignificantHistogram::
kPlayerRemoved:
histogram_name =
MediaEngagementContentsObserver::kHistogramSignificantRemovedName;
break;
case MediaEngagementContentsObserver::InsignificantHistogram::
kPlayerNotAddedFirstTime:
histogram_name = MediaEngagementContentsObserver::
kHistogramSignificantNotAddedFirstTimeName;
break;
case MediaEngagementContentsObserver::InsignificantHistogram::
kPlayerNotAddedAfterFirstTime:
histogram_name = MediaEngagementContentsObserver::
kHistogramSignificantNotAddedAfterFirstTimeName;
break;
default:
NOTREACHED();
break;
}
base::HistogramBase* base_histogram = base::LinearHistogram::FactoryGet(
histogram_name, 1,
MediaEngagementContentsObserver::kMaxInsignificantPlaybackReason,
MediaEngagementContentsObserver::kMaxInsignificantPlaybackReason + 1,
base::HistogramBase::kUmaTargetedHistogramFlag);
for (auto reason : reasons)
base_histogram->Add(static_cast<int>(reason));
base_histogram->Add(static_cast<int>(
MediaEngagementContentsObserver::InsignificantPlaybackReason::kCount));
}
void MediaEngagementContentsObserver::MaybeInsertRemoveSignificantPlayer(
const content::MediaPlayerId& id) {
// If we have not received the whole player state yet then we can't be
// significant and therefore we don't want to make a decision yet.
PlayerState& state = GetPlayerState(id);
if (!IsPlayerStateComplete(state))
return;
// If the player has an audio track, is un-muted and is playing then we should
// add it to the audible players map.
if (state.muted == false && state.playing == true &&
state.has_audio == true &&
audible_players_.find(id) == audible_players_.end()) {
audible_players_.emplace(id, std::make_pair(false, nullptr));
}
bool is_currently_significant =
significant_players_.find(id) != significant_players_.end();
std::vector<MediaEngagementContentsObserver::InsignificantPlaybackReason>
reasons = GetInsignificantPlayerReasons(state);
if (is_currently_significant) {
if (!reasons.empty()) {
// We are considered significant and we have reasons why we shouldn't
// be, so we should make the player not significant.
significant_players_.erase(id);
RecordInsignificantReasons(reasons, state,
MediaEngagementContentsObserver::
InsignificantHistogram::kPlayerRemoved);
}
} else {
if (reasons.empty()) {
// We are not considered significant but we don't have any reasons
// why we shouldn't be. Make the player significant.
significant_players_.insert(id);
} else if (state.reasons_recorded) {
RecordInsignificantReasons(
reasons, state,
MediaEngagementContentsObserver::InsignificantHistogram::
kPlayerNotAddedAfterFirstTime);
} else {
RecordInsignificantReasons(
reasons, state,
MediaEngagementContentsObserver::InsignificantHistogram::
kPlayerNotAddedFirstTime);
state.reasons_recorded = true;
}
}
}
void MediaEngagementContentsObserver::UpdatePlayerTimer(
const content::MediaPlayerId& id) {
UpdatePageTimer();
// The player should be considered audible.
auto audible_row = audible_players_.find(id);
if (audible_row == audible_players_.end())
return;
// If we meet all the reqirements for being significant then start a timer.
if (significant_players_.find(id) != significant_players_.end()) {
if (audible_row->second.second)
return;
auto new_timer = std::make_unique<base::OneShotTimer>();
if (task_runner_)
new_timer->SetTaskRunner(task_runner_);
new_timer->Start(
FROM_HERE,
MediaEngagementContentsObserver::kSignificantMediaPlaybackTime,
base::BindOnce(&MediaEngagementContentsObserver::
OnSignificantMediaPlaybackTimeForPlayer,
base::Unretained(this), id));
audible_row->second.second = std::move(new_timer);
} else if (audible_row->second.second) {
// We no longer meet the requirements so we should get rid of the timer.
audible_row->second.second = nullptr;
}
}
bool MediaEngagementContentsObserver::AreConditionsMet() const {
if (significant_players_.empty())
return false;
return !web_contents()->IsAudioMuted();
}
void MediaEngagementContentsObserver::UpdatePageTimer() {
if (!session_ || session_->significant_media_element_playback_recorded())
return;
if (AreConditionsMet()) {
if (playback_timer_.IsRunning())
return;
if (task_runner_)
playback_timer_.SetTaskRunner(task_runner_);
playback_timer_.Start(
FROM_HERE,
MediaEngagementContentsObserver::kSignificantMediaPlaybackTime,
base::BindOnce(&MediaEngagementContentsObserver::
OnSignificantMediaPlaybackTimeForPage,
base::Unretained(this)));
} else {
if (!playback_timer_.IsRunning())
return;
playback_timer_.Stop();
}
}
bool MediaEngagementContentsObserver::AreAudioContextConditionsMet() const {
if (!base::FeatureList::IsEnabled(media::kRecordWebAudioEngagement))
return false;
if (audio_context_players_.empty())
return false;
return !web_contents()->IsAudioMuted();
}
void MediaEngagementContentsObserver::UpdateAudioContextTimer() {
if (!session_ || session_->significant_audio_context_playback_recorded())
return;
if (AreAudioContextConditionsMet()) {
if (audio_context_timer_.IsRunning())
return;
if (task_runner_)
audio_context_timer_.SetTaskRunner(task_runner_);
audio_context_timer_.Start(
FROM_HERE,
MediaEngagementContentsObserver::kSignificantMediaPlaybackTime,
base::BindOnce(&MediaEngagementContentsObserver::
OnSignificantAudioContextPlaybackTimeForPage,
base::Unretained(this)));
} else if (audio_context_timer_.IsRunning()) {
audio_context_timer_.Stop();
}
}
void MediaEngagementContentsObserver::SetTaskRunnerForTest(
scoped_refptr<base::SequencedTaskRunner> task_runner) {
task_runner_ = std::move(task_runner);
}
void MediaEngagementContentsObserver::ReadyToCommitNavigation(
content::NavigationHandle* handle) {
// If the navigation is occuring in the main frame we should use the URL
// provided by |handle| as the navigation has not committed yet. If the
// navigation is in a sub frame then use the URL from the main frame.
url::Origin origin = url::Origin::Create(
handle->IsInMainFrame()
? handle->GetURL()
: handle->GetWebContents()->GetLastCommittedURL());
MediaEngagementScore score = service_->CreateEngagementScore(origin);
bool has_high_engagement = score.high_score();
if (base::FeatureList::IsEnabled(media::kMediaEngagementHTTPSOnly))
DCHECK(!has_high_engagement || (origin.scheme() == url::kHttpsScheme));
// If the preloaded feature flag is enabled and the number of visits is less
// than the number of visits required to have an MEI score we should check the
// global data.
if (!has_high_engagement &&
score.visits() < MediaEngagementScore::GetScoreMinVisits() &&
base::FeatureList::IsEnabled(media::kPreloadMediaEngagementData)) {
has_high_engagement =
MediaEngagementPreloadedList::GetInstance()->CheckOriginIsPresent(
origin);
}
// If we have high media engagement then we should send that to Blink.
if (has_high_engagement) {
SendEngagementLevelToFrame(url::Origin::Create(handle->GetURL()),
handle->GetRenderFrameHost());
}
}
content::WebContents* MediaEngagementContentsObserver::GetOpener() const {
#if !defined(OS_ANDROID)
for (auto* browser : *BrowserList::GetInstance()) {
if (browser->profile() != service_->profile())
continue;
int index =
browser->tab_strip_model()->GetIndexOfWebContents(web_contents());
if (index == TabStripModel::kNoTab)
continue;
// Whether or not the |opener| is null, this is the right tab strip.
return browser->tab_strip_model()->GetOpenerOfWebContentsAt(index);
}
#endif // !defined(OS_ANDROID)
return nullptr;
}
scoped_refptr<MediaEngagementSession>
MediaEngagementContentsObserver::GetOrCreateSession(
content::NavigationHandle* navigation_handle,
content::WebContents* opener) const {
url::Origin origin = url::Origin::Create(navigation_handle->GetURL());
if (origin.opaque())
return nullptr;
if (!service_->ShouldRecordEngagement(origin))
return nullptr;
MediaEngagementContentsObserver* opener_observer =
service_->GetContentsObserverFor(opener);
if (opener_observer && opener_observer->session_ &&
opener_observer->session_->IsSameOriginWith(origin)) {
return opener_observer->session_;
}
MediaEngagementSession::RestoreType restore_type =
navigation_handle->GetRestoreType() == content::RestoreType::kNotRestored
? MediaEngagementSession::RestoreType::kNotRestored
: MediaEngagementSession::RestoreType::kRestored;
return new MediaEngagementSession(
service_, origin, restore_type,
ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
ukm::SourceIdType::NAVIGATION_ID));
}
| 34.715582 | 96 | 0.741535 | [
"vector"
] |
dc068eb5f7eebe4460c20431c996b6877a83eb51 | 11,556 | cc | C++ | src/ray/gcs/gcs_server/actor_info_handler_impl.cc | Yeachan-Heo/ray | a73c488c74b1e01da3961db2eb538c43c29753f5 | [
"Apache-2.0"
] | 1 | 2020-11-14T19:25:41.000Z | 2020-11-14T19:25:41.000Z | src/ray/gcs/gcs_server/actor_info_handler_impl.cc | Yeachan-Heo/ray | a73c488c74b1e01da3961db2eb538c43c29753f5 | [
"Apache-2.0"
] | 2 | 2022-01-13T04:15:38.000Z | 2022-03-12T01:03:35.000Z | src/ray/gcs/gcs_server/actor_info_handler_impl.cc | Yeachan-Heo/ray | a73c488c74b1e01da3961db2eb538c43c29753f5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 The Ray Authors.
//
// 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 "actor_info_handler_impl.h"
#include "ray/util/logging.h"
namespace ray {
namespace rpc {
void DefaultActorInfoHandler::HandleCreateActor(
const ray::rpc::CreateActorRequest &request, ray::rpc::CreateActorReply *reply,
ray::rpc::SendReplyCallback send_reply_callback) {
RAY_CHECK(request.task_spec().type() == TaskType::ACTOR_CREATION_TASK);
auto actor_id =
ActorID::FromBinary(request.task_spec().actor_creation_task_spec().actor_id());
RAY_LOG(INFO) << "Registering actor, actor id = " << actor_id;
Status status = gcs_actor_manager_.RegisterActor(
request,
[reply, send_reply_callback, actor_id](std::shared_ptr<gcs::GcsActor> actor) {
RAY_LOG(INFO) << "Registered actor, actor id = " << actor_id;
GCS_RPC_SEND_REPLY(send_reply_callback, reply, Status::OK());
});
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to create actor: " << status.ToString();
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
}
}
void DefaultActorInfoHandler::HandleGetActorInfo(
const rpc::GetActorInfoRequest &request, rpc::GetActorInfoReply *reply,
rpc::SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.actor_id());
RAY_LOG(DEBUG) << "Getting actor info"
<< ", job id = " << actor_id.JobId() << ", actor id = " << actor_id;
auto on_done = [actor_id, reply, send_reply_callback](
const Status &status,
const boost::optional<ActorTableData> &result) {
if (result) {
reply->mutable_actor_table_data()->CopyFrom(*result);
}
RAY_LOG(DEBUG) << "Finished getting actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id << ", status = " << status;
GCS_RPC_SEND_REPLY(send_reply_callback, reply, Status::OK());
};
// Look up the actor_id in the GCS.
Status status = gcs_client_.Actors().AsyncGet(actor_id, on_done);
if (!status.ok()) {
on_done(status, boost::none);
}
}
void DefaultActorInfoHandler::HandleGetAllActorInfo(
const rpc::GetAllActorInfoRequest &request, rpc::GetAllActorInfoReply *reply,
rpc::SendReplyCallback send_reply_callback) {
RAY_LOG(DEBUG) << "Getting all actor info.";
auto on_done = [reply, send_reply_callback](const Status &status,
const std::vector<ActorTableData> &result) {
for (auto &it : result) {
reply->add_actor_table_data()->CopyFrom(it);
}
RAY_LOG(DEBUG) << "Finished getting all actor info.";
GCS_RPC_SEND_REPLY(send_reply_callback, reply, Status::OK());
};
Status status = gcs_client_.Actors().AsyncGetAll(on_done);
if (!status.ok()) {
on_done(status, std::vector<ActorTableData>());
}
}
void DefaultActorInfoHandler::HandleGetNamedActorInfo(
const rpc::GetNamedActorInfoRequest &request, rpc::GetNamedActorInfoReply *reply,
rpc::SendReplyCallback send_reply_callback) {
const std::string &name = request.name();
RAY_LOG(DEBUG) << "Getting actor info"
<< ", name = " << name;
auto on_done = [name, reply, send_reply_callback](
Status status, const boost::optional<ActorTableData> &result) {
if (status.ok()) {
if (result) {
reply->mutable_actor_table_data()->CopyFrom(*result);
}
} else {
RAY_LOG(ERROR) << "Failed to get actor info: " << status.ToString()
<< ", name = " << name;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
// Try to look up the actor ID for the named actor.
ActorID actor_id = gcs_actor_manager_.GetActorIDByName(name);
if (actor_id.IsNil()) {
// The named actor was not found.
std::stringstream stream;
stream << "Actor with name '" << name << "' was not found.";
on_done(Status::NotFound(stream.str()), boost::none);
} else {
// Look up the actor_id in the GCS.
Status status = gcs_client_.Actors().AsyncGet(actor_id, on_done);
if (!status.ok()) {
on_done(status, boost::none);
}
RAY_LOG(DEBUG) << "Finished getting actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
}
}
void DefaultActorInfoHandler::HandleRegisterActorInfo(
const rpc::RegisterActorInfoRequest &request, rpc::RegisterActorInfoReply *reply,
rpc::SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.actor_table_data().actor_id());
RAY_LOG(DEBUG) << "Registering actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
auto actor_table_data = std::make_shared<ActorTableData>();
actor_table_data->CopyFrom(request.actor_table_data());
auto on_done = [this, actor_id, actor_table_data, reply,
send_reply_callback](const Status &status) {
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to register actor info: " << status.ToString()
<< ", job id = " << actor_id.JobId() << ", actor id = " << actor_id;
} else {
RAY_CHECK_OK(gcs_pub_sub_->Publish(ACTOR_CHANNEL, actor_id.Hex(),
actor_table_data->SerializeAsString(), nullptr));
RAY_LOG(DEBUG) << "Finished registering actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
Status status = gcs_client_.Actors().AsyncRegister(actor_table_data, on_done);
if (!status.ok()) {
on_done(status);
}
}
void DefaultActorInfoHandler::HandleUpdateActorInfo(
const rpc::UpdateActorInfoRequest &request, rpc::UpdateActorInfoReply *reply,
rpc::SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.actor_id());
RAY_LOG(DEBUG) << "Updating actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
auto actor_table_data = std::make_shared<ActorTableData>();
actor_table_data->CopyFrom(request.actor_table_data());
auto on_done = [this, actor_id, actor_table_data, reply,
send_reply_callback](const Status &status) {
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to update actor info: " << status.ToString()
<< ", job id = " << actor_id.JobId() << ", actor id = " << actor_id;
} else {
RAY_CHECK_OK(gcs_pub_sub_->Publish(ACTOR_CHANNEL, actor_id.Hex(),
actor_table_data->SerializeAsString(), nullptr));
RAY_LOG(DEBUG) << "Finished updating actor info, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
Status status = gcs_client_.Actors().AsyncUpdate(actor_id, actor_table_data, on_done);
if (!status.ok()) {
on_done(status);
}
}
void DefaultActorInfoHandler::HandleAddActorCheckpoint(
const AddActorCheckpointRequest &request, AddActorCheckpointReply *reply,
SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.checkpoint_data().actor_id());
ActorCheckpointID checkpoint_id =
ActorCheckpointID::FromBinary(request.checkpoint_data().checkpoint_id());
RAY_LOG(DEBUG) << "Adding actor checkpoint, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id << ", checkpoint id = " << checkpoint_id;
auto actor_checkpoint_data = std::make_shared<ActorCheckpointData>();
actor_checkpoint_data->CopyFrom(request.checkpoint_data());
auto on_done = [actor_id, checkpoint_id, reply, send_reply_callback](Status status) {
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to add actor checkpoint: " << status.ToString()
<< ", job id = " << actor_id.JobId() << ", actor id = " << actor_id
<< ", checkpoint id = " << checkpoint_id;
} else {
RAY_LOG(DEBUG) << "Finished adding actor checkpoint, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id
<< ", checkpoint id = " << checkpoint_id;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
Status status = gcs_client_.Actors().AsyncAddCheckpoint(actor_checkpoint_data, on_done);
if (!status.ok()) {
on_done(status);
}
}
void DefaultActorInfoHandler::HandleGetActorCheckpoint(
const GetActorCheckpointRequest &request, GetActorCheckpointReply *reply,
SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.actor_id());
ActorCheckpointID checkpoint_id =
ActorCheckpointID::FromBinary(request.checkpoint_id());
RAY_LOG(DEBUG) << "Getting actor checkpoint, job id = " << actor_id.JobId()
<< ", checkpoint id = " << checkpoint_id;
auto on_done = [actor_id, checkpoint_id, reply, send_reply_callback](
const Status &status,
const boost::optional<ActorCheckpointData> &result) {
if (status.ok()) {
RAY_DCHECK(result);
reply->mutable_checkpoint_data()->CopyFrom(*result);
RAY_LOG(DEBUG) << "Finished getting actor checkpoint, job id = " << actor_id.JobId()
<< ", checkpoint id = " << checkpoint_id;
} else {
RAY_LOG(ERROR) << "Failed to get actor checkpoint: " << status.ToString()
<< ", job id = " << actor_id.JobId()
<< ", checkpoint id = " << checkpoint_id;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
Status status =
gcs_client_.Actors().AsyncGetCheckpoint(checkpoint_id, actor_id, on_done);
if (!status.ok()) {
on_done(status, boost::none);
}
}
void DefaultActorInfoHandler::HandleGetActorCheckpointID(
const GetActorCheckpointIDRequest &request, GetActorCheckpointIDReply *reply,
SendReplyCallback send_reply_callback) {
ActorID actor_id = ActorID::FromBinary(request.actor_id());
RAY_LOG(DEBUG) << "Getting actor checkpoint id, job id = " << actor_id.JobId()
<< ", actor id = " << actor_id;
auto on_done = [actor_id, reply, send_reply_callback](
const Status &status,
const boost::optional<ActorCheckpointIdData> &result) {
if (status.ok()) {
RAY_DCHECK(result);
reply->mutable_checkpoint_id_data()->CopyFrom(*result);
RAY_LOG(DEBUG) << "Finished getting actor checkpoint id, job id = "
<< actor_id.JobId() << ", actor id = " << actor_id;
} else {
RAY_LOG(ERROR) << "Failed to get actor checkpoint id: " << status.ToString()
<< ", job id = " << actor_id.JobId() << ", actor id = " << actor_id;
}
GCS_RPC_SEND_REPLY(send_reply_callback, reply, status);
};
Status status = gcs_client_.Actors().AsyncGetCheckpointID(actor_id, on_done);
if (!status.ok()) {
on_done(status, boost::none);
}
}
} // namespace rpc
} // namespace ray
| 42.959108 | 90 | 0.647283 | [
"vector"
] |
dc06ca1283d27ce2c99fd606330d3347f2789f5a | 19,221 | cpp | C++ | plugins/ExtendedKalmanFilterPlugin/src/base/noise/ProcessNoiseBase.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/ExtendedKalmanFilterPlugin/src/base/noise/ProcessNoiseBase.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/ExtendedKalmanFilterPlugin/src/base/noise/ProcessNoiseBase.cpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | //$Id$
//------------------------------------------------------------------------------
// ProcessNoiseBase
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Emergent Space Technologies, Inc. under
// contract number NNG15CR67C
//
// Author: John McGreevy, Emergent Space Technologies, Inc.
// Created: 2018/09/17
/**
* The base class for process noise models
*/
//------------------------------------------------------------------------------
#include "ProcessNoiseBase.hpp"
#include "NoiseException.hpp"
#include "CoordinateConverter.hpp"
#include "MessageInterface.hpp"
//#define DEBUG_CONVERSION
//---------------------------------
// static data
//---------------------------------
const std::string
ProcessNoiseBase::PARAMETER_TEXT[ProcessNoiseBaseParamCount - GmatBaseParamCount] =
{
"CoordinateSystem",
};
const Gmat::ParameterType
ProcessNoiseBase::PARAMETER_TYPE[ProcessNoiseBaseParamCount - GmatBaseParamCount] =
{
Gmat::OBJECT_TYPE, // CoordinateSystem
};
//------------------------------------------------------------------------------
// ProcessNoiseBase(const std::string &itsTypeName,
// const std::string &itsName)
//------------------------------------------------------------------------------
/**
* Constructor
*
* @param itsTypeName The type name of the new object
* @param itsName The name of the new object
* @param itsShortName The short name of the new object
*/
//------------------------------------------------------------------------------
ProcessNoiseBase::ProcessNoiseBase(const std::string &itsTypeName,
const std::string &itsName, const std::string &itsShortName) :
GmatBase (GmatType::GetTypeId("ProcessNoise"),itsTypeName,itsName),
shortName (itsShortName),
solarSystem (NULL),
needsReinit (false),
coordSysName ("EarthMJ2000Eq"),
coordinateSystem (NULL),
j2k (NULL),
refBody (NULL)
{
objectTypes.push_back(GmatType::GetTypeId("ProcessNoise"));
objectTypeNames.push_back("ProcessNoise");
parameterCount = ProcessNoiseBaseParamCount;
isInitialized = false;
}
//------------------------------------------------------------------------------
// ~ProcessNoiseBase()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
ProcessNoiseBase::~ProcessNoiseBase()
{
if (j2k)
delete j2k;
}
//------------------------------------------------------------------------------
// ProcessNoiseBase(const ProcessNoiseBase& pnm)
//------------------------------------------------------------------------------
/**
* Copy constructor
*/
//------------------------------------------------------------------------------
ProcessNoiseBase::ProcessNoiseBase(
const ProcessNoiseBase& pnm) :
GmatBase (pnm),
shortName (pnm.shortName),
solarSystem (pnm.solarSystem),
needsReinit (false),
coordSysName (pnm.coordSysName),
coordinateSystem (pnm.coordinateSystem),
j2k (NULL),
refBody (NULL)
{
isInitialized = false;
}
//------------------------------------------------------------------------------
// ProcessNoiseBase& operator=(const ProcessNoiseBase& pnm)
//------------------------------------------------------------------------------
/**
* Assignment operator
*/
//------------------------------------------------------------------------------
ProcessNoiseBase& ProcessNoiseBase::operator=(
const ProcessNoiseBase& pnm)
{
if (this != &pnm)
{
GmatBase::operator=(pnm);
shortName = pnm.shortName;
solarSystem = pnm.solarSystem;
isInitialized = false;
needsReinit = false;
coordSysName = pnm.coordSysName;
coordinateSystem = pnm.coordinateSystem;
j2k = NULL;
refBody = NULL;
}
return *this;
}
//------------------------------------------------------------------------------
// std::string GetShortName()
//------------------------------------------------------------------------------
/**
* Get the short name for the script field
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetShortName()
{
return shortName;
}
//---------------------------------------------------------------------------
// virtual void SetSolarSystem(SolarSystem *ss)
//---------------------------------------------------------------------------
/**
* Set the solar system for this object
*/
//------------------------------------------------------------------------------
void ProcessNoiseBase::SetSolarSystem(SolarSystem *ss)
{
solarSystem = ss;
}
//------------------------------------------------------------------------------
// void Initialize()
//------------------------------------------------------------------------------
/**
* Initialize the process noise object, including the coordinate systems
*/
//------------------------------------------------------------------------------
bool ProcessNoiseBase::Initialize()
{
if (isInitialized && !needsReinit) return true;
GmatBase::Initialize();
// Remove any old coordinate systems
if (j2k)
delete j2k;
if (!refBody)
throw NoiseException("Reference body not defined for process noise.");
SpacePoint *j2kBody = refBody->GetJ2000Body();
j2k = CoordinateSystem::CreateLocalCoordinateSystem("j2k", "MJ2000Eq", j2kBody, NULL, NULL, j2kBody, solarSystem);
isInitialized = true;
needsReinit = false;
return true;
}
//------------------------------------------------------------------------------
// void SetRefBody(SpacePoint* body)
//------------------------------------------------------------------------------
/**
* Set the reference body for the noise model
*/
//------------------------------------------------------------------------------
void ProcessNoiseBase::SetRefBody(SpacePoint* body)
{
refBody = body;
needsReinit = true;
}
//------------------------------------------------------------------------------
// void ConvertMatrix(Rmatrix &mat, const GmatTime &epoch)
//------------------------------------------------------------------------------
/**
* Convert the covariance matrix from the input frame to the inertial frame
* @param mat The covariance matrix to convert
* @param epoch The epoch to evaluate the process noise coordinate conversion at.
*/
//------------------------------------------------------------------------------
void ProcessNoiseBase::ConvertMatrix(Rmatrix &mat, const GmatTime &epoch)
{
#ifdef DEBUG_CONVERSION
MessageInterface::ShowMessage("Entering ProcessNoiseBase::ConvertMatrix()\n");
MessageInterface::ShowMessage(" Input matrix:\n");
for (UnsignedInt ii = 0U; ii < mat.GetNumRows(); ii++)
MessageInterface::ShowMessage(" [ %s ]\n", mat.ToRowString(ii, 6).c_str());
MessageInterface::ShowMessage("\n");
#endif
if (!isInitialized || needsReinit)
Initialize();
if (coordinateSystem == j2k)
{
#ifdef DEBUG_CONVERSION
MessageInterface::ShowMessage(" Input and output coordinate systems match, no transformation required.\n");
MessageInterface::ShowMessage("Exiting ProcessNoiseBase::ConvertMatrix()\n\n");
#endif
return; // No conversion needed
}
Integer stateSize = mat.GetNumRows();
CoordinateConverter cc;
Rvector inState(stateSize); // At origin of local coordinate system
Rvector outState(stateSize); // Placeholder, only the rotation matrix is needed
cc.Convert(epoch, inState, coordinateSystem, outState, j2k, true, false);
Rmatrix33 vnbRot = cc.GetLastRotationMatrix();
Rmatrix transform = Rmatrix::Identity(stateSize);
for (UnsignedInt ii = 0; ii < 3U; ii++)
{
for (UnsignedInt jj = 0; jj < 3U; jj++)
{
transform(ii, jj) = vnbRot(ii, jj);
transform(ii+3, jj+3) = vnbRot(ii, jj);
}
}
#ifdef DEBUG_CONVERSION
MessageInterface::ShowMessage(" Transformation matrix:\n");
for (UnsignedInt ii = 0U; ii < transform.GetNumRows(); ii++)
MessageInterface::ShowMessage(" [ %s ]\n", transform.ToRowString(ii, 6).c_str());
MessageInterface::ShowMessage("\n");
#endif
mat = transform*mat*transform.Transpose();
#ifdef DEBUG_CONVERSION
MessageInterface::ShowMessage(" Output matrix:\n");
for (UnsignedInt ii = 0U; ii < mat.GetNumRows(); ii++)
MessageInterface::ShowMessage(" [ %s ]\n", mat.ToRowString(ii, 6).c_str());
MessageInterface::ShowMessage("Exiting ProcessNoiseBase::ConvertMatrix()\n\n");
#endif
}
//------------------------------------------------------------------------------
// Gmat::ParameterType GetParameterType(const Integer id) const
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
Gmat::ParameterType ProcessNoiseBase::GetParameterType(const Integer id) const
{
if (id >= GmatBaseParamCount && id < ProcessNoiseBaseParamCount)
return PARAMETER_TYPE[id - GmatBaseParamCount];
else
return GmatBase::GetParameterType(id);
}
//------------------------------------------------------------------------------
// std::string GetParameterTypeString(const Integer id) const
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetParameterTypeString(const Integer id) const
{
if (id >= GmatBaseParamCount && id < ProcessNoiseBaseParamCount)
return GmatBase::PARAM_TYPE_STRING[GetParameterType(id)];
else
return GmatBase::GetParameterTypeString(id);
}
//------------------------------------------------------------------------------
// std::string GetParameterText(const Integer id)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetParameterText(const Integer id) const
{
if (id >= GmatBaseParamCount && id < ProcessNoiseBaseParamCount)
return PARAMETER_TEXT[id - GmatBaseParamCount];
else
return GmatBase::GetParameterText(id);
}
//------------------------------------------------------------------------------
// Integer GetParameterID(const std::string str)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
Integer ProcessNoiseBase::GetParameterID(const std::string &str) const
{
for (int i=GmatBaseParamCount; i<ProcessNoiseBaseParamCount; i++)
{
if (str == ProcessNoiseBase::PARAMETER_TEXT[i - GmatBaseParamCount])
return i;
}
return GmatBase::GetParameterID(str);
}
//------------------------------------------------------------------------------
// std::string GetStringParameter(const Integer id)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetStringParameter(const Integer id) const
{
switch (id)
{
case COORD_SYS:
return coordSysName;
default:
return GmatBase::GetStringParameter(id);
}
}
//------------------------------------------------------------------------------
// std::string GetStringParameter(const std::string &label)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetStringParameter(const std::string &label) const
{
return GetStringParameter(GetParameterID(label));
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const std::string &value)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
bool ProcessNoiseBase::SetStringParameter(const Integer id, const std::string &value)
{
switch (id)
{
case COORD_SYS:
coordSysName = value;
return true;
default:
return GmatBase::SetStringParameter(id, value);
}
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const std::string &label, const std::string &value)
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
bool ProcessNoiseBase::SetStringParameter(const std::string &label,
const std::string &value)
{
return SetStringParameter(GetParameterID(label), value);
}
//------------------------------------------------------------------------------
// std::string GetRefObjectName(const UnsignedInt type) const
//------------------------------------------------------------------------------
/**
* This method returns the name of the referenced objects.
*
* @param type The type of the reference object to return
*
* @return name of the reference object of the requested type.
*/
//------------------------------------------------------------------------------
std::string ProcessNoiseBase::GetRefObjectName(const UnsignedInt type) const
{
if (type == Gmat::COORDINATE_SYSTEM)
return coordSysName;
return GmatBase::GetRefObjectName(type);
}
//------------------------------------------------------------------------------
// virtual bool HasRefObjectTypeArray()
//------------------------------------------------------------------------------
/**
* @see GmatBase
*/
//------------------------------------------------------------------------------
bool ProcessNoiseBase::HasRefObjectTypeArray()
{
return true;
}
//------------------------------------------------------------------------------
// const ObjectTypeArray& GetRefObjectTypeArray()
//------------------------------------------------------------------------------
/**
* Retrieves the list of ref object types used by this class.
*
* @return the list of object types.
*
*/
//------------------------------------------------------------------------------
const ObjectTypeArray& ProcessNoiseBase::GetRefObjectTypeArray()
{
refObjectTypes.clear();
refObjectTypes.push_back(Gmat::COORDINATE_SYSTEM);
return refObjectTypes;
}
//------------------------------------------------------------------------------
// const StringArray& GetRefObjectNameArray(const UnsignedInt type)
//---------------------------------------------------------------------------
/**
* Returns the names of the reference object. (Derived classes should implement
* this as needed.)
*
* @param <type> reference object type.
*
* @return The names of the reference object.
*/
//------------------------------------------------------------------------------
const StringArray& ProcessNoiseBase::GetRefObjectNameArray(const UnsignedInt type)
{
refObjectNames.clear();
if (type == Gmat::UNKNOWN_OBJECT || type == Gmat::COORDINATE_SYSTEM)
refObjectNames.push_back(coordSysName);
return refObjectNames;
}
//---------------------------------------------------------------------------
// GmatBase* GetRefObject(const UnsignedInt type, const std::string &name)
//---------------------------------------------------------------------------
/**
* Returns the reference object pointer.
*
* @param type type of the reference object.
* @param name name of the reference object.
*
* @return reference object pointer.
*/
//---------------------------------------------------------------------------
GmatBase* ProcessNoiseBase::GetRefObject(const UnsignedInt type,
const std::string &name)
{
if (type == Gmat::COORDINATE_SYSTEM)
return coordinateSystem;
return GmatBase::GetRefObject(type, name);
}
//------------------------------------------------------------------------------
// bool SetRefObject(GmatBase *obj, const UnsignedInt type,
// const std::string &name)
//------------------------------------------------------------------------------
/**
* This method sets a reference object for the CoordinateSystem class.
*
* @param obj pointer to the reference object
* @param type type of the reference object
* @param name name of the reference object
*
* @return true if successful; otherwise, false.
*
*/
//------------------------------------------------------------------------------
bool ProcessNoiseBase::SetRefObject(GmatBase *obj, const UnsignedInt type,
const std::string &name)
{
switch (type)
{
case Gmat::COORDINATE_SYSTEM:
{
if (coordSysName == name)
coordinateSystem = (CoordinateSystem*)obj;
return true;
}
default:
return GmatBase::SetRefObject(obj, type, name);
}
}
//---------------------------------------------------------------------------
// bool RenameRefObject(const UnsignedInt type,
// const std::string &oldName, const std::string &newName)
//---------------------------------------------------------------------------
/**
* Renames reference object name used in this class.
*
* @param <type> reference object type.
* @param <oldName> object name to be renamed.
* @param <newName> new object name.
*
* @return true if object name changed, false if not.
*/
//---------------------------------------------------------------------------
bool ProcessNoiseBase::RenameRefObject(const UnsignedInt type,
const std::string &oldName,
const std::string &newName)
{
if (type == Gmat::COORDINATE_SYSTEM)
{
if (coordSysName == oldName)
coordSysName = newName;
}
return true;
}
| 33.369792 | 118 | 0.467093 | [
"object",
"model",
"transform"
] |
dc06ebd674905a7ad99dd7123033fe2c2750254c | 3,260 | cc | C++ | pmlc/dialect/pxa/transforms/tile_accumulate.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/pxa/transforms/tile_accumulate.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/pxa/transforms/tile_accumulate.cc | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Intel Corporation
#include "pmlc/dialect/pxa/transforms/tile_accumulate.h"
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "mlir/Analysis/AffineStructures.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/DebugStringHelper.h"
#include "pmlc/dialect/pxa/analysis/strides.h"
#include "pmlc/dialect/pxa/analysis/uses.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/pxa/transforms/pass_detail.h"
#include "pmlc/dialect/pxa/transforms/tile.h"
#include "pmlc/util/logging.h"
using namespace mlir; // NOLINT
namespace pmlc::dialect::pxa {
AffineParallelOp tileAccumulations(AffineParallelOp op, bool skipTrivial) {
// Find the originating write and its StrideInfo
Optional<StrideInfo> maybeStrideInfo;
if (op.getNumResults() == 1) {
auto srcDef = getPrevWriter(op.getResult(0));
if (auto gemmOp = dyn_cast_or_null<PxaGemmOp>(srcDef)) {
maybeStrideInfo =
computeStrideInfo(gemmOp.out().getType().cast<MemRefType>(),
gemmOp.cAccessMap(), gemmOp.getOperandsForC());
} else if (auto reduceOp = dyn_cast_or_null<PxaReduceOp>(srcDef)) {
maybeStrideInfo = computeStrideInfo(reduceOp);
}
}
// If we can't fall back to adding a nesting level (to guarentee all
// accumulations are in the 'inner' loop)
if (!maybeStrideInfo) {
auto maybeRanges = op.getConstantRanges();
assert(maybeRanges &&
"Cannot tile accumulations on dynamic sized paralllel for");
if (!skipTrivial) {
op = performTiling(op, *maybeRanges);
}
return op;
}
auto si = *maybeStrideInfo;
// Get strides for output
// Find all the accumulation indexes (stride 0 with respect to output) and
// tile them into an inner block
auto ranges = *op.getConstantRanges();
SmallVector<int64_t, 6> accumTile;
auto steps = op.getSteps();
// Track if both inner + outer loops would be used
bool anyAccum = false;
bool anyNonAccum = false;
for (size_t i = 0; i < ranges.size(); i++) {
auto arg = op.getIVs()[i];
if (si.strides.count(arg)) {
// Output non-stationary, outer loop
anyNonAccum = true;
accumTile.push_back(steps[i]);
} else {
// Output stationary, accumulate in inner loop
anyAccum = true;
accumTile.push_back(ranges[i]);
}
}
// Check if both loops were used
bool nonTrivial = anyAccum && anyNonAccum;
// Tile if needed or if we always want fixed depth
if (nonTrivial || !skipTrivial) {
op = performTiling(op, accumTile);
}
return op;
}
namespace {
struct TileAccumulatePass : public TileAccumulateBase<TileAccumulatePass> {
void runOnFunction() final {
auto func = getFunction();
// Tile only the outermost loops
for (auto op : func.getBody().getOps<AffineParallelOp>()) {
if (!op.getConstantRanges()) {
signalPassFailure();
break;
}
tileAccumulations(op, false);
}
}
};
} // namespace
std::unique_ptr<Pass> createTileAccumulatePass() {
return std::make_unique<TileAccumulatePass>();
}
} // namespace pmlc::dialect::pxa.
| 30.46729 | 76 | 0.68681 | [
"vector"
] |
dc07c43ecfc9981c95073af676f5cb90fd01d474 | 6,098 | cpp | C++ | 3rd/xcslib/utility/mm2.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 4 | 2021-02-20T15:59:42.000Z | 2022-03-25T04:04:21.000Z | 3rd/xcslib/utility/mm2.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 1 | 2021-04-14T04:12:48.000Z | 2021-04-14T04:12:48.000Z | 3rd/xcslib/utility/mm2.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 2 | 2019-10-29T12:41:16.000Z | 2021-03-22T16:38:27.000Z | /*
* The XCS Library
* A C++ framework to apply and develop learning classifier systems
* Copyright (C) 2002-2009 Pier Luca Lanzi
*
* Pier Luca Lanzi
* Dipartimento di Elettronica e Informazione
* Politecnico di Milano
* Piazza Leonardo da Vinci 32
* I-20133 MILANO - ITALY
* pierluca.lanzi@polimi.it/lanzi@elet.polimi.it
*
* This file is part of the XCSLIB library.
*
* xcslib 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.
*
* xcslib 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.
*
* A copy of the license is available at http://www.gnu.org/licenses/gpl.html
*
* If you use this code, please cite the following technical report:
*
* P.L. Lanzi and D. Loiacono (2009), "XCSLib: The XCS Classifier System Library",
* Technical Report No. 2009005, Illinois Genetic Algorithms Laboratory
* University of Illinois at Urbana-Champaign, 117 Transportation Building
* 104 S. Mathews Avenue Urbana, IL 61801
*
* Available at http://www.illigal.uiuc.edu/pub/papers/IlliGALs/2009005.pdf
*
* For updates please visit: http://xcslib.sf.net
* http://www.pierlucalanzi.net
*/
//-------------------------------------------------------------------------
// Filename : mm2.cc
//
// Purpose : take a set of files containing real numbers which
// represent the plot of a certain variable and produce
// an output file containing the average of all the input plots
//
// Special Notes :
//
//
// Creator : Pier Luca Lanzi
//
// Creation Date : 2004/09/22
//
// Current Owner : Pier Luca Lanzi
//
//-------------------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
int mm2(int argc, char* argv[])
{
if (argc<4)
{
cout << endl;
cout << "USAGE: mm <columns> <output file> <input files>" << endl;
cout << endl;
cout << endl;
return 0;
}
unsigned long no_columns = atoi(argv[1]); //! number of columns
char* str_fn_output = argv[2]; //! output file
unsigned long first_file = 3; //! index to the first file
unsigned long no_files = argc-first_file; //! number of files
cerr << "NUMBER OF COLUMNS: " << no_columns << endl;
cerr << "OUTPUT FILE: " << str_fn_output << endl;
cerr << "NUMBER OF FILES " << no_files << endl;
cerr << "FILES:" << endl;
for(unsigned long cf=first_file; cf<argc; cf++)
{
cerr << "\t" << cf-first_file << "\t" << argv[cf] << endl;
}
vector<double> abscissa; //! abscissa
vector<double> avg; //! vettore utilizzato per contenere medie
vector<double> sq; //! sum of squares used for standard deviation
double elem; // per lettura elemento
int index; // scandisce files da processare
int count; // conta il numero di elementi nel file
int countMax; // conta il numero di elementi massimo dei files
int countMin; // conta il numero di elementi minimo dei files
char fileName[256]; // nome del file da processare
//! inizializzazione
countMax = -1; //! maximum no elements
countMin = -1; //! minimum no elements
//! \var cf current file processed
for (int cf=first_file; cf<argc; cf++)
{
ifstream IN(argv[cf]);
if (!IN)
{
cerr << "\ainput file " << fileName;
cerr << " not opened" << endl;
exit(1);
}
count=0;
if (no_columns==1)
{
while (IN>>elem)
{
if (count>countMax)
{
//! new element
avg.push_back(elem);
sq.push_back(elem*elem);
countMax++;
} else {
//! update avg and sq
avg[count]+=elem;
sq[count]+=elem*elem;
};
count++;
};
} else {
double x;
while (IN>>x>>elem)
{
if (count>countMax)
{
//! new element
abscissa.push_back(x);
avg.push_back(elem);
sq.push_back(elem*elem);
countMax++;
} else {
//! update avg and sq
if (abscissa[count]!=x)
{
cerr << "FILE: \t" << argv[cf] << endl;
cerr << "LINE: \t" << count << endl;
cerr << "ERROR:\t" << x << "does not appear in previous files" << endl;
cerr << endl;
exit(-1);
}
avg[count]+=elem;
sq[count]+=elem*elem;
};
count++;
};
}
//! count was set to the next free line
//! now count is set to the actual number of lines
count--;
//! update countMin
if ((countMin<0) || (count<countMin))
{
countMin=count;
};
};
cerr << "LINES : " << count << endl;
cerr << "MAX LINES : " << countMin << endl;
cerr << "MIN LINES : " << countMax << endl;
ofstream OUT(str_fn_output);
if (!OUT)
{
cerr << "FILE: \t" << str_fn_output << endl;
//cerr << "LINE: \t" << __line__ << endl;
cerr << "ERROR:\t" << "not opened" << endl;
cerr << endl;
exit(-1);
};
cout << "NO FILES " << no_files << endl;
for (unsigned long el=0; el<=countMin; el++)
{
if (no_columns==2)
{
OUT << abscissa[el] << "\t";
}
//! average
float average = avg[el]/double(no_files);
OUT << average;
//! variance
double var = max(double(0),double((sq[el]/double(no_files))-(average*average)));
//! standard deviation
double sd = sqrt(var);
//! standard error
//cout << "NO FILES " << no_files << "\t" << double(no_files) << sqrt(double(no_files)) << endl;
//cout << "SD = " << sd << endl;
double se = sd/sqrt(double(no_files));
//! output the standard error
OUT << "\t" << se;
//! standard error
OUT << endl;
}
OUT.close();
}
| 27.102222 | 98 | 0.574779 | [
"vector"
] |
dc11e802dae74ea80e46efdd85412db4c420207e | 915 | cpp | C++ | #1024 Palindromic Number.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | 1 | 2021-12-26T08:34:47.000Z | 2021-12-26T08:34:47.000Z | #1024 Palindromic Number.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | null | null | null | #1024 Palindromic Number.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
unsigned s = 0, step;
vector<unsigned> ori, rev;
for(char temp = getchar(); temp != ' '; temp = getchar()) ori.push_back(temp - '0');
scanf("%u", &step);
for(unsigned carry, temp; s < step; ++s) {
rev = ori; carry = 0;
reverse(rev.begin(), rev.end());
if(rev == ori) break;
for(size_t i = 0; i < ori.size(); ++i) {
temp = ori[i] + rev[i] + carry;
ori[i] = temp % 10;
carry = temp / 10;
}
if(carry != 0) ori.push_back(carry);
}
for(auto it = ori.rbegin(); it != ori.rend(); ++it) printf("%u", *it);
printf("\n%u\n", s);
return 0;
}
/*
67 3
484
2
69 3
s = 0
ori: 6 9, rev: 9 6
ori: 5 6 1
output: 165
s = 1
ori: 5 6 1, rev: 1 6 5
ori: 6 2 7
output
s = 2
ori: 6 2 7, rev: 7 2 6
ori: 3 5 3 1
1353
3
*/ | 18.673469 | 88 | 0.503825 | [
"vector"
] |
dc146c291d32961b665fef7c19eff5b93d4b11bc | 14,885 | cpp | C++ | game_engine/src/gui.cpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | 14 | 2017-06-01T16:00:25.000Z | 2021-12-01T16:02:00.000Z | game_engine/src/gui.cpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | null | null | null | game_engine/src/gui.cpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | 4 | 2017-10-04T22:51:44.000Z | 2021-03-18T10:16:02.000Z | // Endless Online Awaken
#include "gui.hpp"
#include "util.hpp"
#include "config.hpp"
#include "game_state.hpp"
#include "client.hpp"
#include "map_editor.hpp"
#include "map.hpp"
#include <imgui.h>
#include "imgui_impl_a5.h"
#include <iostream>
bool GUI::initialized_ = false;
GUI::State GUI::state;
unsigned int GUI::bg;
std::string GUI::open_popup;
std::string GUI::popup_message;
int GUI::input_focus;
bool GUI::clear_gfx;
bool Chat::initialized_ = false;
std::vector<std::pair<std::string, std::string>> Chat::messages;
bool Chat::new_message;
GUI::GUI()
{
if(!this->initialized_)
{
this->state = GUI::State::MainMenu;
this->bg = 0;
this->open_popup = "";
this->popup_message = "";
this->input_focus = 0;
this->clear_gfx = false;
this->SetState(State::MainMenu);
this->initialized_ = true;
}
}
void GUI::Process()
{
bool show_test_window = false;
if(this->state == State::MainMenu)
{
this->MainMenu();
}
else if(this->state == State::Editor)
{
MapEditor().MakeGUI();
}
else if(this->state == State::CreateAccount)
{
this->CreateAccount();
}
else if(this->state == State::Credits)
{
this->Credits();
}
else if(this->state == State::CharacterList)
{
this->CharacterList();
}
else if(this->state == State::CreateCharacter)
{
this->CreateCharacter();
}
else if(this->state == State::Playing)
{
this->Playing();
}
if (show_test_window)
{
ImGui::SetNextWindowPos(ImVec2(20, 10));
ImGui::ShowTestWindow(&show_test_window);
}
if(!this->open_popup.empty())
{
ImGui::OpenPopup(this->open_popup.c_str());
this->open_popup.clear();
}
ImGuiWindowFlags flags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize;
if(ImGui::BeginPopupModal("Disconnected", NULL, flags))
{
ImGui::Text("Connection with the game server has been lost.");
if(ImGui::Button("OK"))
{
this->SetState(State::MainMenu);
GameState().Set(GameState::State::MainMenu);
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if(ImGui::BeginPopupModal("Connection error", NULL, flags))
{
ImGui::Text("Could not connect to the game server.");
if(ImGui::Button("OK"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if(ImGui::BeginPopupModal("Account created", NULL, flags))
{
ImGui::Text("Account created! Now you can log into the game.");
if(ImGui::Button("OK"))
{
this->SetState(State::MainMenu);
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if(ImGui::BeginPopupModal("Character created", NULL, flags))
{
ImGui::Text("Character created!");
if(ImGui::Button("OK"))
{
this->SetState(State::CharacterList);
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if(ImGui::BeginPopupModal("Server answer", NULL, flags))
{
ImGui::Text(this->popup_message.c_str());
if(ImGui::Button("OK"))
{
this->popup_message.clear();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void GUI::Render()
{
bool draw_bg = this->state == State::MainMenu || this->state == State::CreateAccount || this->state == State::CharacterList
|| this->state == State::Credits || this->state == State::CreateCharacter;
if(draw_bg)
{
ALLEGRO_BITMAP *bg = GFXLoader().GetBitmap(1, this->bg);
if(bg != NULL) al_draw_bitmap(bg, 0, 0, 0);
}
if(this->state == State::Playing)
{
ALLEGRO_BITMAP *bg = GFXLoader().GetBitmap(2, 1);
if(bg != NULL) al_draw_bitmap(bg, 0, 0, 0);
}
ImGui::Render();
if(this->clear_gfx)
{
GFXLoader().Clear();
this->clear_gfx = false;
}
}
void GUI::SetState(State state)
{
this->clear_gfx = true;
if(state == State::MainMenu)
{
this->bg = RandGen().RandInt(30, 36);
}
if(state == State::Editor && Client().character == 0)
{
Character *character = new Character("Artist", 1, 1, 1);
character->speed = 18;
Map().characters.push_back(std::shared_ptr<Character>(character));
Client().character = character;
}
this->state = state;
}
GUI::State GUI::GetState()
{
return this->state;
}
void GUI::OpenPopup(std::string id, std::string message)
{
this->open_popup = id;
this->popup_message = message;
}
void GUI::SetFocus(int widget)
{
this->input_focus = widget;
}
void GUI::MainMenu()
{
static bool show_login = false;
Config config;
ImGuiWindowFlags flags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::SetNextWindowPos(ImVec2(20.f, 200.f));
if(!ImGui::Begin("Main menu", NULL, flags))
{
ImGui::End();
return;
}
std::string action = "";
if(ImGui::Button("Create account"))
{
action = "create account";
}
if(ImGui::Button("Play game"))
{
action = "play game";
}
if(ImGui::Button("Credits"))
{
action = "credits";
}
if(ImGui::Button("Exit"))
{
GameState().Set(GameState::State::Exit);
}
if(action == "create account")
{
Client client;
if(!client.Connected())
{
if(!client.Connect(config.GetValue("Address"), std::atoi(config.GetValue("Port").c_str())))
this->OpenPopup("Connection error");
}
if(client.Connected())
{
this->SetState(State::CreateAccount);
this->SetFocus(1);
}
}
if(action == "play game")
{
Client client;
if(!client.Connected())
{
if(!client.Connect(config.GetValue("Address"), std::atoi(config.GetValue("Port").c_str())))
this->OpenPopup("Connection error");
}
if(client.Connected())
{
show_login = true;
this->SetFocus(1);
}
}
if(action == "credits")
{
this->SetState(State::Credits);
}
if(show_login)
{
this->Login(&show_login);
}
ImGui::End();
}
void GUI::CreateAccount()
{
static char acc_name[16], password[12], password_again[12], real_name[64], location[64], email[64];
Config config;
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::SetNextWindowPos(ImVec2(220.0f, 200.0f), ImGuiCond_FirstUseEver);
ImGui::Begin("Create account", 0, flags);
if(this->input_focus == 1)
{
ImGui::SetKeyboardFocusHere();
this->input_focus = 0;
}
ImGui::InputText("Account name", acc_name, IM_ARRAYSIZE(acc_name));
ImGui::InputText("Password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui::InputText("Password again", password_again, IM_ARRAYSIZE(password_again), ImGuiInputTextFlags_Password);
ImGui::InputText("Real name", real_name, IM_ARRAYSIZE(real_name));
ImGui::InputText("Location", location, IM_ARRAYSIZE(location));
bool do_create = false;
if(ImGui::InputText("Email address", email, IM_ARRAYSIZE(email), ImGuiInputTextFlags_EnterReturnsTrue))
{
do_create = true;
}
if(ImGui::Button("Create"))
{
do_create = true;
}
if(ImGui::Button("Cancel"))
{
this->SetState(State::MainMenu);
}
if(do_create)
{
Client client;
if(!client.Connected())
{
if(!client.Connect(config.GetValue("Address"), std::atoi(config.GetValue("Port").c_str())))
this->OpenPopup("Connection error");
}
if(client.Connected())
{
std::cout << "CLICK" << std::endl;
std::array<std::string, 5> input_data;
input_data[0] = acc_name;
input_data[1] = password;
input_data[2] = real_name;
input_data[3] = location;
input_data[4] = email;
client.CreateAccount(input_data);
}
}
ImGui::End();
}
void GUI::Login(bool *p_open)
{
static char username[32];
static char password[16];
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::SetNextWindowPos(ImVec2(220.0f, 200.0f), ImGuiCond_FirstUseEver);
ImGui::Begin("Login", p_open, flags);
if(this->input_focus == 1)
{
ImGui::SetKeyboardFocusHere();
this->input_focus = 0;
}
ImGui::InputText("Username", username, IM_ARRAYSIZE(username));
ImGuiInputTextFlags input_flags = ImGuiInputTextFlags_Password | ImGuiInputTextFlags_EnterReturnsTrue;
bool do_login = false;
if(ImGui::InputText("Password", password, IM_ARRAYSIZE(password), input_flags))
{
do_login = true;
}
if(ImGui::Button("Login"))
{
do_login = true;
}
if(do_login)
{
std::string usr = username;
std::string pass = password;
Client client;
if(!client.Connected())
{
if(!client.Connect(Config().GetValue("Address"), 8078))
{
this->OpenPopup("Connection error");
}
}
if(client.Connected())
{
if(!usr.empty() && !pass.empty()) Client().Login(usr, pass);
}
}
ImGui::End();
}
void GUI::Credits()
{
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::SetNextWindowPos(ImVec2(220.0f, 200.0f), ImGuiCond_FirstUseEver);
ImGui::Begin("Credits", 0, flags);
ImGui::Text("---------");
ImGui::Text("Code:");
ImGui::Text("Jimmyee");
ImGui::Text("---------");
if(ImGui::Button("OK"))
{
this->SetState(State::MainMenu);
}
ImGui::End();
}
void GUI::CharacterList()
{
Client client;
GFXLoader gfx_loader;
Map map;
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::Begin("Character list", NULL, flags);
ALLEGRO_BITMAP *bitmap = NULL;
int gfx_offset[2] = { 1, 2 };
static std::string name = "";
for(std::size_t i = 0; i < client.characters.size(); ++i)
{
ImGui::Text(client.characters[i]->name.c_str());
bitmap = gfx_loader.GetBitmap(8, gfx_offset[(int)client.characters[i]->gender], true, ".png");
int frame_w = 48;
int frame_h = 84;
ImVec2 uv0 = ImVec2(0, 0);
ImVec2 uv1 = ImVec2(0.25, 1.0/5);
ImGui::Image(bitmap, ImVec2(frame_w, frame_h), uv0, uv1, ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128));
ImGui::PushID(i);
if(ImGui::Button("Login"))
{
client.SelectCharacter(client.characters[i]->name);
}
ImGui::PopID();
ImGui::SameLine();
bool delete_char = false;
ImGui::PushID(i);
if(ImGui::Button("Delete"))
{
delete_char = true;
}
ImGui::PopID();
if(delete_char)
{
ImGui::OpenPopup("Delete character");
name = client.characters[i]->name;
}
}
flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove;
if(ImGui::BeginPopupModal("Delete character", NULL, flags))
{
ImGui::Text("Are you sure?");
if(ImGui::Button("Yes"))
{
client.DeleteCharacter(name);
ImGui::CloseCurrentPopup();
}
if(ImGui::Button("No"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if(ImGui::Button("Create"))
{
this->SetState(State::CreateCharacter);
}
ImGui::SameLine();
if(ImGui::Button("Logout"))
{
Client().Disconnect();
this->SetState(State::MainMenu);
}
ImGui::End();
}
void GUI::CreateCharacter()
{
Client client;
static char name[12] = "";
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
ImGui::Begin("Create character", 0, flags);
ImGui::InputText("Name", name, IM_ARRAYSIZE(name));
ImGui::Text("Gender:");
static int i = 0;
ImGui::RadioButton("Female", &i, 0); ImGui::SameLine();
ImGui::RadioButton("Male", &i, 1);
if(ImGui::Button("Create"))
{
client.CreateCharacter(name, (Gender)i);
}
if(ImGui::Button("Cancel"))
{
this->SetState(State::CharacterList);
}
ImGui::End();
}
void GUI::Playing()
{
Client client;
ImGuiWindowFlags flags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar;
ImGui::SetNextWindowPos(ImVec2(10, 308));
ImGui::SetNextWindowSize(ImVec2(620, 162));
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
ImGui::Begin("Game Panel", 0, flags);
this->ChatBox();
ImGui::End();
ImGui::PopStyleColor();
}
void GUI::ChatBox()
{
Chat chat;
static char chat_input[255] = "";
if(this->input_focus == 1)
{
ImGui::SetKeyboardFocusHere();
this->input_focus = 0;
}
ImGui::SetCursorPos(ImVec2(116, 0));
ImGui::PushItemWidth(454);
ImGuiInputTextFlags it_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AlwaysInsertMode;
std::string message = chat_input;
if(ImGui::InputText("", chat_input, IM_ARRAYSIZE(chat_input), it_flags))
{
if(!message.empty())
{
Client().character->Talk(0, message);
Client().Talk(0, message);
strcpy(chat_input, "");
}
this->SetFocus(1);
}
ImGui::PopItemWidth();
ImGui::SetCursorPos(ImVec2(92, 22));
ImGui::BeginChildFrame(0, ImVec2(484, 118), 0);
ImGui::PushTextWrapPos(470);
for(auto &it : chat.messages)
{
std::string name = std::get<0>(it);
name[0] = std::toupper(name[0]);
name += ": ";
ImGui::Text(name.c_str()); ImGui::SameLine();
ImGui::Text(std::get<1>(it).c_str());
}
ImGui::PopTextWrapPos();
if(chat.new_message)
{
ImGui::SetScrollPosHere();
chat.new_message = false;
}
ImGui::EndChildFrame();
}
Chat::Chat()
{
if(this->initialized_)
{
this->new_message = false;
this->initialized_ = false;
}
}
void Chat::AddMessage(std::string char_name, std::string message)
{
if(this->messages.size() >= 255) this->messages.erase(this->messages.begin());
this->messages.push_back(std::make_pair(char_name, message));
this->new_message = true;
}
| 24.321895 | 127 | 0.580316 | [
"render",
"vector"
] |
dc147d9ba97ebcd94ffb714f7e4726cda32e9c91 | 5,728 | cpp | C++ | src/main.cpp | joewiz/curlpipe | e969d69bd156869f0ebdee85eed7cc8529c3e10e | [
"MIT"
] | 4 | 2019-03-08T19:56:41.000Z | 2022-03-11T09:55:48.000Z | src/main.cpp | joewiz/curlpipe | e969d69bd156869f0ebdee85eed7cc8529c3e10e | [
"MIT"
] | 5 | 2018-11-22T16:11:32.000Z | 2018-11-23T13:01:32.000Z | src/main.cpp | xquery/curlscript | b5a745ae481f578044b6c6016442b2f4620a0156 | [
"MIT"
] | 1 | 2018-11-22T15:49:26.000Z | 2018-11-22T15:49:26.000Z | /******************************************************************************
* curlpipe - https://github.com/xquery/curlpipe
******************************************************************************
* Copyright (c) 2017-2018 James Fuller <jim.fuller@webcomposite.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
******************************************************************************/
#include <cxxopts.hpp>
#include <vector>
#include <numeric>
#include <functional>
#include <iostream>
#include <curlpipe/curlpipe.cpp>
using namespace std;
int banner(){
cout << "curlpipe " << get_version() << " | ⓒ 2017-2018 James Fuller <jim.fuller@webcomposite.com> | https://github.com/xquery/curlpipe" << endl;
return CS_OK;
}
int usage(){
banner();
cout << "\nUsage: curlpipe [options...] <file>\n\n";
cout << " ex. > curlpipe -PmyPort=8001 -PmyHost=localhost mycurlpipe.cp \n\n"
<< " -h | --help : Help.\n"
<< " -d | --debug : Emit debug info.\n"
<< " -i | --info : Emit info.\n"
<< " -l | --log : Enable logging to file.\n"
<< " -q | --quiet : Suppress output to stdout (console).\n"
<< " -a | --auth : Pass a username:password pair as the argument.\n"
<< " -A | --auth-type : Specify the auth mechanism (basic|digest).\n"
<< " -p | --params : Define set of parameters for token replacement (json|xml).\n"
<< " -P | --param : Define parameter(s) for token replacement.\n"
<< " -o | --options : Define set of curlpipe options (default is ~/.curlpiperc).\n"
<< " -O | --option : Define curlpipe option(s).\n"
<< " -f | --file : Supply curlpipe file uri.\n" << endl;
return CS_OK;
}
cxxopts::Options setopts(){
cxxopts::Options opts("curlpipe", "http pipelines with curl.");
opts.add_options()
("positional",
"Positional arguments: these are the arguments that are entered "
"without an option", cxxopts::value<std::vector<std::string>>())
("h,help", "Help.")
("d,debug", "Emit debug info.")
("i,info", "Emit info.")
("l,log", "Enable logging to file", cxxopts::value<string>())
("s,serialiser", "Switch serialiser",cxxopts::value<string>())
("q,quiet", "Suppress output to stdout (console).")
("a,auth", "Pass a username:password pair as the argument.",cxxopts::value<string>())
("A,auth-type", "Specify the auth mechanism (basic|digest).",cxxopts::value<string>())
("p,params", "Define set of parameters for token replacement with file (json|xml).",cxxopts::value<string>())
("P,param", "Define parameter(s) for token replacement.",cxxopts::value<string>())
("o,options", "Define set of curlpipe options (default is ~/.curlpiperc).",cxxopts::value<string>())
("O,option", "Define curlpipe option(s).",cxxopts::value<string>())
("f,file", "Supply curlpipe file uri.", cxxopts::value<string>());
opts.parse_positional({"input", "output", "positional"});
return opts;
}
int main(int argc, char** argv ){
#ifndef NDEBUG
DLOG_S(INFO) << "debug mode";
#endif
cxxopts::Options opts = setopts();
auto result = opts.parse(argc,argv);
if(result["help"].count() == 1){
usage();
return EXIT_SUCCESS;}
if(result["log"].count() == 1){
set_log_file(result["log"].as<string>());
DLOG_S(INFO) << "set logging to " << result["log"].as<string>(); }
DLOG_S(INFO) << "start processing...";
if(result["info"].count() == 1){
banner();
set_log_verbosity_info();
}else{
set_log_verbosity_error();}
if(result["debug"].count() == 1){
set_log_verbosity_max();}
if(result["positional"].count() == 1){
DLOG_S(INFO) << "set positional opt";
auto& v = result["positional"].as<std::vector<std::string>>();
for (const auto& s : v) {
curlpipe::exec(s, result["quiet"].count());}
} else{
if(result["file"].count() == 1){
DLOG_S(INFO) << "set file opt";
curlpipe::exec(result["file"].as<string>(), result["quiet"].count());
}else{
string script;
string lineInput;
while (cin >> lineInput) {
script += lineInput;
}
curlpipe::execScript(script, result["quiet"].count());
LOG_S(ERROR) << "must supply curlpipe file.";
return EXIT_FAILURE; }}
DLOG_S(INFO) << "finished processing, dumping output to stdout.";
return EXIT_SUCCESS;
}
| 43.067669 | 149 | 0.577514 | [
"vector"
] |
dc17da8ad76381b8d50af7e977198cb4ed2cc00b | 12,190 | cpp | C++ | FileGenerate/NcFileGenerate/arrayncfilegenerate.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | 1 | 2021-01-29T02:12:53.000Z | 2021-01-29T02:12:53.000Z | FileGenerate/NcFileGenerate/arrayncfilegenerate.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | FileGenerate/NcFileGenerate/arrayncfilegenerate.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | // Author : XuBenHao
// Version : 1.0.0
// Mail : xbh370970843@163.com
// Copyright : XuBenHao 2020 - 2030
#include "arrayncfilegenerate.h"
namespace NFileGenerate
{
ArrayNcFileGenerate::ArrayNcFileGenerate(QObject* object)
: NcFileGenerate(object)
{
}
int ArrayNcFileGenerate::GenerateForSearch(
const QString& filePath_,
char* pContent_)
{
m_file.close();
m_file.setFileName(filePath_);
bool _bRet = m_file.open(
QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text);
if(!_bRet)
{
return ACCESS_ERROR;
}
// how to generate search file
int _nSize = m_nParam.m_nSize;
QString _str;
QByteArray _nByteArr;
int i = 0;
double _nPos = 0.0;
char _strInfo[100];
for(; i < _nSize; i++)
{
if(i != 0.0)
{
_nPos += (m_nParam.m_arrElements[i-1].m_nSize.m_nWidth/2.0
+m_nParam.m_arrElements[i].m_nSize.m_nWidth/2.0);
}
_str = QString::asprintf("Move={ Type=1; MoveObjs={ Name=\"%s\", Id=%ld, Pos=%.f,PosWay=0; } }\n",
m_nParam.m_strScaleName,
m_nParam.m_nScaleId,
_nPos);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
char* _pStr = m_nParam.m_arrElements[i].m_strContent;
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "索引%d位置元素与%s进行比较",
i, pContent_);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
if(strcmp(pContent_, _pStr) == 0)
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "索引%d位置元素与%s匹配",
i, pContent_);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
QColor _nCol = NParameter::GetColor(m_nParam.m_arrElements[i].m_nMatch);
int _nR, _nG, _nB, _nA;
_nCol.getRgb(&_nR, &_nG, &_nB, &_nA);
_str = QString::asprintf("Color={ Name=\"%s\", Id=%ld, Value=(%d,%d,%d,%d);}\n",
m_nParam.m_arrElements[i].m_strName,
m_nParam.m_arrElements[i].m_nObjectId,
_nR, _nG, _nB, _nA);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
break;
}
else
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "索引%d位置元素与%s不匹配",
i, pContent_);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
QColor _nCol = NParameter::GetColor(m_nParam.m_arrElements[i].m_nNotMatch);
int _nR, _nG, _nB, _nA;
_nCol.getRgb(&_nR, &_nG, &_nB, &_nA);
_str = QString::asprintf("Color={ Name=\"%s\", Id=%ld, Value=(%d,%d,%d,%d);}\n",
m_nParam.m_arrElements[i].m_strName,
m_nParam.m_arrElements[i].m_nObjectId,
_nR, _nG, _nB, _nA);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
}
if(i < _nSize)
{
char _strInfo[100];
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "在索引%d位置找到查找元素", i);
_str = QString::asprintf("Tip={ Value=\"%s\"; }",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
else
{
_str = QString::asprintf("Tip ={ Value=\"查找元素在数组内不存在\"; };\n");
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
m_file.flush();
m_file.close();
return SUCCESS;
}
int ArrayNcFileGenerate::GenerateForDelete(
const QString& filePath_,
int nIndex_,
double nDeltaLength_)
{
m_file.close();
m_file.setFileName(filePath_);
bool _bRet = m_file.open(
QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text);
if(!_bRet)
{
return ACCESS_ERROR;
}
// how to generate delete file
int _nSize = m_nParam.m_nSize;
QString _str;
QByteArray _nByteArr;
int i = 0;
double _nPos = 0.0;
char _strInfo[100];
if(nIndex_ < 0 || nIndex_ >= _nSize)
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "The delete index position is not legal");
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
return SUCCESS;
}
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "将删除元素移出数组");
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
// PosWay:
// 0 Abs
// 1 Inc
_str = QString::asprintf("Move={ Type=1; MoveObjs={ Name=\"%s\", Id=%ld, Pos=%.f,PosWay=1; } }\n",
m_nParam.m_arrElements[nIndex_].m_strName,
m_nParam.m_arrElements[nIndex_].m_nObjectId,
nDeltaLength_);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
for(int i = nIndex_+1; i < _nSize; i++)
{
_nPos = (m_nParam.m_arrElements[i].m_nSize.m_nWidth/2.0
+m_nParam.m_arrElements[i-1].m_nSize.m_nWidth/2.0);
m_nParam.m_arrElements[i-1] = m_nParam.m_arrElements[i];
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "移动索引%d位置元素到其前一位置",
i);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
// PosWay:
// 0 Abs
// 1 Inc
_str = QString::asprintf("Move={ Type=1; MoveObjs={ Name=\"%s\", Id=%ld, Pos=%.f,PosWay=1; } }\n",
m_nParam.m_arrElements[i].m_strName,
m_nParam.m_arrElements[i].m_nObjectId,
-_nPos);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
}
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "Finish",
i);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
m_file.close();
return SUCCESS;
}
int ArrayNcFileGenerate::GenerateForInsert(
const QString& filePath_,
char* pContent_,
int nIndex_,
double nDeltaLength_,
long nInsertObjId_)
{
m_file.close();
m_file.setFileName(filePath_);
bool _bRet = m_file.open(
QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text);
if(!_bRet)
{
return ACCESS_ERROR;
}
// how to generate search file
int _nSize = m_nParam.m_nSize;
QString _str;
QByteArray _nByteArr;
//int i = 0;
double _nPos = 0.0;
char _strInfo[100];
if(_nSize == m_nParam.m_nCapacity)
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "数组已满,无法插入");
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
return SUCCESS;
}
if(nIndex_ < 0 || nIndex_ > _nSize)
{
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "插入位置%d不是合法位置",
nIndex_);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
else
{
m_nParam.m_arrElements.Add(NParameter::ArrayNcElement());
for(int i = _nSize - 1; i >= nIndex_; i--)
{
_nPos = (m_nParam.m_arrElements[i].m_nSize.m_nWidth/2.0
+m_nParam.m_arrElements[i+1].m_nSize.m_nWidth/2.0);
m_nParam.m_arrElements[i+1] = m_nParam.m_arrElements[i];
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "移动索引%d位置元素到下一位置",
i);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
// PosWay:
// 0 Abs
// 1 Inc
_str = QString::asprintf("Move={ Type=1; MoveObjs={ Name=\"%s\", Id=%ld, Pos=%.f,PosWay=1; } }\n",
m_nParam.m_arrElements[i].m_strName,
m_nParam.m_arrElements[i].m_nObjectId,
_nPos);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
NParameter::ArrayNcElement _nEle;
_nEle.m_nSize = m_nParam.m_arrElements[0].m_nSize;
_nEle.m_nDefault = m_nParam.m_arrElements[0].m_nDefault;
_nEle.m_nMatch = m_nParam.m_arrElements[0].m_nMatch;
_nEle.m_nNotMatch = m_nParam.m_arrElements[0].m_nNotMatch;
strncpy(
_nEle.m_strContent,
pContent_,
sizeof(_nEle.m_strContent));
strncpy(
_nEle.m_strName,
pContent_,
sizeof(_nEle.m_strName));
_nEle.m_nObjectId = nInsertObjId_;
m_nParam.m_arrElements[nIndex_] = _nEle;
//_nPos = ();
//m_nParam.m_arrElements[i+1] = m_nParam.m_arrElements[i];
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "移动插入元素到索引%d位置",
nIndex_);
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
// PosWay:
// 0 Abs
// 1 Inc
_str = QString::asprintf("Move={ Type=1; MoveObjs={ Name=\"%s\", Id=%ld, Pos=%.f,PosWay=1; } }\n",
m_nParam.m_arrElements[nIndex_].m_strName,
m_nParam.m_arrElements[nIndex_].m_nObjectId,
nDeltaLength_);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
}
memset(_strInfo, 0, sizeof(_strInfo));
sprintf(_strInfo, "Finish");
_str = QString::asprintf("Tip={ Value=\"%s\"; }\n",
_strInfo);
_nByteArr = _str.toUtf8();
m_file.write(_nByteArr);
m_file.flush();
m_file.close();
return SUCCESS;
}
}
| 33.955432 | 114 | 0.479409 | [
"object"
] |
dc1ea6f6bb5c3c91dd7f17e13de907a04f9e30da | 11,254 | cpp | C++ | common/dbinterface.cpp | tahmed-dev/sonic-swss-common | a2c82ffb4e164af00b44c6e4c59b80299f35f7b1 | [
"Apache-2.0"
] | null | null | null | common/dbinterface.cpp | tahmed-dev/sonic-swss-common | a2c82ffb4e164af00b44c6e4c59b80299f35f7b1 | [
"Apache-2.0"
] | 1 | 2020-06-05T06:27:17.000Z | 2020-06-05T06:27:17.000Z | common/dbinterface.cpp | tahmed-dev/sonic-swss-common | a2c82ffb4e164af00b44c6e4c59b80299f35f7b1 | [
"Apache-2.0"
] | 1 | 2021-04-20T23:14:58.000Z | 2021-04-20T23:14:58.000Z | #include <chrono>
#include <utility>
#include <hiredis/hiredis.h>
#include "dbinterface.h"
using namespace std;
using namespace std::chrono;
using namespace swss;
void DBInterface::set_redis_kwargs(std::string unix_socket_path, std::string host, int port)
{
m_unix_socket_path = unix_socket_path;
m_host = host;
m_port = port;
}
void DBInterface::connect(int dbId, const std::string& dbName, bool retry)
{
if (retry)
{
_persistent_connect(dbId, dbName);
}
else
{
_onetime_connect(dbId, dbName);
}
}
void DBInterface::close(const std::string& dbName)
{
m_redisClient.erase(dbName);
}
int64_t DBInterface::del(const string& dbName, const std::string& key, bool blocking)
{
auto innerfunc = [&]
{
return m_redisClient.at(dbName).del(key);
};
return blockable<int64_t>(innerfunc, dbName, blocking);
}
void DBInterface::delete_all_by_pattern(const string& dbName, const string& pattern)
{
auto& client = m_redisClient.at(dbName);
auto keys = client.keys(pattern);
for (auto& key: keys)
{
client.del(key);
}
}
bool DBInterface::exists(const string& dbName, const std::string& key)
{
return m_redisClient.at(dbName).exists(key);
}
std::string DBInterface::get(const std::string& dbName, const std::string& hash, const std::string& key, bool blocking)
{
auto innerfunc = [&]
{
auto pvalue = m_redisClient.at(dbName).hget(hash, key);
if (!pvalue)
{
std::string message = "Key '" + hash + "' field '" + key + "' unavailable in database '" + dbName + "'";
SWSS_LOG_WARN("%s", message.c_str());
throw UnavailableDataError(message, hash);
}
const std::string& value = *pvalue;
return value == "None" ? "" : value;
};
return blockable<std::string>(innerfunc, dbName, blocking);
}
std::map<std::string, std::string> DBInterface::get_all(const std::string& dbName, const std::string& hash, bool blocking)
{
auto innerfunc = [&]
{
std::map<std::string, std::string> map;
m_redisClient.at(dbName).hgetall(hash, std::inserter(map, map.end()));
if (map.empty())
{
std::string message = "Key '{" + hash + "}' unavailable in database '{" + dbName + "}'";
SWSS_LOG_WARN("%s", message.c_str());
throw UnavailableDataError(message, hash);
}
for (auto& i : map)
{
std::string& value = i.second;
if (value == "None")
{
value = "";
}
}
return map;
};
return blockable<std::map<std::string, std::string>>(innerfunc, dbName, blocking);
}
std::vector<std::string> DBInterface::keys(const std::string& dbName, const char *pattern, bool blocking)
{
auto innerfunc = [&]
{
auto keys = m_redisClient.at(dbName).keys(pattern);
if (keys.empty())
{
std::string message = "DB '{" + dbName + "}' is empty with pattern '" + pattern + "'!";
SWSS_LOG_WARN("%s", message.c_str());
throw UnavailableDataError(message, "hset");
}
return keys;
};
return blockable<std::vector<std::string>>(innerfunc, dbName, blocking);
}
int64_t DBInterface::publish(const std::string& dbName, const std::string& channel, const std::string& message)
{
return m_redisClient.at(dbName).publish(channel, message);
}
int64_t DBInterface::set(const std::string& dbName, const std::string& hash, const std::string& key, const std::string& value, bool blocking)
{
auto innerfunc = [&]
{
m_redisClient.at(dbName).hset(hash, key, value);
// Return the number of fields that were added.
return 1;
};
return blockable<int64_t>(innerfunc, dbName, blocking);
}
DBConnector& DBInterface::get_redis_client(const std::string& dbName)
{
return m_redisClient.at(dbName);
}
template <typename T, typename FUNC>
T DBInterface::blockable(FUNC f, const std::string& dbName, bool blocking)
{
int attempts = 0;
for (;;)
{
try
{
T ret_data = f();
_unsubscribe_keyspace_notification(dbName);
return ret_data;
}
catch (const UnavailableDataError& e)
{
if (blocking)
{
auto found = keyspace_notification_channels.find(dbName);
if (found != keyspace_notification_channels.end())
{
bool result = _unavailable_data_handler(dbName, e.getData());
if (result)
{
continue; // received updates, try to read data again
}
else
{
_unsubscribe_keyspace_notification(dbName);
throw; // No updates was received. Raise exception
}
}
else
{
// Subscribe to updates and try it again (avoiding race condition)
_subscribe_keyspace_notification(dbName);
}
}
else
{
return T();
}
}
catch (const std::system_error&)
{
/*
Something is fundamentally wrong with the request itself.
Retrying the request won't pass unless the schema itself changes. In this case, the error
should be attributed to the application itself. Re-raise the error.
*/
SWSS_LOG_ERROR("Bad DB request [%s]", dbName.c_str());
throw;
}
catch (const RedisError&)
{
// Redis connection broken and we need to retry several times
attempts += 1;
_connection_error_handler(dbName);
std::string msg = "DB access failure by [" + dbName + + "]";
if (BLOCKING_ATTEMPT_ERROR_THRESHOLD < attempts && attempts < BLOCKING_ATTEMPT_SUPPRESSION)
{
// Repeated access failures implies the database itself is unhealthy.
SWSS_LOG_ERROR("%s", msg.c_str());
}
else
{
SWSS_LOG_WARN("%s", msg.c_str());
}
}
}
}
// Unsubscribe the chosent client from keyspace event notifications
void DBInterface::_unsubscribe_keyspace_notification(const std::string& dbName)
{
auto found = keyspace_notification_channels.find(dbName);
if (found != keyspace_notification_channels.end())
{
SWSS_LOG_DEBUG("Unsubscribe from keyspace notification");
keyspace_notification_channels.erase(found);
}
}
// When the queried config is not available in Redis--wait until it is available.
// Two timeouts are at work here:
// 1. Notification timeout - how long to wait before giving up on receiving any given pub-sub message.
// 2. Max data wait - swsssdk-specific. how long to wait for the data to populate (in absolute time)
bool DBInterface::_unavailable_data_handler(const std::string& dbName, const char *data)
{
auto start = system_clock::now();
SWSS_LOG_DEBUG("Listening on pubsub channel '%s'", dbName.c_str());
auto wait = duration<float>(PUB_SUB_MAXIMUM_DATA_WAIT);
while (system_clock::now() - start < wait)
{
auto& channel = keyspace_notification_channels.at(dbName);
auto ctx = channel->getContext();
redisReply *reply;
int rc = redisGetReply(ctx, reinterpret_cast<void**>(&reply));
if (rc == REDIS_ERR && ctx->err == REDIS_ERR_IO && errno == EAGAIN)
{
// Timeout
continue;
}
if (rc != REDIS_OK)
{
throw RedisError("Failed to redisGetReply with on pubsub channel on dbName=" + dbName, ctx);
}
RedisReply r(reply);
// r is an array of:
// 0. 'type': 'pmessage',
// 1. 'pattern': '__key*__:*'
// 2. 'channel':
// 3. 'data':
redisReply& r3 = *r.getChild(3);
if (r3.type != REDIS_REPLY_STRING)
{
throw system_error(make_error_code(errc::io_error),
"Wrong expected type of result");
}
if (strcmp(r3.str, data) == 0)
{
SWSS_LOG_INFO("'%s' acquired via pub-sub dbName=%s. Unblocking...", data, dbName.c_str());
// Wait for a "settling" period before releasing the wait.
sleep(DATA_RETRIEVAL_WAIT_TIME);
return true;
}
}
SWSS_LOG_WARN("No notification for '%s' from '%s' received before timeout.", data, dbName.c_str());
return false;
}
// Subscribe the chosent client to keyspace event notifications
void DBInterface::_subscribe_keyspace_notification(const std::string& dbName)
{
SWSS_LOG_DEBUG("Subscribe to keyspace notification");
auto& client = m_redisClient.at(dbName);
DBConnector *pubsub = client.newConnector(0);
pubsub->psubscribe(KEYSPACE_PATTERN);
// Set the timeout of the pubsub channel, so future redisGetReply will be impacted
struct timeval tv = { 0, (suseconds_t)(1000 * PUB_SUB_NOTIFICATION_TIMEOUT) };
int rc = redisSetTimeout(pubsub->getContext(), tv);
if (rc != REDIS_OK)
{
throw RedisError("Failed to redisSetTimeout", pubsub->getContext());
}
keyspace_notification_channels.emplace(std::piecewise_construct, std::forward_as_tuple(dbName), std::forward_as_tuple(pubsub));
}
// In the event Redis is unavailable, close existing connections, and try again.
void DBInterface::_connection_error_handler(const std::string& dbName)
{
SWSS_LOG_WARN("Could not connect to Redis--waiting before trying again.");
int dbId = get_redis_client(dbName).getDbId();
close(dbName);
sleep(CONNECT_RETRY_WAIT_TIME);
connect(dbId, dbName, true);
}
void DBInterface::_onetime_connect(int dbId, const string& dbName)
{
if (dbName.empty())
{
throw invalid_argument("dbName");
}
pair<decltype(m_redisClient.begin()), bool> rc;
if (m_unix_socket_path.empty())
{
rc = m_redisClient.emplace(std::piecewise_construct
, std::forward_as_tuple(dbName)
, std::forward_as_tuple(dbId, m_host, m_port, 0));
}
else
{
rc = m_redisClient.emplace(std::piecewise_construct
, std::forward_as_tuple(dbName)
, std::forward_as_tuple(dbId, m_unix_socket_path, 0));
}
bool inserted = rc.second;
if (inserted)
{
auto redisClient = rc.first->second;
redisClient.config_set("notify-keyspace-events", KEYSPACE_EVENTS);
}
}
// Keep reconnecting to Database 'dbId' until success
void DBInterface::_persistent_connect(int dbId, const string& dbName)
{
for (;;)
{
try
{
_onetime_connect(dbId, dbName);
return;
}
catch (RedisError&)
{
const int wait = CONNECT_RETRY_WAIT_TIME;
SWSS_LOG_WARN("Connecting to DB '%s(%d)' failed, will retry in %d s", dbName.c_str(), dbId, wait);
close(dbName);
sleep(wait);
}
}
}
| 32.33908 | 141 | 0.595255 | [
"vector"
] |
dc2332709e19173c63b4b1aaad15e3a4839da318 | 536 | cpp | C++ | DP/Knapsack.cpp | yuruhi/library | fecbd92ec6c6997d50bf954c472ac4bfeff74de5 | [
"Apache-2.0"
] | null | null | null | DP/Knapsack.cpp | yuruhi/library | fecbd92ec6c6997d50bf954c472ac4bfeff74de5 | [
"Apache-2.0"
] | 6 | 2021-01-05T07:39:05.000Z | 2021-01-05T07:44:31.000Z | DP/Knapsack.cpp | yuruhi/library | fecbd92ec6c6997d50bf954c472ac4bfeff74de5 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include <algorithm>
#include <cassert>
template <class T>
std::vector<T> Knapsack(int n, int wight_limit, const std::vector<T>& value,
const std::vector<int>& weight) {
assert(n == static_cast<int>(value.size()));
assert(n == static_cast<int>(weight.size()));
std::vector<T> dp(wight_limit + 1, 0);
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= wight_limit - weight[i]; ++j) {
dp[j + weight[i]] = std::max(dp[j + weight[i]], dp[j] + value[i]);
}
}
return dp;
}
| 28.210526 | 76 | 0.585821 | [
"vector"
] |
dc2416bea14a826ad740fcb67da79c4312c9a774 | 3,409 | hpp | C++ | Ruken/Source/Include/Functional/Event.hpp | BluTree/Ruken | 0c8e8d2f80d3e7fbf9138f1761b045dc682301ba | [
"MIT"
] | 6 | 2020-09-12T19:16:49.000Z | 2022-03-17T14:10:16.000Z | Ruken/Source/Include/Functional/Event.hpp | BluTree/Ruken | 0c8e8d2f80d3e7fbf9138f1761b045dc682301ba | [
"MIT"
] | 1 | 2021-11-15T10:13:17.000Z | 2021-11-15T10:13:17.000Z | Ruken/Source/Include/Functional/Event.hpp | BluTree/Ruken | 0c8e8d2f80d3e7fbf9138f1761b045dc682301ba | [
"MIT"
] | 3 | 2020-09-03T16:41:35.000Z | 2022-01-24T09:35:55.000Z | /*
* MIT License
*
* Copyright (c) 2019-2020 Basile Combet, Philippe Yi
*
* 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 NON INFRINGEMENT. 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 <vector>
#include <functional>
#include "Build/Namespace.hpp"
#include "Types/FundamentalTypes.hpp"
BEGIN_RUKEN_NAMESPACE
/**
* \brief Event class. This class is comparable to the C# delegate without the -= operator
* \tparam TArgs Input arguments of the event
*/
template <typename... TArgs>
class Event
{
using Function = std::function<RkVoid(TArgs...)>;
private:
#pragma region Members
std::vector<Function> m_subscribers;
#pragma endregion
public:
#pragma region Constructors
Event() = default;
Event(Event const& in_copy) = default;
Event(Event&& in_move) = default;
~Event() = default;
#pragma endregion
#pragma region Methods
/**
* \brief Clears all the subscribers from the event
*/
RkVoid Reset() noexcept;
/**
* \brief Subscribes a new function to the event
* \param in_function Function to subscribe
*/
RkVoid Subscribe(Function const& in_function) noexcept;
RkVoid Subscribe(Function&& in_function) noexcept;
/**
* \brief Invokes the event
* \note Every subscriber will be invoked in the same order as they subscribed
*
* \param in_args Arguments to pass to all the subscribers
*/
RkVoid Invoke(TArgs... in_args) noexcept;
#pragma endregion
#pragma region Operators
/**
* \brief Equivalent of the Invoke() method
* \param in_args Arguments to pass to all the subscribers
*/
RkVoid operator()(TArgs... in_args) noexcept;
/**
* \brief Equivalent of the Subscribe() method
* \param in_function Function to subscribe
* \return Instance of the event
*/
Event& operator+=(Function const& in_function) noexcept;
Event& operator+=(Function&& in_function) noexcept;
Event& operator=(Event const& in_copy) = default;
Event& operator=(Event&& in_move) = default;
#pragma endregion
};
#include "Functional/Event.inl"
END_RUKEN_NAMESPACE | 30.4375 | 90 | 0.647697 | [
"vector"
] |
dc27c2e76331004224233f0966272bdc75683a56 | 434 | hpp | C++ | darknet_ros/include/Tracking_Kalman.hpp | sbgisen/darknet_ros_tracking | 2d2754d5a1005759bba2e0259c27ef84810522e3 | [
"MIT"
] | 2 | 2020-01-17T16:37:26.000Z | 2020-04-06T23:38:11.000Z | darknet_ros/include/Tracking_Kalman.hpp | sbgisen/darknet_ros_tracking | 2d2754d5a1005759bba2e0259c27ef84810522e3 | [
"MIT"
] | 6 | 2020-07-21T10:37:21.000Z | 2020-09-03T12:33:28.000Z | darknet_ros/include/Tracking_Kalman.hpp | sbgisen/darknet_ros_tracking | 2d2754d5a1005759bba2e0259c27ef84810522e3 | [
"MIT"
] | 1 | 2020-08-24T03:10:36.000Z | 2020-08-24T03:10:36.000Z | #include "yolo_v2_class.hpp"
#include "opencv2/video/tracking.hpp"
#include <opencv2/highgui/highgui.hpp>
class track_kalman
{
public:
track_kalman(int _state_size, int _meas_size, int _contr_size);
private:
cv::KalmanFilter kf;
int state_size;
int meas_size;
int contr_size;
void set(std::vector<bbox_t> result_vec);
std::vector<bbox_t> correct(std::vector<bbox_t> result_vec);
std::vector<bbox_t> predict();
};
| 19.727273 | 65 | 0.741935 | [
"vector"
] |
dc2a1510c64fd52cbcc8ad4bb29d9a226ed36639 | 9,746 | cpp | C++ | src/DescentEngine/src/EntityEngine/EntityEngine.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 7 | 2016-01-28T14:28:10.000Z | 2021-09-03T17:33:37.000Z | src/DescentEngine/src/EntityEngine/EntityEngine.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 1 | 2016-03-19T11:34:36.000Z | 2016-03-24T21:35:06.000Z | src/DescentEngine/src/EntityEngine/EntityEngine.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 3 | 2016-03-10T14:23:40.000Z | 2019-03-17T16:21:21.000Z | /*
Copyright (C) 2016 Thomas Hauth. All Rights Reserved.
* Written by Thomas Hauth (Thomas.Hauth@web.de)
This file is part of Kung Foo Barracuda.
Kung Foo Barracuda 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.
Kung Foo Barracuda 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 Kung Foo Barracuda. If not, see <http://www.gnu.org/licenses/>.
*/
#include "EntityEngine.h"
#include <algorithm>
#include <cmath>
#include <vector>
#include "Entity.h"
#include "EntityTemplate.h"
#include "../RenderEngine.h"
#include "MoveAccessClass.h"
#include "../Timing.h"
#include "../Performance/SectionTimer.h"
#include "../Pathfinding/Node.h"
EntityEngine::EntityEngine() {
}
EntityEngine::~EntityEngine() {
}
// todo: make sure this index is cleaned up properly
void EntityEngine::addEntity(uniq<Entity> ent, std::string const& name, ManagedEntityList * managedList) {
// add in index after a certain name
m_entitiesIndex[name] = ent.get();
addEntity(std::move(ent));
}
Entity * EntityEngine::getEntity(std::string const& name) {
auto it = m_entitiesIndex.find(name);
if (it == m_entitiesIndex.end()) {
return nullptr;
} else {
return it->second;
}
}
void EntityEngine::dropNavigationNodes(NodeVector & nodes) {
nodes.clear();
}
bool EntityEngine::checkForCollisionObject(Vector2 const& position, const float radi) const {
// check statics
// this ensures that enemies keep their distance to walls and not get stuck
const float posDelta = 3.0f;
for (auto & sEnt : getStaticEntities()) {
if (sEnt->doesCollide()) {
// some easy criteria to be faster ( especially on the ouya )
if ((std::abs(position.y() - sEnt->getPosition().y()) < posDelta)
&& (std::abs(position.x() - sEnt->getPosition().x()) < posDelta)) {
const Vector2 conAtoB = sEnt->getPosition() - position;
const float conDist = conAtoB.magSquared();
if (conDist < (radi + sEnt->getCollisionRadius())) {
// that's a collision
return true;
}
}
}
}
return false;
}
void EntityEngine::generatePathfindingNodes(NodeVector & nodes) {
// lay a grid over the static entities
SectionTimer tm(GlobalTimingRepo::Rep, "EntityEngine.generatePathfindingNodes");
const int resolutionFactor = 1;
const float collisionMarginFactor = 2.5f;
const float gridSize = 1.0f / float(resolutionFactor); // 0.5f;
//const float neighbourDistance = sqrt(gridSize * gridSize * 2.0f) * 1.1f;
float floatHighestY = 0;
float floatLowestY = 100000000000.0f;
for (auto & ent : getStaticEntities()) {
floatHighestY = std::max(floatHighestY, ent->getPosition().y());
floatLowestY = std::min(floatLowestY, ent->getPosition().y());
}
dropNavigationNodes(nodes);
// protect against no entities
if (getStaticEntities().size() == 0)
return;
assert(floatHighestY > floatLowestY);
logging::Info() << "Generating navigation grid for lowY: " << floatLowestY << " highY: " << floatHighestY;
const int highestY = int(std::ceil(floatHighestY));
const int lowestY = int(std::floor(floatLowestY));
const int spanY = highestY - lowestY;
const float spanX = 15.0f;
const int nodeCount = (spanX * resolutionFactor) * (spanY * resolutionFactor);
nodes.resize(nodeCount);
// with a resolution of 2 times the tile size
const int sizeX = spanX * resolutionFactor;
const int sizeY = (spanY * resolutionFactor);
for (int y = 0; y < sizeY; y++) {
for (int x = 0; x < sizeX; x++) {
Vector2 pos(float(x) * gridSize, float(y) * gridSize + float(lowestY));
// do only add if there is no collision object near by
if (!checkForCollisionObject(pos, gridSize * collisionMarginFactor)) {
const int thisNodeLocation = sizeX * y + x;
NodePtr n = &nodes[thisNodeLocation];
n->Location = pos;
// connect to left
if (x > 0) {
// left same line
n->Neighbours.push_back(&nodes[thisNodeLocation - 1]);
// left lower
if (y > 0) {
n->Neighbours.push_back(&nodes[thisNodeLocation - 1 - sizeX]);
}
// left upper
if (y < (sizeY - 1)) {
n->Neighbours.push_back(&nodes[thisNodeLocation - 1 + sizeX]);
}
}
if (x < (sizeX - 1)) {
// right same line
n->Neighbours.push_back(&nodes[thisNodeLocation + 1]);
// right lower
if (y > 0) {
n->Neighbours.push_back(&nodes[thisNodeLocation + 1 - sizeX]);
}
// right upper
if (y < (sizeY - 1)) {
n->Neighbours.push_back(&nodes[thisNodeLocation + 1 + sizeX]);
}
}
if (y > 0) {
// lower one
n->Neighbours.push_back(&nodes[thisNodeLocation - sizeX]);
}
if (y < (sizeY - 1)) {
// upper one
n->Neighbours.push_back(&nodes[thisNodeLocation + sizeX]);
}
}
}
}
}
void EntityEngine::cleanManagedList(ManagedEntityList & managedList, Engines & e) {
for (auto ent : managedList) {
removeEntity(ent, e);
}
}
/*
void EntityEngine::cleanManagedStaticList(ManagedStaticEntityList & managedList, Engines & e) {
for (auto ent : managedList) {
removeStaticEntity(ent, e);
}
}*/
void EntityEngine::addStaticEntity(uniq<Entity> ent, ManagedStaticEntityList *managedList) {
//im_stat
// add partitioned in y
auto itAddPosition = getStaticEntitiesRegionStart(
EntityRegion(ent->getPosition().y(), ent->getPosition().y()));
// insert is before itAddPosition
m_staticEntities.insert(itAddPosition, std::move(ent));
}
void EntityEngine::executeMoveIntents() {
for (auto & et : getEntities()) {
MoveAccessClass::applyMoveIntent(*et.get());
}
}
void EntityEngine::updateDirtyEntities(ScreenTransform const& trans, VisualUpdatePairList & updateList) {
for (auto & et : getEntities()) {
if (et->isPositionDirty()) {
updateList.push_back(et->updateVisual(trans));
et->unsetPositionDirty();
}
}
}
EntityListUniq::iterator EntityEngine::getStaticEntitiesRegionStart(EntityRegion const& entRegion) {
for (auto it = getStaticEntities().begin(); it != getStaticEntities().end(); it++) {
if ((*it)->getPosition().y() > entRegion.m_lowerBound) {
return it;
}
}
return getStaticEntities().begin();
}
EntityListUniq::iterator EntityEngine::getStaticEntitiesRegionEnd(EntityRegion const& entRegion) {
for (auto it = getStaticEntities().begin(); it != getStaticEntities().end(); it++) {
if ((*it)->getPosition().y() > entRegion.m_upperBound) {
return it;
}
}
return getStaticEntities().end();
}
void EntityEngine::removeStaticEntity(EntityListUniq::iterator const& it, Engines & eg) {
// kill the visual
// TODO: memleak, remove this sprite visual in the corresponding unregister function
(*it)->unregister(eg);
/* SpriteVisual * vis = (*it)->getActiveVisual();
if (vis != nullptr) {
re.removeSpriteVisual(vis);
}
*/
m_staticEntities.erase(it);
}
void EntityEngine::removeEntity(EntityListUniq::iterator const& it, Engines & e) {
// find and erase from index list
/*
auto itIndex = std::find(m_entitiesIndex.begin(), m_entitiesIndex.end(), it->get());
todo: this is a map and you have to find the value
use boost::multi_index ??
auto itIndex = m_entitiesIndex.find(it->get());
if ( itIndex != m_entitiesIndex.end) {
m_entitiesIndex.erase(itIndex);
}*/
/*if ( itIndex != m_entitiesIndex.end()){
m_entitiesIndex.erase(itIndex);
}*/
(*it)->unregister(e);
getEntities().erase(it);
}
void EntityEngine::updatePathfinding() {
generatePathfindingNodes(m_pathfindingNodes);
}
void EntityEngine::removeEntity(Entity * ent, Engines & e) {
// find the pointer
auto it = find_uniq(getEntities().begin(), getEntities().end(), ent);
if (it == getEntities().end()) {
logging::Fatal() << "Could not find entity to remove in entity list";
} else {
removeEntity(it, e);
}
}
void EntityEngine::removeStaticEntity(Entity * ent, Engines & e) {
// find the pointer
auto it = find_uniq(getStaticEntities().begin(), getStaticEntities().end(), ent);
if (it == getStaticEntities().end()) {
logging::Fatal() << "Could not find static entity to remove in entity list";
} else {
removeStaticEntity(it, e);
}
}
void EntityEngine::cleanAllStatic(Engines &eg) {
while (getStaticEntities().begin() != getStaticEntities().end()) {
removeStaticEntity(getStaticEntities().begin(), eg);
}
logging::Info() << "static entity count after kill: " << getStaticEntities().size();
}
void EntityEngine::cleanStaticBelow(const float yCoord, Engines &eg) {
std::vector<Entity *> toRemove;
for (auto it = getStaticEntities().begin(); it != getStaticEntities().end(); it++) {
if ((*it)->getPosition().y() < yCoord) {
toRemove.push_back(it->get());
}
}
for (auto it : toRemove) {
removeStaticEntity(it, eg);
}
}
EntityTemplate const& EntityEngine::getTemplate(std::string const& name) const {
auto it = m_templateMap.find(name);
if (it == m_templateMap.end()) {
logging::Fatal() << "Entitiy Template " << name << " not known";
}
return it->second;
}
EntityEngine::TemplateMap const& EntityEngine::getTemplateMap() const {
return m_templateMap;
}
void EntityEngine::addTemplate(std::string const& name, EntityTemplate templ) {
m_templateMap[name] = templ;
}
NodePtr EntityEngine::findClosestNode(Vector2 const& vec) {
NodePtr minNode = nullptr;
float minDist = 10000000.0f;
for (auto & n : m_pathfindingNodes) {
const float d = n.distanceTo(vec);
if (d < minDist) {
minNode = &n;
minDist = d;
}
}
return minNode;
}
| 28.580645 | 107 | 0.68818 | [
"object",
"vector"
] |
dc39419df90ffb026cc58c845efa6f370845e8d2 | 2,542 | cpp | C++ | example/math/src/math_exp2.cpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 12 | 2016-08-02T17:01:13.000Z | 2021-03-04T12:11:33.000Z | example/math/src/math_exp2.cpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 5 | 2017-05-09T12:05:06.000Z | 2021-03-16T10:39:23.000Z | example/math/src/math_exp2.cpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 2 | 2016-08-25T13:10:29.000Z | 2019-05-01T01:54:29.000Z | //============================================================================
// MCKL/example/math/src/math_exp2.cpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2018, Yan Zhou
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#include "math_asm.hpp"
MCKL_EXAMPLE_DEFINE_MATH_ASM(A1R1, double, exp2, vd_exp2)
int main(int argc, char **argv)
{
math_asm_vd_exp2_check(0xC08FF00000000000ULL, 0x408FF80000000000ULL);
mckl::Vector<MathBound<double>> bounds;
bounds.push_back(MathBound<double>(-1022, -1000));
bounds.push_back(MathBound<double>(-1000, -500));
bounds.push_back(MathBound<double>(-500, -1));
bounds.push_back(MathBound<double>(-1, -DBL_MIN));
bounds.push_back(MathBound<double>(-DBL_MIN, DBL_MIN));
bounds.push_back(MathBound<double>(DBL_MIN, 1));
bounds.push_back(MathBound<double>(1, 500));
bounds.push_back(MathBound<double>(500, 1000));
bounds.push_back(MathBound<double>(1000, 1023));
math_asm(argc, argv, math_asm_vd_exp2, bounds);
return 0;
}
| 47.074074 | 78 | 0.659323 | [
"vector"
] |
dc3a3d2a784da152df57664e8a0beb8fd8a7366e | 1,656 | hpp | C++ | src/track.hpp | Gypsophino-dev/Gypsophino | 484325bd5db36d99cdc13048646695b94f656111 | [
"WTFPL"
] | null | null | null | src/track.hpp | Gypsophino-dev/Gypsophino | 484325bd5db36d99cdc13048646695b94f656111 | [
"WTFPL"
] | null | null | null | src/track.hpp | Gypsophino-dev/Gypsophino | 484325bd5db36d99cdc13048646695b94f656111 | [
"WTFPL"
] | null | null | null | #pragma once
#include "shape.hpp"
#include "score.hpp"
#include "note.hpp"
#include <raylib.h>
#include <vector>
namespace gyp {
class track : rectangle {
private:
using vci = std::vector<float>::const_iterator;
// Track Style
Color fill;
Color outline;
int thick;
KeyboardKey bind_key;
// Node Style
note note_style;
// Timing
int current_time; // lower limit for note to display
int visible_time; // upper limit for note to display
int error_time; // max time difference
// Speed (Setted by set_geometry())
int speed;
// Iterator
bool is_iterator_set;
vci notes_begin; // For drawing
vci notes_end; // For drawing
vci notes_current; // For drawing
vci notes_visible; // For drawing
// Score
score<parabolic_func> track_score;
int judge_height;
public:
// Constructor & Destructor
track();
// track(const track &other);
// track(track &&other) noexcept;
~track() = default;
// Setter
void set_geometry(int pos_x, int pos_y, int width, int height);
void set_track_style(Color fill_color, Color outline_color, int outline_thickness, KeyboardKey bind_key);
void set_note_style(int height, Color color);
void set_note_style(int height, Image image);
void set_time(int current_time, int visible_time, int error_time);
void set_speed(int speed);
void set_iterator(vci iter_begin, vci iter_end);
// Getter
[[nodiscard]] float get_score() const;
// Method
int init();
void update();
void sync(int current_time);
void draw() const;
void draw_pressed() const;
void hit(); // just for update the canvas, not for score
void interact();
};
} // namespace gyp
| 25.090909 | 107 | 0.702295 | [
"shape",
"vector"
] |
dc3aa010431e74a5c22a4910517ee75d86f04866 | 6,255 | cpp | C++ | src/Equations/Fluid/DensityFromBoundaryFluxPXI.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 12 | 2020-09-07T11:19:10.000Z | 2022-02-17T17:40:19.000Z | src/Equations/Fluid/DensityFromBoundaryFluxPXI.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 110 | 2020-09-02T15:29:24.000Z | 2022-03-09T09:50:01.000Z | src/Equations/Fluid/DensityFromBoundaryFluxPXI.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 3 | 2021-05-21T13:24:31.000Z | 2022-02-11T14:43:12.000Z | /**
* This term represents the flux of particles from a p/xi grid across the grid
* p boundary into the fluid grid. The flux of particles into the fluid grid
* cell 'r' is given by the pitch-integrated flux across the p=pmax boundary:
*
* / +1
* S(r) = 2*pi*pmax^2 | Phi^{(p)}(r, pmax, xi) dxi
* / -1
*
* NOTE: This term should be added to the equation for the density (e.g. 'nRE')
* and applied to the distribution function (i.e. the matrix column representing 'fRE').
*/
#include <functional>
#include "DREAM/Equations/Fluid/DensityFromBoundaryFluxPXI.hpp"
#include "DREAM/NotImplementedException.hpp"
using namespace DREAM;
/**
* Constructor.
*/
DensityFromBoundaryFluxPXI::DensityFromBoundaryFluxPXI(
FVM::Grid *densityGrid, FVM::Grid *distributionGrid,
const FVM::Operator *eqn
) : FVM::EquationTerm(densityGrid), distributionGrid(distributionGrid),
equation(eqn) {
SetName("DensityFromBoundaryFluxPXI");
}
/**
* Destructor.
*/
DensityFromBoundaryFluxPXI::~DensityFromBoundaryFluxPXI() {}
/**
* Get the number of non-zero elements per matrix row in the
* linearized operator matrix.
*/
len_t DensityFromBoundaryFluxPXI::GetNumberOfNonZerosPerRow() const {
// XXX Here we assume that all momentum grids are the same
const len_t nXi = this->distributionGrid->GetMomentumGrid(0)->GetNp2();
return (nXi*3);
}
/**
* Get the number of non-zero elements per matrix row in the
* jacobian matrix.
*
* TODO calculate correctly by taking 'equation' into account.
*/
len_t DensityFromBoundaryFluxPXI::GetNumberOfNonZerosPerRow_jac() const {
// XXX Here we assume that all momentum grids are the same
const len_t nXi = this->distributionGrid->GetMomentumGrid(0)->GetNp2();
return (nXi*3);
}
/**
* Set a block of the jacobian.
*
* derivId: Quantity with respect to which the differentation should be made.
* qtyId: Quantity to differentiate.
* jac: Jacobian matrix.
* x: Value of unknown quantity.
*/
bool DensityFromBoundaryFluxPXI::SetJacobianBlock(
const len_t qtyId, const len_t derivId, FVM::Matrix * jac, const real_t* /*x*/
) {
bool contributes = (qtyId == derivId);
//throw NotImplementedException("Cannot set jacobian for 'DensityFromBoundaryFluxPXI' term yet.");
if (qtyId == derivId)
this->SetMatrixElements(jac, nullptr);
// TODO Handle derivatives of coefficients
return contributes;
}
/**
* Set elements in the linearized operator matrix.
*
* mat: Matrix to set elements of.
* rhs: Right-hand-side vector to set elements of.
*/
void DensityFromBoundaryFluxPXI::SetMatrixElements(
FVM::Matrix *mat, real_t*
) {
this->__SetElements([&mat](const len_t I, const len_t J, const real_t V) {
mat->SetElement(I, J, V);
});
}
/**
* Set elements in the given function vector.
*
* vec: Function vector to set elements of.
* f: Distribution function.
*/
void DensityFromBoundaryFluxPXI::SetVectorElements(
real_t *vec, const real_t *f
) {
this->__SetElements([&vec,&f](const len_t I, const len_t J, const real_t V) {
vec[I] += V*f[J];
});
}
void DensityFromBoundaryFluxPXI::__SetElements(
std::function<void(const len_t, const len_t, const real_t)> f
) {
const len_t nr = this->distributionGrid->GetNr();
const real_t *VpVol = this->distributionGrid->GetVpVol();
len_t offset = 0;
for (len_t ir = 0; ir < nr; ir++) {
const FVM::MomentumGrid *mg = this->distributionGrid->GetMomentumGrid(ir);
const len_t
nxi = mg->GetNp2(),
np = mg->GetNp1();
const real_t
//*dp = mg->GetDp1(),
*dxi = mg->GetDp2(),
*dp_f = mg->GetDp1_f(),
*Vp_fp = this->distributionGrid->GetVp_f1(ir);
const real_t *Ap = equation->GetAdvectionCoeff1(ir);
const real_t *Dpp = equation->GetDiffusionCoeff11(ir);
const real_t *Dpx = equation->GetDiffusionCoeff12(ir);
// Evaluate xi-integral
for (len_t j = 0; j < nxi; j++) {
const len_t idx = offset + j*np + (np-1);
//real_t dd = dp[np-1] / dp[np-2];
real_t dd = 0;
real_t dVol = Vp_fp[j*(np+1) + np-1] * dxi[j] / VpVol[ir];
// Contribution from advection (with delta = 0)
const real_t *delta1_0 = equation->GetInterpolationCoeff1(ir,np-1,j);
for(len_t k=0; k<3; k++)
f(ir, idx+k-2, -(1+dd)*delta1_0[k]*Ap[j*(np+1) + np-1] * dVol);
// f(ir, idx, -(1+dd)*delta0[2]*Ap[j*(np+1)+np-1] * dVol);
// f(ir, idx-1, -(1+dd)*delta0[1]*Ap[j*(np+1)+np-1] * dVol);
const real_t *delta1_1 = equation->GetInterpolationCoeff1(ir,np-2,j);
for(len_t k=0; k<4; k++)
f(ir, idx+k-3, dd*delta1_1[k]*Ap[j*(np+1) + np-2] * dVol);
// f(ir, idx-1, dd*delta1[2]*Ap[j*(np+1)+np-2] * dVol);
// f(ir, idx-2, dd*delta1[1]*Ap[j*(np+1)+np-2] * dVol);
// Constribution from diffusion
// Dpp
f(ir, idx, (1+dd) * Dpp[j*(np+1) + np-1] / dp_f[np-2] * dVol);
f(ir, idx-1, -(1+dd) * Dpp[j*(np+1) + np-1] / dp_f[np-2] * dVol);
f(ir, idx-1, -dd * Dpp[j*(np+1) + np-2] / dp_f[np-3] * dVol);
f(ir, idx-2, dd * Dpp[j*(np+1) + np-2] / dp_f[np-3] * dVol);
// Dpx
if (j > 0 && j < nxi-1) {
f(ir, idx+np, +(1+dd)*Dpx[j*(np+1) + np-1] / (dp_f[np-2]+dp_f[np-3]) * dVol);
f(ir, idx+np-1, +(1+dd)*Dpx[j*(np+1) + np-1] / (dp_f[np-2]+dp_f[np-3]) * dVol);
f(ir, idx-np, -(1+dd)*Dpx[j*(np+1) + np-1] / (dp_f[np-2]+dp_f[np-3]) * dVol);
f(ir, idx-np-1, -(1+dd)*Dpx[j*(np+1) + np-1] / (dp_f[np-2]+dp_f[np-3]) * dVol);
f(ir, idx+np-1, -dd*Dpx[j*(np+1) + np-2] / (dp_f[np-3]+dp_f[np-4]) * dVol);
f(ir, idx+np-2, -dd*Dpx[j*(np+1) + np-2] / (dp_f[np-3]+dp_f[np-4]) * dVol);
f(ir, idx-np-1, +dd*Dpx[j*(np+1) + np-2] / (dp_f[np-3]+dp_f[np-4]) * dVol);
f(ir, idx-np-2, +dd*Dpx[j*(np+1) + np-2] / (dp_f[np-3]+dp_f[np-4]) * dVol);
}
}
offset += np*nxi;
}
}
| 33.994565 | 102 | 0.581455 | [
"vector"
] |
dc3fae7022cda8eef356f1ab5a95be664e644269 | 2,027 | cc | C++ | algorithms/src/examples/checkmate.cc | victor-iyiola/algorithms | 9787f259b232b74abfddf1e908924d69115bd85b | [
"MIT"
] | 1 | 2018-10-19T04:50:31.000Z | 2018-10-19T04:50:31.000Z | algorithms/src/examples/checkmate.cc | victor-iyiola/algorithms | 9787f259b232b74abfddf1e908924d69115bd85b | [
"MIT"
] | null | null | null | algorithms/src/examples/checkmate.cc | victor-iyiola/algorithms | 9787f259b232b74abfddf1e908924d69115bd85b | [
"MIT"
] | null | null | null | /** The Checkmate Problem.
*
* @description
* Given a King and a Queen, find out if the King is being
* threatened by the Queen.
*
* @solution
* The King is threatened by the Queen if 3 conditions are satisfied:
* 1. Horizontally:
* King.x == Queen.x
* 2. Vertically:
* King.y == Queen.y
* 3. Diagonally:
* abs(King.x - Queen.x) == abs(King.y - Queen.y)
*
* @author
* Victor I. Afolabi
* Artificial Intelligence & Software Engineer.
* Email: javafolabi@gmail.com
* GitHub: https://github.com/victor-iyiola
*
* @project
* File: checkmate.cc
* Created on 26 August, 2018 @ 09:22 AM.
*
* @license
* MIT License
* Copyright (c) 2018. Victor I. Afolabi. All rights reserved.
**/
#include <cmath>
// Maximum grid of a classic chess board.
#define MAX_GRID 8
struct King {
size_t x, y;
King(size_t x, size_t y) : x(x), y(y) {}
};
struct Queen {
size_t x, y;
Queen(size_t x, size_t y) : x(x), y(y) {}
};
/** Validate if the co-ordinates for King and Queen are out of bounds.
*
* @params
* K King&: King object.
* Q Queen&: Queen object.
*
* @return
* bool -- True if one of Queen or King is out of bounds,
* False, otherwise.
*/
bool validate(const King& K, const Queen& Q) {
return (K.x < MAX_GRID || K.y < MAX_GRID || Q.x < MAX_GRID || Q.y < MAX_GRID);
}
/** Checkmate: Is King threatened by Queen?
*
* @params
* King& K: King object.
* Queen& Q: Queen object.
*
* @return
* bool -- True, if King is being threatened,
* False otherwise or co-ordinates out-of-bounds.
*/
bool checkmate(const King& K, const Queen& Q) {
// Conditions:
// K.x == Q.x -- Horizontally
// K.y == Q.y -- Vertically
// |K.x - Q.x| == |K.y - Q.y| -- Diagonally
if (validate(K, Q))
return (K.x == Q.x || K.y == Q.y ||
std::abs(static_cast<float>(K.x - Q.x)) ==
std::abs(static_cast<float>(K.y - Q.y)));
return false;
}
| 24.130952 | 80 | 0.571288 | [
"object"
] |
dc40e6035e7c1bd7cde6f1ea1d16a704dbb7330b | 3,221 | cpp | C++ | Ko-Fi Engine/Source/GameObject.cpp | boscobarberesbert/Ko-Fi-Engine | 207ef2223f7c317a776cc7ca2da80ce9a2752116 | [
"MIT"
] | 2 | 2022-02-17T10:06:57.000Z | 2022-02-17T11:57:18.000Z | Ko-Fi Engine/Source/GameObject.cpp | boscobarberesbert/game-engine | 207ef2223f7c317a776cc7ca2da80ce9a2752116 | [
"MIT"
] | null | null | null | Ko-Fi Engine/Source/GameObject.cpp | boscobarberesbert/game-engine | 207ef2223f7c317a776cc7ca2da80ce9a2752116 | [
"MIT"
] | 8 | 2022-01-04T10:45:15.000Z | 2022-03-04T16:23:58.000Z | #include "GameObject.h"
#include "Engine.h"
#include "Primitive.h"
#include "Defs.h"
#include "ComponentTransform.h"
#include "ComponentMesh.h"
#include "ComponentInfo.h"
// Used with a path for the .fbx load
GameObject::GameObject(int id, KoFiEngine* engine, const char* name)
{
active = true;
//LoadModel(path);
if (name == nullptr)
this->name = "GameObject " + std::to_string(id);
else
this->name = name;
this->id = id;
this->engine = engine;
CreateComponent<ComponentInfo>();
transform = CreateComponent<ComponentTransform>();
this->parent = nullptr;
}
GameObject::~GameObject()
{
CleanUp();
}
bool GameObject::Start()
{
bool ret = true;
for (Component* component : components)
{
ret = component->Start();
}
return ret;
}
bool GameObject::PreUpdate()
{
bool ret = true;
for (Component* component : components)
{
ret = component->PreUpdate();
}
return ret;
}
bool GameObject::Update()
{
bool ret = true;
for (Component* component : components)
{
ret = component->Update();
}
return ret;
}
bool GameObject::PostUpdate(float dt)
{
bool ret = true;
if (active)
{
for (Component* component : components)
{
ret = component->PostUpdate(dt);
}
}
return ret;
}
bool GameObject::CleanUp()
{
for (Component* component : components)
{
RELEASE(component);
}
components.clear();
children.clear();
parent = nullptr;
return true;
}
void GameObject::Enable()
{
active = true;
}
void GameObject::Disable()
{
active = false;
}
void GameObject::DeleteComponent(Component* component)
{
auto componentIt = std::find(components.begin(), components.end(), component);
if (componentIt != components.end())
{
components.erase(componentIt);
components.shrink_to_fit();
}
}
void GameObject::AddComponent(Component* component)
{
components.push_back(component);
}
void GameObject::AttachChild(GameObject* child)
{
if (child->parent != nullptr)
child->parent->RemoveChild(child);
child->parent = this;
children.push_back(child);
child->transform->NewAttachment();
child->PropagateTransform();
}
void GameObject::RemoveChild(GameObject* child)
{
auto it = std::find(children.begin(), children.end(), child);
if (it != children.end())
{
children.erase(it);
}
}
void GameObject::PropagateTransform()
{
for (GameObject* go : children)
{
go->transform->OnParentMoved();
}
}
ComponentTransform* GameObject::GetTransform()
{
return this->transform;
}
void GameObject::SetName(std::string name)
{
this->name = name;
}
std::vector<GameObject*> GameObject::GetChildren() const
{
return children;
}
void GameObject::SetChild(GameObject* child)
{
children.push_back(child);
}
std::string GameObject::GetName()
{
return name;
}
GameObject* GameObject::GetParent()const
{
return parent;
}
std::vector<Component*> GameObject::GetComponents() const
{
return components;
}
void GameObject::SetId(int id)
{
this->id = id;
}
uint GameObject::GetId() const
{
return id;
}
bool GameObject::HasChildrenWithId(int id)
{
for (std::vector<GameObject*>::iterator child = children.begin(); child != children.end(); child++)
{
if ((*child)->id == id)
return true;
}
return false;
}
KoFiEngine* GameObject::GetEngine()
{
return engine;
}
| 15.866995 | 100 | 0.690469 | [
"vector",
"transform"
] |
dc413c92ea9169a95a63d2000f5cb023560e3ea9 | 1,622 | cpp | C++ | example/classic_func/test.cpp | goroyabu/com_cli | f2bad311276c56559537a3ba38410244658a17fc | [
"MIT"
] | 1 | 2019-04-22T11:17:43.000Z | 2019-04-22T11:17:43.000Z | example/classic_func/test.cpp | goroyabu/com_cli | f2bad311276c56559537a3ba38410244658a17fc | [
"MIT"
] | null | null | null | example/classic_func/test.cpp | goroyabu/com_cli | f2bad311276c56559537a3ba38410244658a17fc | [
"MIT"
] | null | null | null | /**
@author Goro Yabu
@date 2019/03/14
@version 2.0
**/
#include <com_cli.hpp>
#include <cmdline.hpp>
using namespace std;
int test_read_value()
{
string name = "Donkey";
com_cli::read_value("What is your name", &name);
int age = 37;
com_cli::read_value("How old are you", &age);
cout << endl;
cout << "Your name is " << name << " ! " << endl;
cout << "You are " << age << " years old ! " << endl;
cout << endl;
return 0;
}
int test_read_keyword()
{
string answer; int ianswer = 0;
vector<string> list = {"Sunday", "monday", "TUESDAY", "WEDnesday"};
if( com_cli::read_keyword("Choose your favourite day ?", list, &ianswer) == com_cli::CLI_OK ){
answer = list[ianswer];
cout << "Your choise = " << answer << endl;
cout << "Index of choise = " << ianswer << endl;
}
else{
com_cli::cli_error(1, "test_read_keyword", "Your input is not valid");
}
cout << endl;
return 0;
}
/*
int select_members()
{
vector<string> name = {"Mario", "bowser", "toad", "luigi"};
vector<double> level = {10.0, 99.0, 5.0, 1.03};
vector<int> answer;
com_cli::read_keyword("DK *** Select Character ***", name, -1, &answer);
cout << "YOUR TEAM" << endl;
for(int index : answer) cout << name[index] << endl;
cout << endl;
com_cli::read_value<double>("*** Modify Parameter ***", name, &level);
for(auto i : level) cout << i << endl;
return 0;
}
*/
int main()
{
com_cli::init("",".cli_hist");
test_read_value();
test_read_keyword();
com_cli::end();
return 0;
}
| 23.852941 | 98 | 0.562269 | [
"vector"
] |
dc438dc67d4c0c69c985cbe9b9417147063528e1 | 9,271 | cc | C++ | src/metadatamanagement/metaclient.cc | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null | src/metadatamanagement/metaclient.cc | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null | src/metadatamanagement/metaclient.cc | wangzhezhe/observerchain | faa8fb9d845a2720704538f01e1e7597083d4510 | [
"MIT"
] | null | null | null |
/*
*
* Copyright 2015 gRPC authors.
*
* 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 <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "unistd.h"
#include "metaserver.grpc.pb.h"
#include "../utils/groupManager/groupManager.h"
#include "metaclient.h"
const string projectDir = "/project1/parashar-001/zw241/software/eventDrivenWorkflow/src/metadatamanagement";
const string metaserverDir = projectDir + "/Metaserver";
class MetaClient
{
public:
MetaClient(std::shared_ptr<Channel> channel)
: stub_(Meta::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
std::string Recordtime(const std::string &key)
{
// Data we are sending to the server.
TimeRequest request;
request.set_key(key);
// Container for the data we expect from the server.
TimeReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Recordtime(&context, request, &reply);
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
std::string Recordtimestart(const std::string &key)
{
// Data we are sending to the server.
TimeRequest request;
request.set_key(key);
// Container for the data we expect from the server.
TimeReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Recordtimestart(&context, request, &reply);
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
std::string Recordtimetick(const std::string &key)
{
// Data we are sending to the server.
TimeRequest request;
request.set_key(key);
// Container for the data we expect from the server.
TimeReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Recordtimetick(&context, request, &reply);
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
std::string Getmeta(const std::string &key)
{
// Data we are sending to the server.
GetRequest request;
request.set_key(key);
// Container for the data we expect from the server.
GetReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Getmeta(&context, request, &reply);
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
std::string Putmeta(const std::string &key, const std::string &value)
{
// Data we are sending to the server.
PutRequest request;
request.set_key(key);
request.set_value(value);
// Container for the data we expect from the server.
PutReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Putmeta(&context, request, &reply);
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
private:
std::unique_ptr<Meta::Stub> stub_;
};
string getAddr()
{
vector<string> addrList = loadAddrInDir(metaserverDir);
if (addrList.size() > 0)
{
return addrList[0];
}
return "";
}
void recordKey(string key)
{
string serverAddr = getAddr();
if (serverAddr == "")
{
printf("failed to get server addr\n");
return;
}
MetaClient metaclient(grpc::CreateChannel(
serverAddr, grpc::InsecureChannelCredentials()));
string reply = metaclient.Recordtime(key);
std::cout << "Timer received: " << reply << std::endl;
return;
}
void recordKeyStart(string key)
{
string serverAddr = getAddr();
if (serverAddr == "")
{
printf("failed to get server addr\n");
return;
}
MetaClient metaclient(grpc::CreateChannel(
serverAddr, grpc::InsecureChannelCredentials()));
string reply = metaclient.Recordtimestart(key);
std::cout << "Timer received: " << reply << std::endl;
return;
}
void recordKeyTick(string key)
{
string serverAddr = getAddr();
if (serverAddr == "")
{
printf("failed to get server addr\n");
return;
}
MetaClient metaclient(grpc::CreateChannel(
serverAddr, grpc::InsecureChannelCredentials()));
string reply = metaclient.Recordtimetick(key);
std::cout << "Timer received: " << reply << std::endl;
return;
}
/*
int main(int argc, char **argv)
{
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
string serverAddr = getAddr();
if (serverAddr == "")
{
printf("server addr is 0\n");
return 0;
}
MetaClient metaclient(grpc::CreateChannel(
serverAddr, grpc::InsecureChannelCredentials()));
//std::string user("world");
//std::string reply = metaclient.SayHello(user);
//std::cout << "Greeter received: " << reply << std::endl;
std::string key("world");
string reply = metaclient.Recordtime(key);
std::cout << "Timer received: " << reply << std::endl;
sleep(1);
reply = metaclient.Recordtime(key);
std::cout << "Timer received: " << reply << std::endl;
key = "pattern1";
string meta1("meta1");
string meta2("meta2");
string meta3("meta3");
reply = metaclient.Getmeta(key);
std::cout << "Get pattern1 recieve: " << reply << std::endl;
reply = metaclient.Putmeta(key, meta1);
std::cout << "Put meta1 recieve: " << reply << std::endl;
reply = metaclient.Putmeta(key, meta2);
std::cout << "Put meta2 recieve: " << reply << std::endl;
reply = metaclient.Putmeta(key, meta3);
std::cout << "Put meta3 recieve: " << reply << std::endl;
reply = metaclient.Getmeta(key);
std::cout << "Get pattern1 recieve: " << reply << std::endl;
reply = metaclient.Getmeta(key);
std::cout << "Get pattern1 recieve: " << reply << std::endl;
reply = metaclient.Getmeta(key);
std::cout << "Get pattern1 recieve: " << reply << std::endl;
reply = metaclient.Getmeta(key);
std::cout << "Get pattern1 recieve: " << reply << std::endl;
printf("------test tick------\n");
key = "pattern_tick";
reply = metaclient.Recordtimestart(key);
std::cout << "Put pattern_tick 1st recieve: " << reply << std::endl;
reply = metaclient.Recordtimestart(key);
std::cout << "Put pattern_tick 2st recieve: " << reply << std::endl;
reply = metaclient.Recordtimetick(key);
std::cout << "Put pattern_tick 3st recieve: " << reply << std::endl;
reply = metaclient.Recordtimetick(key);
std::cout << "Put pattern_tick 4st recieve: " << reply << std::endl;
return 0;
}
*/ | 27.592262 | 109 | 0.592924 | [
"vector"
] |
dc4622640aa3ee37e2c4932de414c26ae24e8889 | 2,129 | cc | C++ | src/totalinfo.cc | kevinywlui/batstat | c97acff139b619a96698f3c9b3887ee83a035303 | [
"MIT"
] | null | null | null | src/totalinfo.cc | kevinywlui/batstat | c97acff139b619a96698f3c9b3887ee83a035303 | [
"MIT"
] | null | null | null | src/totalinfo.cc | kevinywlui/batstat | c97acff139b619a96698f3c9b3887ee83a035303 | [
"MIT"
] | null | null | null | #include "batinfo.h"
#include "totalinfo.h"
#include <fmt/format.h>
#include <cmath>
#include <vector>
#include <filesystem>
namespace fs = std::filesystem;
Totalinfo::Totalinfo() {
// Get number of batteries
num_batteries = 1;
fs::path power_supply_path = "/sys/class/power_supply";
auto bat_path = power_supply_path / ("BAT" + std::to_string(num_batteries));
while (fs::exists(bat_path)) {
num_batteries++;
bat_path = power_supply_path / ("BAT" + std::to_string(num_batteries));
}
std::vector<Batinfo> bat_vec;
for (uint32_t i=0; i < num_batteries; i++) {
bat_vec.push_back(Batinfo(i));
}
// sum up the totals
energy_now = 0;
energy_full = 0;
power_now = 0;
for (auto bat: bat_vec) {
energy_now += bat.energy_now;
energy_full += bat.energy_full;
power_now += bat.power_now;
}
energy_frac = energy_now / float(energy_full);
// determine total status
is_charging = false;
is_discharging = false;
for (auto bat: bat_vec) {
if (bat.is_charging) {
is_charging = true;
break;
}
else if (bat.is_discharging) {
is_discharging = true;
break;
}
}
is_full = !(is_charging || is_discharging);
// determine the status strings
if (is_charging) {
status = "Charging";
status_abbr = "CHR";
}
else if (is_discharging) {
status = "Discharging";
status_abbr = "DIS";
}
else {
status = "Full";
status_abbr = "FULL";
}
// determine number of hours until finish charging or discharging
if (is_full) {
hours_until_comp = -1;
}
else if (power_now == 0) {
hours_until_comp = -1;
}
else if (is_charging) {
hours_until_comp = (energy_full - energy_now) / float(power_now);
}
else {
hours_until_comp = energy_now / float(power_now);
}
if (hours_until_comp < 0) {
time_string = "";
}
else {
uint32_t hours = std::floor(hours_until_comp);
if (hours > 99) {
time_string = "Inf";
}
else {
uint32_t minutes = std::floor((hours_until_comp-hours)*60);
time_string = fmt::format("({:0>2}:{:0>2})", hours, minutes);
}
}
}
| 22.410526 | 78 | 0.627525 | [
"vector"
] |
dc479d5cba61894391b727f22cc95ca80e6f9ad9 | 5,451 | cpp | C++ | WINNOONNA NeuralNetAPI CPP OpenMP/NeuralNetAPI/Utils.cpp | sciencetechworks/WINOONNA | 64a8a416f94986f8f28dc083c2403d75a7611fc4 | [
"Apache-2.0"
] | null | null | null | WINNOONNA NeuralNetAPI CPP OpenMP/NeuralNetAPI/Utils.cpp | sciencetechworks/WINOONNA | 64a8a416f94986f8f28dc083c2403d75a7611fc4 | [
"Apache-2.0"
] | null | null | null | WINNOONNA NeuralNetAPI CPP OpenMP/NeuralNetAPI/Utils.cpp | sciencetechworks/WINOONNA | 64a8a416f94986f8f28dc083c2403d75a7611fc4 | [
"Apache-2.0"
] | null | null | null | /**
Wonderfully Integrated Native Object Oriented Neural Network API.
STANDARD DISCLAIMER
ScienceTechWorks is furnishing this item "as is". ScienceTechWorks does not provide any warranty of the item whatsoever, whether express, implied, or statutory, including, but not limited to, any warranty of merchantability or fitness for a particular purpose or any warranty that the contents of the item will be error-free.
In no respect shall ScienceTechWorks incur any liability for any damages, including, but limited to, direct, indirect, special, or consequential damages arising out of, resulting from, or any way connected to the use of the item, whether or not based upon warranty, contract, tort, or otherwise; whether or not injury was sustained by persons or property or otherwise; and whether or not loss was sustained from, or arose out of, the results of, the item, or any services that may be provided by ScienceTechWorks.
If a recognizable person appears in this video, use for commercial purposes may infringe a right of privacy or publicity. It may not be used to state or imply the endorsement by ScienceTechWorks employees of a commercial product, process or service, or used in any other manner that might mislead. Accordingly, it is requested that if this video is used in advertising and other commercial promotion, layout and copy be submitted to ScienceTechWorks prior to release. It may not be used to state or imply the endorsement by ScienceTechWorks employees of a commercial product, process or service, or used in any other manner that might mislead.
ScienceTechworks@gmail.com
Ramon.Talavera@gmail.com
**/
#include "Utils.h"
Utils::Utils(void)
{
}
Utils::~Utils(void)
{
}
int aleat(int inf,int sup){
return (int)(rand()/(((double)RAND_MAX+1)/(sup-inf+1))) + inf;
}
int aleat_r8(int inf,int sup,int *seed1,int *seed2,int *seed3)
{
return (int)generate_random_r8((double)inf,(double)sup,seed1,seed2,seed3);
}
double r8_random ( int *s1, int *s2, int *s3 )
//*****************************************************************************80
//
// Purpose:
//
// R8_RANDOM returns a pseudorandom number between 0 and 1.
//
// Discussion:
//
// This function returns a pseudo-random number rectangularly distributed
// between 0 and 1. The cycle length is 6.95E+12. (See page 123
// of Applied Statistics (1984) volume 33), not as claimed in the
// original article.
//
// Modified:
//
// 08 July 2008
//
// Author:
//
// Original FORTRAN77 version by Brian Wichman, David Hill.
// C++ version by John Burkardt.
//
// Reference:
//
// Brian Wichman, David Hill,
// Algorithm AS 183: An Efficient and Portable Pseudo-Random
// Number Generator,
// Applied Statistics,
// Volume 31, Number 2, 1982, pages 188-190.
//
// Parameters:
//
// Input/output, int *S1, *S2, *S3, three values used as the
// seed for the sequence. These values should be positive
// integers between 1 and 30,000.
//
// Output, double R8_RANDOM, the next value in the sequence.
//
{
double value;
*s1 = ( ( 171 * *s1 ) % 30269 );
*s2 = ( ( 172 * *s2 ) % 30307 );
*s3 = ( ( 170 * *s3 ) % 30323 );
value = fmod ( ( double ) ( *s1 ) / 30269.0
+ ( double ) ( *s2 ) / 30307.0
+ ( double ) ( *s3 ) / 30323.0, 1.0 );
return value;
}
/* Faster than generate_random, seeds should be in the range 1, 30.000 */
double generate_random_r8(double lower_bound,double upper_bound,int *seed1,int *seed2,int *seed3)
{
double length;
if (lower_bound>upper_bound)
return 0.0; // error
if ((lower_bound<0)&&(upper_bound<0))
{
length=-lower_bound-upper_bound;
} else
if ((lower_bound<0)&&(upper_bound>0))
{
length=-lower_bound+upper_bound;
} else
if ((lower_bound>0)&&(upper_bound>0))
{
length= lower_bound+upper_bound;
} else if ((lower_bound>0)&&(upper_bound<0))
{
// Nunca debiera darse
return 0.0;
}
double random = r8_random ( seed1, seed2, seed3 );
// esta entre 0.0 y 1.0
double generated= lower_bound+length*random;
return generated;
}
double generate_random(double lower_bound,double upper_bound)
{
double length;
if (lower_bound>upper_bound)
return 0.0; // error
if ((lower_bound<0)&&(upper_bound<0))
{
length=-lower_bound-upper_bound;
} else
if ((lower_bound<0)&&(upper_bound>0))
{
length=-lower_bound+upper_bound;
} else
if ((lower_bound>0)&&(upper_bound>0))
{
length= lower_bound+upper_bound;
} else if ((lower_bound>0)&&(upper_bound<0))
{
// Nunca debiera darse
return 0.0;
}
double random = ((double)rand() / ((double)RAND_MAX));
// esta entre 0.0 y 1.0
double generated= lower_bound+length*random;
return generated;
}
bool true_only_an_x_percent_of_times(double x)
{
//un dado de x caras tiene una prob 1/x de ser la cara 0
double ncaras_dado=1/x;
int rnd=aleat(0,(int)ncaras_dado);
if(rnd==0)
return true;
return false;
}
void plot(double (*function)(double value),
double startx,double endx,double delta,char *savepath)
{
ofstream fout;
fout.open(savepath);
//fout.setf(ios::fixed, ios::floatfield);
//fout.precision(5);
if (fout==NULL)
return;
double x,y;
for (x=startx;x<endx;x+=delta)
{
y=function(x);
fout<<x<<"\t"<<y<<endl;
}
fout.close();
}
| 30.116022 | 644 | 0.665382 | [
"object"
] |
dc49b6f9bb3e2b03c7a87588bb55d1f59ad4307c | 22,982 | cpp | C++ | src/services/candypond/CandyPond.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | src/services/candypond/CandyPond.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | src/services/candypond/CandyPond.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | #include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <arc/data/FileCache.h>
#include <arc/data/DataHandle.h>
#include <arc/URL.h>
#include <arc/StringConv.h>
#include <arc/UserConfig.h>
#include <arc/FileAccess.h>
#include <arc/FileUtils.h>
#include <arc/User.h>
#include <arc/Utils.h>
#include <arc/message/MessageAttributes.h>
#include <arc/message/PayloadRaw.h>
#include <arc/message/PayloadStream.h>
#include <arc/message/PayloadSOAP.h>
#include <arc/credential/Credential.h>
#include "CandyPond.h"
namespace CandyPond {
static Arc::Plugin *get_service(Arc::PluginArgument* arg)
{
Arc::ServicePluginArgument* srvarg =
arg?dynamic_cast<Arc::ServicePluginArgument*>(arg):NULL;
if(!srvarg) return NULL;
CandyPond* s = new CandyPond((Arc::Config*)(*srvarg),arg);
if (*s)
return s;
delete s;
return NULL;
}
Arc::Logger CandyPond::logger(Arc::Logger::rootLogger, "CandyPond");
CandyPond::CandyPond(Arc::Config *cfg, Arc::PluginArgument* parg) :
Service(cfg,parg),
dtr_generator(NULL) {
valid = false;
// read configuration information
/*
candypond config specifies A-REX conf file
<candypond:config>/etc/arc.conf</candypond:config>
*/
ns["candypond"] = "urn:candypond_config";
if (!(*cfg)["service"] || !(*cfg)["service"]["config"]) {
// error - no config defined
logger.msg(Arc::ERROR, "No A-REX config file found in candypond configuration");
return;
}
std::string arex_config = (std::string)(*cfg)["service"]["config"];
logger.msg(Arc::INFO, "Using A-REX config file %s", arex_config);
config.SetConfigFile(arex_config);
if (!config.Load()) {
logger.msg(Arc::ERROR, "Failed to process A-REX configuration in %s", arex_config);
return;
}
config.Print();
if (config.CacheParams().getCacheDirs().empty()) {
logger.msg(Arc::ERROR, "No caches defined in configuration");
return;
}
// check if we are running along with A-REX or standalone
bool with_arex = false;
if ((*cfg)["service"]["witharex"] && (std::string)(*cfg)["service"]["witharex"] == "true") with_arex = true;
// start Generator for data staging
dtr_generator = new CandyPondGenerator(config, with_arex);
valid = true;
}
CandyPond::~CandyPond(void) {
if (dtr_generator) {
delete dtr_generator;
dtr_generator = NULL;
}
}
Arc::MCC_Status CandyPond::CacheCheck(Arc::XMLNode in, Arc::XMLNode out, const Arc::User& mapped_user) {
/*
Accepts:
<CacheCheck>
<TheseFilesNeedToCheck>
<FileURL>url</FileURL>
...
</TheseFilesNeedToCheck>
</CacheCheck>
Returns
<CacheCheckResponse>
<CacheCheckResult>
<Result>
<FileURL>url</FileURL>
<ExistInTheCache>true</ExistInTheCache>
<FileSize>1234</FileSize>
</Result>
...
</CacheCheckResult>
</CacheCheckResponse>
*/
// substitute cache paths according to mapped user
ARex::CacheConfig cache_params(config.CacheParams());
cache_params.substitute(config, mapped_user);
Arc::FileCache cache(cache_params.getCacheDirs(), "0", mapped_user.get_uid(), mapped_user.get_gid());
if (!cache) {
logger.msg(Arc::ERROR, "Error creating cache");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheCheck", "Server error with cache");
}
Arc::XMLNode resp = out.NewChild("CacheCheckResponse");
Arc::XMLNode results = resp.NewChild("CacheCheckResult");
for(int n = 0;;++n) {
Arc::XMLNode id = in["CacheCheck"]["TheseFilesNeedToCheck"]["FileURL"][n];
if (!id) break;
std::string fileurl = (std::string)in["CacheCheck"]["TheseFilesNeedToCheck"]["FileURL"][n];
Arc::XMLNode resultelement = results.NewChild("Result");
resultelement.NewChild("FileURL") = fileurl;
bool fileexist = false;
std::string file_lfn;
Arc::initializeCredentialsType cred_type(Arc::initializeCredentialsType::SkipCredentials);
Arc::UserConfig usercfg(cred_type);
Arc::URL url(fileurl);
Arc::DataHandle d(url, usercfg);
if (!d) {
logger.msg(Arc::ERROR, "Can't handle URL %s", fileurl);
resultelement.NewChild("ExistInTheCache") = "false";
resultelement.NewChild("FileSize") = "0";
continue;
}
logger.msg(Arc::INFO, "Looking up URL %s", d->str());
file_lfn = cache.File(d->str());
if (file_lfn.empty()) {
logger.msg(Arc::ERROR, "Empty filename returned from FileCache");
resultelement.NewChild("ExistInTheCache") = "false";
resultelement.NewChild("FileSize") = "0";
continue;
}
logger.msg(Arc::INFO, "Cache file is %s", file_lfn);
struct stat fileStat;
if (Arc::FileStat(file_lfn, &fileStat, false))
fileexist = true;
else if (errno != ENOENT)
logger.msg(Arc::ERROR, "Problem accessing cache file %s: %s", file_lfn, Arc::StrError(errno));
resultelement.NewChild("ExistInTheCache") = (fileexist ? "true": "false");
if (fileexist)
resultelement.NewChild("FileSize") = Arc::tostring(fileStat.st_size);
else
resultelement.NewChild("FileSize") = "0";
}
return Arc::MCC_Status(Arc::STATUS_OK);
}
Arc::MCC_Status CandyPond::CacheLink(Arc::XMLNode in, Arc::XMLNode out, const Arc::User& mapped_user) {
/*
Accepts:
<CacheLink>
<TheseFilesNeedToLink>
<File>
<FileURL>url</FileURL> // remote file
<FileName>name</FileName> // local file on session dir
</File>
...
</TheseFilesNeedToLink>
<Username>uname</Username>
<JobID>123456789</JobID>
<Priority>90</Priority>
<Stage>false</Stage>
</CacheLink>
Returns:
<CacheLinkResponse>
<CacheLinkResult>
<Result>
<FileURL>url</FileURL>
<ReturnCode>0</ReturnCode>
<ReturnExplanation>success</ReturnExplanation>
</Result>
...
</CacheLinkResult>
</CacheLinkResponse>
*/
// read in inputs
bool dostage = false;
if (in["CacheLink"]["Stage"])
dostage = ((std::string)in["CacheLink"]["Stage"] == "true") ? true : false;
Arc::XMLNode jobidnode = in["CacheLink"]["JobID"];
if (!jobidnode) {
logger.msg(Arc::ERROR, "No job ID supplied");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Bad input (no JobID specified)");
}
std::string jobid = (std::string)jobidnode;
int priority = 50;
Arc::XMLNode prioritynode = in["CacheLink"]["Priority"];
if (prioritynode) {
if (!Arc::stringto((std::string)prioritynode, priority)) {
logger.msg(Arc::ERROR, "Bad number in priority element: %s", (std::string)prioritynode);
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Bad input (bad number in Priority)");
}
if (priority <= 0) priority = 1;
if (priority > 100) priority = 100;
}
Arc::XMLNode uname = in["CacheLink"]["Username"];
if (!uname) {
logger.msg(Arc::ERROR, "No username supplied");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Bad input (no Username specified)");
}
std::string username = (std::string)uname;
// TODO: try to force mapping to supplied user
if (username != mapped_user.Name()) {
logger.msg(Arc::ERROR, "Supplied username %s does not match mapped username %s", username, mapped_user.Name());
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Supplied username does not match mapped user");
}
// check job id and session dir are ok
// substitute session dirs and use tmp configuration to find the one for this job
std::vector<std::string> sessions = config.SessionRoots();
for (std::vector<std::string>::iterator session = sessions.begin(); session != sessions.end(); ++session) {
config.Substitute(*session, mapped_user);
}
ARex::GMConfig tmp_config;
tmp_config.SetSessionRoot(sessions);
std::string session_root = tmp_config.SessionRoot(jobid);
if (session_root.empty()) {
logger.msg(Arc::ERROR, "No session directory found");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "No session directory found for supplied Job ID");
}
std::string session_dir = session_root + '/' + jobid;
logger.msg(Arc::INFO, "Using session dir %s", session_dir);
struct stat fileStat;
if (!Arc::FileStat(session_dir, &fileStat, true)) {
logger.msg(Arc::ERROR, "Failed to stat session dir %s", session_dir);
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Failed to access session dir");
}
// check permissions - owner must be same as mapped user
if (fileStat.st_uid != mapped_user.get_uid()) {
logger.msg(Arc::ERROR, "Session dir %s is owned by %i, but current mapped user is %i", session_dir, fileStat.st_uid, mapped_user.get_uid());
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Failed to access session dir");
}
// get delegated proxy info to check permission on cached files
// TODO: use credentials of caller of this service. For now ask the
// delegation store for the proxy of the job.
ARex::DelegationStore::DbType deleg_db_type = ARex::DelegationStore::DbBerkeley;
switch (config.DelegationDBType()) {
case ARex::GMConfig::deleg_db_bdb:
deleg_db_type = ARex::DelegationStore::DbBerkeley;
break;
case ARex::GMConfig::deleg_db_sqlite:
deleg_db_type = ARex::DelegationStore::DbSQLite;
break;
}
ARex::DelegationStore dstore(config.DelegationDir(), deleg_db_type, false);
std::string proxy_path;
// Read job's local file to extract delegation id
ARex::JobLocalDescription job_desc;
if (job_local_read_file(jobid, config, job_desc) && !job_desc.delegationid.empty()) {
proxy_path = dstore.FindCred(job_desc.delegationid, job_desc.DN);
}
if (proxy_path.empty() || !Arc::FileStat(proxy_path, &fileStat, true)) {
logger.msg(Arc::ERROR, "Failed to access proxy of given job id %s at %s", jobid, proxy_path);
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", "Failed to access proxy");
}
Arc::UserConfig usercfg;
usercfg.UtilsDirPath(config.ControlDir());
usercfg.ProxyPath(proxy_path);
usercfg.InitializeCredentials(Arc::initializeCredentialsType::NotTryCredentials);
std::string dn;
Arc::Time exp_time;
try {
Arc::Credential ci(usercfg.ProxyPath(), usercfg.ProxyPath(), usercfg.CACertificatesDirectory(), "");
dn = ci.GetIdentityName();
exp_time = ci.GetEndTime();
} catch (Arc::CredentialError& e) {
logger.msg(Arc::ERROR, "Couldn't handle certificate: %s", e.what());
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLink", std::string("Error with proxy at "+proxy_path));
}
logger.msg(Arc::INFO, "DN is %s", dn);
// create cache
// substitute cache paths according to mapped user
ARex::CacheConfig cache_params(config.CacheParams());
cache_params.substitute(config, mapped_user);
Arc::FileCache cache(cache_params.getCacheDirs(), jobid, mapped_user.get_uid(), mapped_user.get_gid());
if (!cache) {
logger.msg(Arc::ERROR, "Error with cache configuration");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheCheck", "Server error with cache");
}
// set up response structure
Arc::XMLNode resp = out.NewChild("CacheLinkResponse");
Arc::XMLNode results = resp.NewChild("CacheLinkResult");
std::map<std::string, std::string> to_download; // files not in cache (remote, local)
bool error_happened = false; // if true then don't bother with downloads at the end
// loop through all files
for (int n = 0;;++n) {
Arc::XMLNode id = in["CacheLink"]["TheseFilesNeedToLink"]["File"][n];
if (!id) break;
Arc::XMLNode f_url = id["FileURL"];
if (!f_url) break;
Arc::XMLNode f_name = id["FileName"];
if (!f_name) break;
std::string fileurl = (std::string)f_url;
std::string filename = (std::string)f_name;
std::string session_file = session_dir + '/' + filename;
Arc::XMLNode resultelement = results.NewChild("Result");
logger.msg(Arc::INFO, "Looking up URL %s", fileurl);
resultelement.NewChild("FileURL") = fileurl;
Arc::URL u(fileurl);
Arc::DataHandle d(u, usercfg);
if (!d) {
logger.msg(Arc::ERROR, "Can't handle URL %s", fileurl);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::BadURLError);
resultelement.NewChild("ReturnCodeExplanation") = "Could not hande input URL";
error_happened = true;
continue;
}
d->SetSecure(false);
// the actual url used with the cache
std::string url = d->str();
bool available = false;
bool is_locked = false;
if (!cache.Start(url, available, is_locked)) {
if (is_locked) {
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::Locked);
resultelement.NewChild("ReturnCodeExplanation") = "File is locked";
} else {
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::CacheError);
resultelement.NewChild("ReturnCodeExplanation") = "Error starting cache";
}
error_happened = true;
continue;
}
if (!available) {
cache.Stop(url);
// file not in cache - the result status for these files will be set later
to_download[fileurl] = session_file;
continue;
}
// file is in cache - check permissions
if (!cache.CheckDN(url, dn)) {
Arc::DataStatus res = d->Check(false);
if (!res.Passed()) {
logger.msg(Arc::ERROR, "Permission checking failed: %s", url);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::PermissionError);
resultelement.NewChild("ReturnCodeExplanation") = "Permission denied";
error_happened = true;
continue;
}
cache.AddDN(url, dn, exp_time);
logger.msg(Arc::VERBOSE, "Permission checking passed for url %s", url);
}
// link file
bool try_again = false;
// TODO add executable and copy flags to request
if (!cache.Link(session_file, url, false, false, false, try_again)) {
// If locked, send to DTR and let it deal with the retry strategy
if (try_again) {
to_download[fileurl] = session_file;
continue;
}
// failed to link - report as if not there
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::LinkError);
resultelement.NewChild("ReturnCodeExplanation") = "Failed to link to session dir";
error_happened = true;
continue;
}
// Successfully linked to session - move to scratch if necessary
if (!config.ScratchDir().empty()) {
std::string scratch_file(config.ScratchDir()+'/'+jobid+'/'+filename);
// Access session and scratch under mapped uid
Arc::FileAccess fa;
if (!fa.fa_setuid(mapped_user.get_uid(), mapped_user.get_gid()) ||
!fa.fa_rename(session_file, scratch_file)) {
logger.msg(Arc::ERROR, "Failed to move %s to %s: %s", session_file, scratch_file, Arc::StrError(errno));
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::LinkError);
resultelement.NewChild("ReturnCodeExplanation") = "Failed to link to move file from session dir to scratch";
error_happened = true;
continue;
}
}
// everything went ok so report success
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::Success);
resultelement.NewChild("ReturnCodeExplanation") = "Success";
}
// check for any downloads to perform, only if requested and there were no previous errors
if (to_download.empty() || error_happened || !dostage) {
for (std::map<std::string, std::string>::iterator i = to_download.begin(); i != to_download.end(); ++i) {
Arc::XMLNode resultelement = results.NewChild("Result");
resultelement.NewChild("FileURL") = i->first;
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::NotAvailable);
resultelement.NewChild("ReturnCodeExplanation") = "File not available";
}
return Arc::MCC_Status(Arc::STATUS_OK);
}
bool stage_start_error = false;
// Loop through files to download and start a DTR for each one
for (std::map<std::string, std::string>::iterator i = to_download.begin(); i != to_download.end(); ++i) {
Arc::XMLNode resultelement = results.NewChild("Result");
resultelement.NewChild("FileURL") = i->first;
// if one DTR failed to start then don't start any more
// TODO cancel others already started
if (stage_start_error) {
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::DownloadError);
resultelement.NewChild("ReturnCodeExplanation") = "Failed to start data staging";
continue;
}
logger.msg(Arc::VERBOSE, "Starting new DTR for %s", i->first);
if (!dtr_generator->addNewRequest(mapped_user, i->first, i->second, usercfg, jobid, priority)) {
logger.msg(Arc::ERROR, "Failed to start new DTR for %s", i->first);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::DownloadError);
resultelement.NewChild("ReturnCodeExplanation") = "Failed to start data staging";
stage_start_error = true;
}
else {
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::Staging);
resultelement.NewChild("ReturnCodeExplanation") = "Staging started";
}
}
return Arc::MCC_Status(Arc::STATUS_OK);
}
Arc::MCC_Status CandyPond::CacheLinkQuery(Arc::XMLNode in, Arc::XMLNode out) {
/*
Accepts:
<CacheLinkQuery>
<JobID>123456789</JobID>
</CacheLinkQuery>
Returns:
<CacheLinkQueryResponse>
<CacheLinkQueryResult>
<Result>
<ReturnCode>0</ReturnCode>
<ReturnExplanation>success</ReturnExplanation>
</Result>
</CacheLinkQueryResult>
</CacheLinkQueryResponse>
*/
Arc::XMLNode jobidnode = in["CacheLinkQuery"]["JobID"];
if (!jobidnode) {
logger.msg(Arc::ERROR, "No job ID supplied");
return Arc::MCC_Status(Arc::GENERIC_ERROR, "CacheLinkQuery", "Bad input (no JobID specified)");
}
std::string jobid = (std::string)jobidnode;
// set up response structure
Arc::XMLNode resp = out.NewChild("CacheLinkQueryResponse");
Arc::XMLNode results = resp.NewChild("CacheLinkQueryResult");
Arc::XMLNode resultelement = results.NewChild("Result");
std::string error;
// query Generator for DTR status
if (dtr_generator->queryRequestsFinished(jobid, error)) {
if (error.empty()) {
logger.msg(Arc::INFO, "Job %s: all files downloaded successfully", jobid);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::Success);
resultelement.NewChild("ReturnCodeExplanation") = "Success";
}
else if (error == "Job not found") {
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::CacheError);
resultelement.NewChild("ReturnCodeExplanation") = "No such job";
}
else {
logger.msg(Arc::INFO, "Job %s: Some downloads failed", jobid);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::DownloadError);
resultelement.NewChild("ReturnCodeExplanation") = "Download failed: " + error;
}
}
else {
logger.msg(Arc::VERBOSE, "Job %s: files still downloading", jobid);
resultelement.NewChild("ReturnCode") = Arc::tostring(CandyPond::Staging);
resultelement.NewChild("ReturnCodeExplanation") = "Still staging";
}
return Arc::MCC_Status(Arc::STATUS_OK);
}
Arc::MCC_Status CandyPond::process(Arc::Message &inmsg, Arc::Message &outmsg) {
// Check authorization
if(!ProcessSecHandlers(inmsg, "incoming")) {
logger.msg(Arc::ERROR, "CandyPond: Unauthorized");
return make_soap_fault(outmsg, "Authorization failed");
}
std::string method = inmsg.Attributes()->get("HTTP:METHOD");
// find local user
std::string mapped_username = inmsg.Attributes()->get("SEC:LOCALID");
if (mapped_username.empty()) {
logger.msg(Arc::ERROR, "No local user mapping found");
return make_soap_fault(outmsg, "No local user mapping found");
}
Arc::User mapped_user(mapped_username);
if(method == "POST") {
logger.msg(Arc::VERBOSE, "process: POST");
logger.msg(Arc::INFO, "Identity is %s", inmsg.Attributes()->get("TLS:PEERDN"));
// Both input and output are supposed to be SOAP
// Extracting payload
Arc::PayloadSOAP* inpayload = NULL;
try {
inpayload = dynamic_cast<Arc::PayloadSOAP*>(inmsg.Payload());
} catch(std::exception& e) { };
if(!inpayload) {
logger.msg(Arc::ERROR, "input is not SOAP");
return make_soap_fault(outmsg);
}
// Applying known namespaces
inpayload->Namespaces(ns);
if(logger.getThreshold() <= Arc::VERBOSE) {
std::string str;
inpayload->GetDoc(str, true);
logger.msg(Arc::VERBOSE, "process: request=%s",str);
}
// Analyzing request
Arc::XMLNode op = inpayload->Child(0);
if(!op) {
logger.msg(Arc::ERROR, "input does not define operation");
return make_soap_fault(outmsg);
}
logger.msg(Arc::VERBOSE, "process: operation: %s",op.Name());
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns);
outpayload->Namespaces(ns);
Arc::MCC_Status result(Arc::STATUS_OK);
// choose operation
if (MatchXMLName(op,"CacheCheck")) {
result = CacheCheck(*inpayload, *outpayload, mapped_user);
}
else if (MatchXMLName(op, "CacheLink")) {
result = CacheLink(*inpayload, *outpayload, mapped_user);
}
else if (MatchXMLName(op, "CacheLinkQuery")) {
result = CacheLinkQuery(*inpayload, *outpayload);
}
else {
// unknown operation
logger.msg(Arc::ERROR, "SOAP operation is not supported: %s", op.Name());
delete outpayload;
return make_soap_fault(outmsg);
}
if (!result)
return make_soap_fault(outmsg, result.getExplanation());
if (logger.getThreshold() <= Arc::VERBOSE) {
std::string str;
outpayload->GetDoc(str, true);
logger.msg(Arc::VERBOSE, "process: response=%s", str);
}
outmsg.Payload(outpayload);
if (!ProcessSecHandlers(outmsg,"outgoing")) {
logger.msg(Arc::ERROR, "Security Handlers processing failed");
delete outmsg.Payload(NULL);
return Arc::MCC_Status();
}
}
else {
// only POST supported
logger.msg(Arc::ERROR, "Only POST is supported in CandyPond");
return Arc::MCC_Status();
}
return Arc::MCC_Status(Arc::STATUS_OK);
}
Arc::MCC_Status CandyPond::make_soap_fault(Arc::Message& outmsg, const std::string& reason) {
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns,true);
Arc::SOAPFault* fault = outpayload?outpayload->Fault():NULL;
if(fault) {
fault->Code(Arc::SOAPFault::Sender);
if (reason.empty())
fault->Reason("Failed processing request");
else
fault->Reason("Failed processing request: "+reason);
}
outmsg.Payload(outpayload);
return Arc::MCC_Status(Arc::STATUS_OK);
}
} // namespace CandyPond
extern Arc::PluginDescriptor const ARC_PLUGINS_TABLE_NAME[] = {
{ "candypond", "HED:SERVICE", NULL, 0, &CandyPond::get_service },
{ NULL, NULL, NULL, 0, NULL }
};
| 36.192126 | 144 | 0.66687 | [
"vector"
] |
dc4abe5de3f4d332b18b8f78ba37f37852cb1b19 | 329 | cpp | C++ | fib.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | fib.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | fib.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int fib(int num)
{
if ((num == 1) || (num == 2))
return 1;
return fib(num - 1) + fib(num - 2);
}
};
int main(int argc, char const *argv[])
{
Solution *obj = new Solution();
cout << obj->fib(10) << endl;
return 0;
}
| 13.708333 | 39 | 0.56231 | [
"vector"
] |
dc4d54b96782d819a7eb0047e2552cba5684e864 | 3,606 | cpp | C++ | modules/task_1/galindo_fox_algorithm/main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | null | null | null | modules/task_1/galindo_fox_algorithm/main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | null | null | null | modules/task_1/galindo_fox_algorithm/main.cpp | allnes/pp_2022_spring | 159191f9c2f218f8b8487f92853cc928a7652462 | [
"BSD-3-Clause"
] | 2 | 2022-03-31T17:48:22.000Z | 2022-03-31T18:06:07.000Z | // Copyright 2022 Javier Galindo
#include <gtest/gtest.h>
#include <vector>
#include "../../../modules/task_1/galindo_fox_algorithm/galindo_fox_algorithm.h"
TEST(Javier_Galindo_Sequential, Test_Create_Random_Matrix) {
const int count = 10;
Matrix A = createRandomMatrix(count);
Matrix B(A);
ASSERT_EQ(A, B);
}
TEST(Javier_Galindo_Sequential, Test_Throw_Exception_Dif_Size) {
Matrix A = { 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
Matrix B(1);
ASSERT_ANY_THROW(sequentialBlockMatrixMultiplication(A, B, 4 * 4));
}
TEST(Javier_Galindo_Sequential, Test_Throw_Exception_Null_Block_size) {
Matrix A;
Matrix B;
ASSERT_ANY_THROW(sequentialBlockMatrixMultiplication(A, B, 0));
}
TEST(Javier_Galindo_Sequential, Test_Throw_Exception_Null_Matrix_Size) {
Matrix A;
Matrix B;
ASSERT_ANY_THROW(sequentialBlockMatrixMultiplication(A, B, 10));
}
TEST(Javier_Galindo_Sequential, Test_Throw_Exception_No_Square_Matrix_Size) {
Matrix A(1, 0);
Matrix B(1, 0);
ASSERT_ANY_THROW(sequentialBlockMatrixMultiplication(A, B, 13));
}
TEST(Javier_Galindo_Sequential, Test_Identity_Matrix_Mult) {
Matrix A = { 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
Matrix B(A);
Matrix C = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
ASSERT_EQ(A, C);
}
TEST(Javier_Galindo_Sequential, Test_Top_Matrix_Mult) {
Matrix A = { 1, 2, 3, 4,
0, 2, 3, 4,
0, 0, 3, 4,
0, 0, 0, 4 };
Matrix B(A);
Matrix C = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
Matrix C_my_result = { 1, 6, 18, 40,
0, 4, 15, 36,
0, 0, 9, 28,
0, 0, 0, 16};
ASSERT_EQ(C_my_result, C);
}
TEST(Javier_Galindo_Sequential, Test_4_On_4_Same_Matrix_Mult) {
Matrix A = { 1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4 };
Matrix B(A);
Matrix C = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
Matrix C_block = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
ASSERT_EQ(C, C_block);
}
TEST(Javier_Galindo_Sequential, Test_4_On_4_Reserve_Matrix_Mult) {
Matrix A = { 1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4 };
Matrix B = { 4, 3, 2, 1,
4, 3, 2, 1,
4, 3, 2, 1,
4, 3, 2, 1 };
Matrix C = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
Matrix C_my_result = { 40, 30, 20, 10,
40, 30, 20, 10,
40, 30, 20, 10,
40, 30, 20, 10 };
ASSERT_EQ(C_my_result, C);
}
TEST(Javier_Galindo_Sequential, Test_4_On_4_Matrix_Mult) {
Matrix A = { 4, 18, 7, -2,
0, 12, 1.3, -5.7,
0.01, 1.2, -1.2, -4,
0.3, 0, 7, -2.5};
Matrix B = { 4.3, -150, 14.14, 5.1,
1, -1, 0, -2,
2, 15.6, 6.15, 14.88,
88.14, 2.5, -7.3, 5};
Matrix C = sequentialBlockMatrixMultiplication(A, B, 4 * 4);
Matrix C_my_result = { -127.08, -513.8, 114.21, 78.56,
-487.798, -5.97, 49.605, -33.156,
-353.717, -31.42, 21.9614, -40.205,
-205.06, 57.95, 65.542, 93.19 };
ASSERT_TRUE(isEqualMatrix(C_my_result, C));
}
| 33.082569 | 80 | 0.512757 | [
"vector"
] |
dc4ecc5cb987d98c2d621dc2211208c00ba7312a | 9,539 | cpp | C++ | corelib/src/imufilter/MadgwickFilter.cpp | shovington/rtabmap | 1773f0962d24ece1dd23542a4805537185430d3d | [
"BSD-3-Clause"
] | 1 | 2020-12-09T21:52:54.000Z | 2020-12-09T21:52:54.000Z | corelib/src/imufilter/MadgwickFilter.cpp | shovington/rtabmap | 1773f0962d24ece1dd23542a4805537185430d3d | [
"BSD-3-Clause"
] | 1 | 2020-08-29T07:15:35.000Z | 2020-09-07T14:57:32.000Z | corelib/src/imufilter/MadgwickFilter.cpp | shovington/rtabmap | 1773f0962d24ece1dd23542a4805537185430d3d | [
"BSD-3-Clause"
] | 2 | 2020-10-31T08:30:10.000Z | 2020-11-12T20:30:45.000Z |
/*
* Copyright (C) 2010, CCNY Robotics Lab
* Ivan Dryanovski <ivan.dryanovski@gmail.com>
*
* http://robotics.ccny.cuny.edu
*
* Based on implementation of Madgwick's IMU and AHRS algorithms.
* http://www.x-io.co.uk/node/8#open_source_ahrs_and_imu_algorithms
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MadgwickFilter.h"
#include <rtabmap/utilite/ULogger.h>
namespace rtabmap {
// Fast inverse square-root
// See: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Reciprocal_of_the_square_root
static inline float invSqrt(float x)
{
float xhalf = 0.5f * x;
union
{
float x;
int i;
} u;
u.x = x;
u.i = 0x5f3759df - (u.i >> 1);
/* The next line can be repeated any number of times to increase accuracy */
u.x = u.x * (1.5f - xhalf * u.x * u.x);
return u.x;
}
template<typename T>
static inline void normalizeVectorOpt(T& vx, T& vy, T& vz)
{
T recipNorm = invSqrt (vx * vx + vy * vy + vz * vz);
vx *= recipNorm;
vy *= recipNorm;
vz *= recipNorm;
}
template<typename T>
static inline void normalizeQuaternion(T& q0, T& q1, T& q2, T& q3)
{
T recipNorm = invSqrt (q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
q0 *= recipNorm;
q1 *= recipNorm;
q2 *= recipNorm;
q3 *= recipNorm;
}
static inline void rotateAndScaleVector(
float q0, float q1, float q2, float q3,
float _2dx, float _2dy, float _2dz,
float& rx, float& ry, float& rz) {
// result is half as long as input
rx = _2dx * (0.5f - q2 * q2 - q3 * q3)
+ _2dy * (q0 * q3 + q1 * q2)
+ _2dz * (q1 * q3 - q0 * q2);
ry = _2dx * (q1 * q2 - q0 * q3)
+ _2dy * (0.5f - q1 * q1 - q3 * q3)
+ _2dz * (q0 * q1 + q2 * q3);
rz = _2dx * (q0 * q2 + q1 * q3)
+ _2dy * (q2 * q3 - q0 * q1)
+ _2dz * (0.5f - q1 * q1 - q2 * q2);
}
static inline void orientationChangeFromGyro(
float q0, float q1, float q2, float q3,
float gx, float gy, float gz,
float& qDot1, float& qDot2, float& qDot3, float& qDot4)
{
// Rate of change of quaternion from gyroscope
// See EQ 12
qDot1 = 0.5f * (-q1 * gx - q2 * gy - q3 * gz);
qDot2 = 0.5f * (q0 * gx + q2 * gz - q3 * gy);
qDot3 = 0.5f * (q0 * gy - q1 * gz + q3 * gx);
qDot4 = 0.5f * (q0 * gz + q1 * gy - q2 * gx);
}
static inline void addGradientDescentStep(
float q0, float q1, float q2, float q3,
float _2dx, float _2dy, float _2dz,
float mx, float my, float mz,
float& s0, float& s1, float& s2, float& s3)
{
float f0, f1, f2;
// Gradient decent algorithm corrective step
// EQ 15, 21
rotateAndScaleVector(q0,q1,q2,q3, _2dx, _2dy, _2dz, f0, f1, f2);
f0 -= mx;
f1 -= my;
f2 -= mz;
// EQ 22, 34
// Jt * f
s0 += (_2dy * q3 - _2dz * q2) * f0
+ (-_2dx * q3 + _2dz * q1) * f1
+ (_2dx * q2 - _2dy * q1) * f2;
s1 += (_2dy * q2 + _2dz * q3) * f0
+ (_2dx * q2 - 2.0f * _2dy * q1 + _2dz * q0) * f1
+ (_2dx * q3 - _2dy * q0 - 2.0f * _2dz * q1) * f2;
s2 += (-2.0f * _2dx * q2 + _2dy * q1 - _2dz * q0) * f0
+ (_2dx * q1 + _2dz * q3) * f1
+ (_2dx * q0 + _2dy * q3 - 2.0f * _2dz * q2) * f2;
s3 += (-2.0f * _2dx * q3 + _2dy * q0 + _2dz * q1) * f0
+ (-_2dx * q0 - 2.0f * _2dy * q3 + _2dz * q2) * f1
+ (_2dx * q1 + _2dy * q2) * f2;
}
template<typename T>
static inline void crossProduct(
T ax, T ay, T az,
T bx, T by, T bz,
T& rx, T& ry, T& rz) {
rx = ay*bz - az*by;
ry = az*bx - ax*bz;
rz = ax*by - ay*bx;
}
template<typename T>
static inline T normalizeVector(T& vx, T& vy, T& vz) {
T norm = sqrt(vx*vx + vy*vy + vz*vz);
T inv = 1.0 / norm;
vx *= inv;
vy *= inv;
vz *= inv;
return norm;
}
static inline bool computeOrientation(
Eigen::Vector3f A,
Eigen::Vector3f E,
Eigen::Quaternionf& orientation) {
float Hx, Hy, Hz;
float Mx, My, Mz;
float normH;
// A: pointing up
float Ax = A[0], Ay = A[1], Az = A[2];
// E: pointing down/north
float Ex = E[0], Ey = E[1], Ez = E[2];
// H: vector horizontal, pointing east
// H = E x A
crossProduct(Ex, Ey, Ez, Ax, Ay, Az, Hx, Hy, Hz);
// normalize H
normH = normalizeVector(Hx, Hy, Hz);
if (normH < 1E-7) {
// device is close to free fall (or in space?), or close to
// magnetic north pole.
// mag in T => Threshold 1E-7, typical values are > 1E-5.
return false;
}
// normalize A
normalizeVector(Ax, Ay, Az);
// M: vector horizontal, pointing north
// M = A x H
crossProduct(Ax, Ay, Az, Hx, Hy, Hz, Mx, My, Mz);
// Create matrix for basis transformation
Eigen::Matrix3f R;
//case WorldFrame::ENU:
// vector space world W:
// Basis: bwx (1,0,0) east, bwy (0,1,0) north, bwz (0,0,1) up
// vector space local L:
// Basis: H, M , A
// W(1,0,0) => L(H)
// W(0,1,0) => L(M)
// W(0,0,1) => L(A)
// R: Transform Matrix local => world equals basis of L, because basis of W is I
R(0,0) = Hx; R(0,1) = Mx; R(0,2) = Ax;
R(1,0) = Hy; R(1,1) = My; R(1,2) = Ay;
R(2,0) = Hz; R(2,1) = Mz; R(2,2) = Az;
// Matrix.getRotation assumes vector rotation, but we're using
// coordinate systems. Thus negate rotation angle (inverse).
Eigen::Quaternionf q(R);
orientation = q.inverse();
return true;
}
static inline bool computeOrientation(
Eigen::Vector3f A,
Eigen::Quaternionf& orientation) {
// This implementation could be optimized regarding speed.
// magnetic Field E must not be parallel to A,
// choose an arbitrary orthogonal vector
Eigen::Vector3f E;
if (fabs(A[0]) > 0.1 || fabs(A[1]) > 0.1) {
E[0] = A[1];
E[1] = A[0];
E[2] = 0.0;
} else if (fabs(A[2]) > 0.1) {
E[0] = 0.0;
E[1] = A[2];
E[2] = A[1];
} else {
// free fall
return false;
}
return computeOrientation(A, E, orientation);
}
MadgwickFilter::MadgwickFilter(const ParametersMap & parameters) :
IMUFilter(parameters),
q0(1.0), q1(0.0), q2(0.0), q3(0.0),
w_bx_(0.0), w_by_(0.0), w_bz_(0.0),
initialized_(false),
gain_ (Parameters::defaultImuFilterMadgwickGain()),
zeta_ (Parameters::defaultImuFilterMadgwickZeta())
{
parseParameters(parameters);
}
void MadgwickFilter::parseParameters(const ParametersMap & parameters)
{
Parameters::parse(parameters, Parameters::kImuFilterMadgwickGain(), gain_);
Parameters::parse(parameters, Parameters::kImuFilterMadgwickZeta(), zeta_);
}
/**
* Gain of the filter. Higher values lead to faster convergence but
* more noise. Lower values lead to slower convergence but smoother signal. [0.0, 1.0]
*/
void MadgwickFilter::setAlgorithmGain(double gain)
{
gain_ = gain;
}
/**
* Gyro drift gain (approx. rad/s). [-1.0, 1.0]
*/
void MadgwickFilter::setDriftBiasGain(double zeta)
{
zeta_ = zeta;
}
void MadgwickFilter::getOrientation(double & qx, double & qy, double & qz, double & qw) const
{
qx = this->q1;
qy = this->q2;
qz = this->q3;
qw = this->q0;
// perform precise normalization of the output, using 1/sqrt()
// instead of the fast invSqrt() approximation. Without this,
// TF2 complains that the quaternion is not normalized.
double recipNorm = 1 / sqrt(qx * qx + qy * qy + qz * qz + qw * qw);
qx *= recipNorm;
qy *= recipNorm;
qz *= recipNorm;
qw *= recipNorm;
}
void MadgwickFilter::reset(double qx, double qy, double qz, double qw)
{
this->q0 = qw;
this->q1 = qx;
this->q2 = qy;
this->q3 = qz;
w_bx_ = 0;
w_by_ = 0;
w_bz_ = 0;
initialized_ = false;
}
void MadgwickFilter::updateImpl(
double gx, double gy, double gz,
double ax, double ay, double az,
double dt)
{
if(!initialized_)
{
Eigen::Quaternionf orientation;
Eigen::Vector3f A;
A[0] = ax;
A[1] = ay;
A[2] = az;
computeOrientation(A,orientation);
reset(orientation.x(), orientation.y(), orientation.z(), orientation.w());
initialized_ = true;
return;
}
float s0, s1, s2, s3;
float qDot1, qDot2, qDot3, qDot4;
// Rate of change of quaternion from gyroscope
orientationChangeFromGyro (q0, q1, q2, q3, gx, gy, gz, qDot1, qDot2, qDot3, qDot4);
// Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)
if (!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f)))
{
// Normalise accelerometer measurement
normalizeVectorOpt(ax, ay, az);
// Gradient decent algorithm corrective step
s0 = 0.0; s1 = 0.0; s2 = 0.0; s3 = 0.0;
//case WorldFrame::ENU:
// Gravity: [0, 0, 1]
addGradientDescentStep(q0, q1, q2, q3, 0.0, 0.0, 2.0, ax, ay, az, s0, s1, s2, s3);
normalizeQuaternion(s0, s1, s2, s3);
// Apply feedback step
qDot1 -= gain_ * s0;
qDot2 -= gain_ * s1;
qDot3 -= gain_ * s2;
qDot4 -= gain_ * s3;
}
// Integrate rate of change of quaternion to yield quaternion
if(dt <= 0.0)
{
UWARN("dt=%f <=0.0, orientation will not be updated!", dt);
return;
}
q0 += qDot1 * dt;
q1 += qDot2 * dt;
q2 += qDot3 * dt;
q3 += qDot4 * dt;
//printf("%fs %f %f %f %f\n", dt, q0, q1, q2, q3);
// Normalise quaternion
normalizeQuaternion (q0, q1, q2, q3);
}
}
| 26.206044 | 105 | 0.609393 | [
"vector",
"transform"
] |
dc5ae366e477b844bbe1bb0a8107231d6c9af280 | 6,589 | cpp | C++ | Scripts/out/pybind11-module/bakkesmod/wrappers/canvaswrapper.cpp | Stanbroek/BakkesModSDK-Python | e9f977dbf1d39bbcb445731c2889749fe0c485c8 | [
"MIT"
] | 3 | 2021-09-08T06:08:13.000Z | 2022-01-29T23:24:00.000Z | Scripts/out/pybind11-module/bakkesmod/wrappers/canvaswrapper.cpp | Stanbroek/BakkesModSDK-Python | e9f977dbf1d39bbcb445731c2889749fe0c485c8 | [
"MIT"
] | null | null | null | Scripts/out/pybind11-module/bakkesmod/wrappers/canvaswrapper.cpp | Stanbroek/BakkesModSDK-Python | e9f977dbf1d39bbcb445731c2889749fe0c485c8 | [
"MIT"
] | null | null | null | void bind_canvaswrapper(pybind11::module& m)
{
pybind11::class_<CanvasWrapper, std::shared_ptr<CanvasWrapper>> cl_CanvasWrapper(m, "CanvasWrapper");
cl_CanvasWrapper.def(pybind11::init<uintptr_t>(), pybind11::arg("mem"));
cl_CanvasWrapper.def(pybind11::init<CanvasWrapper const &>(), pybind11::arg("other"));
// cl_CanvasWrapper.def(pybind11::del<>());
cl_CanvasWrapper.def("SetPosition", [](CanvasWrapper& cls_, Vector2F pos) { return cls_.SetPosition(pos); }, pybind11::arg("pos"));
cl_CanvasWrapper.def("GetPositionFloat", [](CanvasWrapper& cls_) { return cls_.GetPositionFloat(); });
cl_CanvasWrapper.def("SetColor", [](CanvasWrapper& cls_, char Red, char Green, char Blue, char Alpha) { return cls_.SetColor(Red, Green, Blue, Alpha); }, pybind11::arg("Red"), pybind11::arg("Green"), pybind11::arg("Blue"), pybind11::arg("Alpha"));
cl_CanvasWrapper.def("SetColor", [](CanvasWrapper& cls_, LinearColor color) { return cls_.SetColor(color); }, pybind11::arg("color"));
cl_CanvasWrapper.def("GetColor", [](CanvasWrapper& cls_) { return cls_.GetColor(); });
cl_CanvasWrapper.def("DrawBox", [](CanvasWrapper& cls_, Vector2F size) { return cls_.DrawBox(size); }, pybind11::arg("size"));
cl_CanvasWrapper.def("FillBox", [](CanvasWrapper& cls_, Vector2F size) { return cls_.FillBox(size); }, pybind11::arg("size"));
cl_CanvasWrapper.def("FillTriangle", [](CanvasWrapper& cls_, Vector2F p1, Vector2F p2, Vector2F p3) { return cls_.FillTriangle(p1, p2, p3); }, pybind11::arg("p1"), pybind11::arg("p2"), pybind11::arg("p3"));
cl_CanvasWrapper.def("FillTriangle", [](CanvasWrapper& cls_, Vector2F p1, Vector2F p2, Vector2F p3, LinearColor color) { return cls_.FillTriangle(p1, p2, p3, color); }, pybind11::arg("p1"), pybind11::arg("p2"), pybind11::arg("p3"), pybind11::arg("color"));
cl_CanvasWrapper.def("DrawString", [](CanvasWrapper& cls_, std::string text) { return cls_.DrawString(text); }, pybind11::arg("text"));
cl_CanvasWrapper.def("DrawString", [](CanvasWrapper& cls_, std::string text, float xScale, float yScale) { return cls_.DrawString(text, xScale, yScale); }, pybind11::arg("text"), pybind11::arg("xScale"), pybind11::arg("yScale"));
cl_CanvasWrapper.def("DrawString", [](CanvasWrapper& cls_, std::string text, float xScale, float yScale, bool dropShadow, bool wrapText=false) { return cls_.DrawString(text, xScale, yScale, dropShadow, wrapText); }, pybind11::arg("text"), pybind11::arg("xScale"), pybind11::arg("yScale"), pybind11::arg("dropShadow"), pybind11::arg("wrapText"));
cl_CanvasWrapper.def("GetStringSize", [](CanvasWrapper& cls_, std::string text, float xScale=1, float yScale=1) { return cls_.GetStringSize(text, xScale, yScale); }, pybind11::arg("text"), pybind11::arg("xScale"), pybind11::arg("yScale"));
cl_CanvasWrapper.def("DrawLine", [](CanvasWrapper& cls_, Vector2F start, Vector2F end) { return cls_.DrawLine(start, end); }, pybind11::arg("start"), pybind11::arg("end"));
cl_CanvasWrapper.def("DrawLine", [](CanvasWrapper& cls_, Vector2F start, Vector2F end, float width) { return cls_.DrawLine(start, end, width); }, pybind11::arg("start"), pybind11::arg("end"), pybind11::arg("width"));
cl_CanvasWrapper.def("DrawRect", [](CanvasWrapper& cls_, Vector2F start, Vector2F end) { return cls_.DrawRect(start, end); }, pybind11::arg("start"), pybind11::arg("end"));
cl_CanvasWrapper.def("DrawTexture", [](CanvasWrapper& cls_, ImageWrapper * img, float scale) { return cls_.DrawTexture(img, scale); }, pybind11::arg("img"), pybind11::arg("scale"));
cl_CanvasWrapper.def("DrawRect", [](CanvasWrapper& cls_, float RectX, float RectY, ImageWrapper * img) { return cls_.DrawRect(RectX, RectY, img); }, pybind11::arg("RectX"), pybind11::arg("RectY"), pybind11::arg("img"));
cl_CanvasWrapper.def("DrawTile", [](CanvasWrapper& cls_, ImageWrapper * img, float XL, float YL, float U, float V, float UL, float VL, LinearColor Color, unsigned int ClipTile, unsigned char Blend) { return cls_.DrawTile(img, XL, YL, U, V, UL, VL, Color, ClipTile, Blend); }, pybind11::arg("img"), pybind11::arg("XL"), pybind11::arg("YL"), pybind11::arg("U"), pybind11::arg("V"), pybind11::arg("UL"), pybind11::arg("VL"), pybind11::arg("Color"), pybind11::arg("ClipTile"), pybind11::arg("Blend"));
cl_CanvasWrapper.def("DrawRotatedTile", [](CanvasWrapper& cls_, ImageWrapper * img, Rotator & Rotation, float XL, float YL, float U, float V, float UL, float VL, float AnchorX, float AnchorY) { return cls_.DrawRotatedTile(img, Rotation, XL, YL, U, V, UL, VL, AnchorX, AnchorY); }, pybind11::arg("img"), pybind11::arg("Rotation"), pybind11::arg("XL"), pybind11::arg("YL"), pybind11::arg("U"), pybind11::arg("V"), pybind11::arg("UL"), pybind11::arg("VL"), pybind11::arg("AnchorX"), pybind11::arg("AnchorY"));
cl_CanvasWrapper.def("SetPosition", [](CanvasWrapper& cls_, Vector2 pos) { return cls_.SetPosition(pos); }, pybind11::arg("pos"));
cl_CanvasWrapper.def("GetPosition", [](CanvasWrapper& cls_) { return cls_.GetPosition(); });
cl_CanvasWrapper.def("DrawBox", [](CanvasWrapper& cls_, Vector2 size) { return cls_.DrawBox(size); }, pybind11::arg("size"));
cl_CanvasWrapper.def("FillBox", [](CanvasWrapper& cls_, Vector2 size) { return cls_.FillBox(size); }, pybind11::arg("size"));
cl_CanvasWrapper.def("FillTriangle", [](CanvasWrapper& cls_, Vector2 p1, Vector2 p2, Vector2 p3) { return cls_.FillTriangle(p1, p2, p3); }, pybind11::arg("p1"), pybind11::arg("p2"), pybind11::arg("p3"));
cl_CanvasWrapper.def("FillTriangle", [](CanvasWrapper& cls_, Vector2 p1, Vector2 p2, Vector2 p3, LinearColor color) { return cls_.FillTriangle(p1, p2, p3, color); }, pybind11::arg("p1"), pybind11::arg("p2"), pybind11::arg("p3"), pybind11::arg("color"));
cl_CanvasWrapper.def("DrawLine", [](CanvasWrapper& cls_, Vector2 start, Vector2 end) { return cls_.DrawLine(start, end); }, pybind11::arg("start"), pybind11::arg("end"));
cl_CanvasWrapper.def("DrawLine", [](CanvasWrapper& cls_, Vector2 start, Vector2 end, float width) { return cls_.DrawLine(start, end, width); }, pybind11::arg("start"), pybind11::arg("end"), pybind11::arg("width"));
cl_CanvasWrapper.def("DrawRect", [](CanvasWrapper& cls_, Vector2 start, Vector2 end) { return cls_.DrawRect(start, end); }, pybind11::arg("start"), pybind11::arg("end"));
cl_CanvasWrapper.def("Project", [](CanvasWrapper& cls_, Vector location) { return cls_.Project(location); }, pybind11::arg("location"));
cl_CanvasWrapper.def("ProjectF", [](CanvasWrapper& cls_, Vector location) { return cls_.ProjectF(location); }, pybind11::arg("location"));
cl_CanvasWrapper.def("GetSize", [](CanvasWrapper& cls_) { return cls_.GetSize(); });
}
| 160.707317 | 507 | 0.711034 | [
"vector"
] |
dc60183c1d61e51e12fda81f865cb583a4de053c | 1,909 | hh | C++ | inc/Scena.hh | KPO-2020-2021/zad5_2-KrystianCyga | 95b0b64bea1320126b59e2d0f6aee36b817a53b5 | [
"Unlicense"
] | null | null | null | inc/Scena.hh | KPO-2020-2021/zad5_2-KrystianCyga | 95b0b64bea1320126b59e2d0f6aee36b817a53b5 | [
"Unlicense"
] | null | null | null | inc/Scena.hh | KPO-2020-2021/zad5_2-KrystianCyga | 95b0b64bea1320126b59e2d0f6aee36b817a53b5 | [
"Unlicense"
] | null | null | null | #pragma once
#include "../inc/stozek.hh"
#include "../inc/wyzyna.hh"
#include "../inc/gran_bryla.hh"
#include "../inc/dron.hh"
#include "../inc/Obiekt.hh"
#include "../inc/brylageo.hh"
#include <string>
#include <list>
#include <vector>
#include <iostream>
#include <memory>
/*!
* \file
* \brief Ten plik zawiera definicję klasy Scena
*/
class Scena
{
std::vector<Dron> Drony;
std::list<std::shared_ptr<Obiekt>> Przeszkody;
unsigned int liczba_dronow = 0;
public:
/*!
* \brief Pobiera od uzytkownika trase lotu
*
*
* \param[in] numer_drona - numer drona
* \param[in] Lacze - Lacze do GNUplota
* \retval true - gdy operacja powiedzie sie
* \retval false - gdy operacja nie powiedzie sie
*/
bool wybierz_drona(int numer_drona, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Zapisuje drona
*
*
* \param[in] numer_drona - numer drona
* \param[in] polozenie - polozenie startu drona
* \retval true - gdy operacja powiedzie sie
* \retval false - gdy operacja nie powiedzie sie
*/
bool Zapis_drona(unsigned int numer_drona, vector3d &polozenie);
/*!
* \brief Uruchamia lot danego drona
*
* \param[in] numer_drona - numer drona
* \param[in] kat - kat lotu
* \param[in] odleglosc - dlugosc lotu
* \param[in] Lacze - Lacze do GNUplota
* \retval true - gdy operacja powiedzie sie
* \retval false - gdy operacja nie powiedzie sie
*/
bool Uzyj_drona( int numer_drona, double kat, unsigned int odleglosc, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Menu Programu
*
* \retval int numer drona
* \retval -1 - koniec programu
*/
int Menu(PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Pozwala na dodanie przeszkody
*
*
* \param[in] Lacze - Lacze do GNUplota
*/
void Dodaj_Przeszkody(PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Pozwala na usuniecie przeszkody
*
*
* \param[in] Lacze - Lacze do GNUplota
*/
void Usun_Przeszkody(PzG::LaczeDoGNUPlota &Lacze);
}; | 23.567901 | 101 | 0.686223 | [
"vector"
] |
dc683a81b703d7c9530d7803175140b7ff74845e | 1,425 | hpp | C++ | Artifical_intelligence/DuckHuntPerfect/GameServer.hpp | jiwidi/KTH-Erasmus | a32908fcd6d0229b649e6498695f05acf095dd77 | [
"MIT"
] | null | null | null | Artifical_intelligence/DuckHuntPerfect/GameServer.hpp | jiwidi/KTH-Erasmus | a32908fcd6d0229b649e6498695f05acf095dd77 | [
"MIT"
] | null | null | null | Artifical_intelligence/DuckHuntPerfect/GameServer.hpp | jiwidi/KTH-Erasmus | a32908fcd6d0229b649e6498695f05acf095dd77 | [
"MIT"
] | null | null | null | #ifndef _DUCKS_GAMESERVER_HPP_
#define _DUCKS_GAMESERVER_HPP_
#include "Deadline.hpp"
#include "Bird.hpp"
#include <vector>
#include <memory>
#include <iostream>
namespace ducks
{
class GameServer
{
struct SPlayer
{
SPlayer(std::istream &pInputStream, std::ostream &pOutputStream, int pID);
std::istream *mInputStream;
std::ostream *mOutputStream;
int mID;
int mNumSent;
int mScore;
bool mGameOver;
};
struct BirdSequence
{
ESpecies mSpecies;
std::vector<EMovement> mActions;
};
typedef std::vector<BirdSequence> Round;
public:
GameServer(std::istream &pInputStream, std::ostream &pOutputStream);
void load(std::istream &pStream);
void run();
void writeObservations(std::ostream &os);
private:
void sendRound(SPlayer &pPlayer, int pRound);
void sendBirds(SPlayer &pPlayer);
void sendScores(SPlayer &pPlayer);
void playerShoot(SPlayer &pPlayer);
void playerGuess(SPlayer &pPlayer);
void removePlayer(SPlayer &pPlayer);
int playersLeft();
private:
int mMaxRounds;
int mMaxTurns;
int64_t mTimeForShoot;
int64_t mTimeForHit;
int64_t mTimeForGuess;
int64_t mTimeForReveal;
std::vector<SPlayer> mPlayers;
std::vector<Round> mEnvironment;
std::vector<Bird> mBirds;
std::vector<ESpecies> mBirdSpecies;
};
} /*namespace ducks*/
#endif
| 20.357143 | 82 | 0.673684 | [
"vector"
] |
dc6b1f38fb6166b8969ce44e9ada35b25f69f19e | 10,668 | cpp | C++ | src/tools/s2wasm.cpp | erandis-vol/binaryen | a076437c8971aca7e2d3756cac57475433e0af12 | [
"Apache-2.0"
] | 1 | 2021-04-22T10:00:46.000Z | 2021-04-22T10:00:46.000Z | src/tools/s2wasm.cpp | erandis-vol/binaryen | a076437c8971aca7e2d3756cac57475433e0af12 | [
"Apache-2.0"
] | null | null | null | src/tools/s2wasm.cpp | erandis-vol/binaryen | a076437c8971aca7e2d3756cac57475433e0af12 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 WebAssembly Community Group participants
*
* 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.
*/
//
// s2wasm console tool
//
#include <exception>
#include "ir/trapping.h"
#include "support/colors.h"
#include "support/command-line.h"
#include "support/file.h"
#include "s2wasm.h"
#include "wasm-emscripten.h"
#include "wasm-io.h"
#include "wasm-linker.h"
#include "wasm-printing.h"
#include "wasm-validator.h"
using namespace cashew;
using namespace wasm;
int main(int argc, const char *argv[]) {
bool ignoreUnknownSymbols = false;
bool generateEmscriptenGlue = false;
bool allowMemoryGrowth = false;
bool importMemory = false;
bool emitBinary = false;
bool debugInfo = false;
std::string startFunction;
std::string sourceMapFilename;
std::string sourceMapUrl;
std::string symbolMap;
std::vector<std::string> archiveLibraries;
TrapMode trapMode = TrapMode::Allow;
unsigned numReservedFunctionPointers = 0;
Options options("s2wasm", "Link .s file into .wast");
options.extra["validate"] = "wasm";
options
.add("--output", "-o", "Output file (stdout if not specified)",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["output"] = argument;
Colors::disable();
})
.add("--ignore-unknown", "", "Ignore unknown symbols",
Options::Arguments::Zero,
[&ignoreUnknownSymbols](Options *, const std::string& ) {
ignoreUnknownSymbols = true;
})
.add("--start", "", "Generate the start method (default: main)",
Options::Arguments::Optional,
[&startFunction](Options *, const std::string& argument) {
startFunction = argument.size() ? argument : "main";
})
.add("--global-base", "", "Where to start to place globals",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["global-base"] = argument;
})
.add("--allocate-stack", "-s", "Size of the user stack in linear memory",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["stack-allocation"] = argument;
})
.add("--initial-memory", "-i", "Initial size of the linear memory",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["initial-memory"] = argument;
})
.add("--max-memory", "-m", "Maximum size of the linear memory",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["max-memory"] = argument;
})
.add("--allow-memory-growth", "", "Allow linear memory to grow at runtime",
Options::Arguments::Zero,
[&allowMemoryGrowth](Options *, const std::string& ) {
allowMemoryGrowth = true;
})
.add("--trap-mode", "",
"Strategy for handling potentially trapping instructions. Valid "
"values are \"allow\", \"js\", and \"clamp\"",
Options::Arguments::One,
[&trapMode](Options *o, const std::string& argument) {
try {
trapMode = trapModeFromString(argument);
} catch (std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << "\n";
exit(EXIT_FAILURE);
}
})
.add("--emscripten-glue", "-e", "Generate emscripten glue",
Options::Arguments::Zero,
[&generateEmscriptenGlue](Options *, const std::string& ) {
generateEmscriptenGlue = true;
})
.add("--import-memory", "", "Import the linear memory instead of exporting it",
Options::Arguments::Zero,
[&importMemory](Options *, const std::string& ) {
importMemory = true;
})
.add("--library", "-l", "Add archive library",
Options::Arguments::N,
[&archiveLibraries](Options *o, const std::string& argument) {
archiveLibraries.push_back(argument);
})
.add("--validate", "-v", "Control validation of the output module",
Options::Arguments::One,
[](Options *o, const std::string& argument) {
if (argument != "web" && argument != "none" && argument != "wasm") {
std::cerr << "Valid arguments for --validate flag are 'wasm', 'web' and 'none'.\n";
exit(1);
}
o->extra["validate"] = argument;
})
.add("--emscripten-reserved-function-pointers", "",
"Number of reserved function pointers for emscripten addFunction "
"support",
Options::Arguments::One,
[&numReservedFunctionPointers](Options *o,
const std::string &argument) {
numReservedFunctionPointers = std::stoi(argument);
})
.add("--emit-binary", "",
"Emit binary instead of text for the output file",
Options::Arguments::Zero,
[&emitBinary](Options *, const std::string &) {
emitBinary = true;
})
.add("--debuginfo", "-g",
"Emit names section in wasm binary (or full debuginfo in wast)",
Options::Arguments::Zero,
[&debugInfo](Options *, const std::string &) {
debugInfo = true;
})
.add("--source-map", "-sm",
"Emit source map (if using binary output) to the specified file",
Options::Arguments::One,
[&sourceMapFilename](Options *, const std::string& argument) {
sourceMapFilename = argument;
})
.add("--source-map-url", "-su",
"Use specified string as source map URL",
Options::Arguments::One,
[&sourceMapUrl](Options *, const std::string& argument) {
sourceMapUrl = argument;
})
.add("--symbolmap", "-s",
"Emit a symbol map (indexes => names)",
Options::Arguments::One,
[&symbolMap](Options *, const std::string& argument) {
symbolMap = argument;
})
.add_positional("INFILE", Options::Arguments::One,
[](Options *o, const std::string& argument) {
o->extra["infile"] = argument;
});
options.parse(argc, argv);
if (options.extra["output"].size() == 0) {
// when no output file is specified, we emit text to stdout
emitBinary = false;
}
if (allowMemoryGrowth && !generateEmscriptenGlue) {
Fatal() << "Error: adding memory growth code without Emscripten glue. "
"This doesn't do anything.\n";
}
auto debugFlag = options.debug ? Flags::Debug : Flags::Release;
auto input(read_file<std::string>(options.extra["infile"], Flags::Text, debugFlag));
if (options.debug) std::cerr << "Parsing and wasming..." << std::endl;
uint64_t globalBase = options.extra.find("global-base") != options.extra.end()
? std::stoull(options.extra["global-base"])
: 0;
uint64_t stackAllocation =
options.extra.find("stack-allocation") != options.extra.end()
? std::stoull(options.extra["stack-allocation"])
: 0;
uint64_t initialMem =
options.extra.find("initial-memory") != options.extra.end()
? std::stoull(options.extra["initial-memory"])
: 0;
uint64_t maxMem =
options.extra.find("max-memory") != options.extra.end()
? std::stoull(options.extra["max-memory"])
: 0;
if (options.debug) std::cerr << "Global base " << globalBase << '\n';
Linker linker(globalBase, stackAllocation, initialMem, maxMem,
importMemory || generateEmscriptenGlue, ignoreUnknownSymbols, startFunction,
options.debug);
S2WasmBuilder mainbuilder(input.c_str(), options.debug);
linker.linkObject(mainbuilder);
if (trapMode != TrapMode::Allow) {
Module* wasm = &(linker.getOutput().wasm);
PassRunner runner(wasm);
addTrapModePass(runner, trapMode);
runner.run();
}
for (const auto& m : archiveLibraries) {
auto archiveFile(read_file<std::vector<char>>(m, Flags::Binary, debugFlag));
bool error;
Archive lib(archiveFile, error);
if (error) Fatal() << "Error opening archive " << m << "\n";
linker.linkArchive(lib);
}
linker.layout();
std::string metadata;
Module& wasm = linker.getOutput().wasm;
if (generateEmscriptenGlue) {
if (options.debug) {
std::cerr << "Emscripten gluing..." << std::endl;
WasmPrinter::printModule(&wasm, std::cerr);
}
metadata = emscriptenGlue(
wasm,
allowMemoryGrowth,
linker.getStackPointerAddress(),
linker.getStaticBump(),
linker.getOutput().getInitializerFunctions(),
numReservedFunctionPointers);
}
if (options.extra["validate"] != "none") {
if (options.debug) std::cerr << "Validating..." << std::endl;
if (!wasm::WasmValidator().validate(wasm,
WasmValidator::Globally | (options.extra["validate"] == "web" ? WasmValidator::Web : 0))) {
WasmPrinter::printModule(&wasm);
Fatal() << "Error: linked module is not valid.\n";
}
}
if (options.debug) std::cerr << "Printing..." << std::endl;
auto outputDebugFlag = options.debug ? Flags::Debug : Flags::Release;
auto outputBinaryFlag = emitBinary ? Flags::Binary : Flags::Text;
Output output(options.extra["output"], outputBinaryFlag, outputDebugFlag);
ModuleWriter writer;
writer.setDebug(options.debug);
writer.setDebugInfo(debugInfo);
writer.setSymbolMap(symbolMap);
writer.setBinary(emitBinary);
if (emitBinary) {
writer.setSourceMapFilename(sourceMapFilename);
writer.setSourceMapUrl(sourceMapUrl);
}
writer.write(wasm, output);
if (generateEmscriptenGlue) {
if (emitBinary) {
std::cout << metadata;
} else {
output << ";; METADATA: " << metadata;
}
}
if (options.debug) std::cerr << "Done." << std::endl;
return 0;
}
| 37.829787 | 100 | 0.589426 | [
"vector"
] |
dc6be7bcecabaf6114d81882f17b6d3d4b58145a | 4,716 | cpp | C++ | moveit_setup_assistant/src/tools/rotated_header_view.cpp | Bhavam/moveit | 6b56cd68d76ae29d1ceb255d06be35543dd3f830 | [
"BSD-3-Clause"
] | 1,116 | 2016-07-29T06:39:49.000Z | 2022-03-31T08:42:14.000Z | moveit_setup_assistant/src/tools/rotated_header_view.cpp | Bhavam/moveit | 6b56cd68d76ae29d1ceb255d06be35543dd3f830 | [
"BSD-3-Clause"
] | 2,784 | 2016-07-29T15:19:38.000Z | 2022-03-31T01:35:59.000Z | moveit_setup_assistant/src/tools/rotated_header_view.cpp | Bhavam/moveit | 6b56cd68d76ae29d1ceb255d06be35543dd3f830 | [
"BSD-3-Clause"
] | 956 | 2016-07-30T17:03:44.000Z | 2022-03-31T15:48:31.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, CITEC, Bielefeld University
* 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 Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Robert Haschke */
#include "rotated_header_view.h"
#include <QPainter>
namespace moveit_setup_assistant
{
RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent) : QHeaderView(orientation, parent)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
setSectionsClickable(true);
setSectionResizeMode(Fixed);
#else
setClickable(true);
setResizeMode(Fixed);
#endif
setDefaultSectionSize(27);
}
void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
if (orientation() == Qt::Vertical)
{
QHeaderView::paintSection(painter, rect, logicalIndex);
return;
}
painter->save();
// rotate about (x,y)
painter->translate(rect.x(), rect.y());
painter->rotate(-90);
painter->translate(-rect.height(), 0);
QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
painter->restore();
}
QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const
{
if (orientation() == Qt::Vertical)
return QHeaderView::sectionSizeFromContents(logicalIndex);
Q_ASSERT(logicalIndex >= 0);
ensurePolished();
// use SizeHintRole
QVariant variant = model()->headerData(logicalIndex, Qt::Vertical, Qt::SizeHintRole);
if (variant.isValid())
return qvariant_cast<QSize>(variant);
// otherwise use the contents
QStyleOptionHeader opt;
initStyleOption(&opt);
opt.section = logicalIndex;
QVariant var = model()->headerData(logicalIndex, orientation(), Qt::FontRole);
QFont fnt;
if (var.isValid() && var.canConvert<QFont>())
fnt = qvariant_cast<QFont>(var);
else
fnt = font();
fnt.setBold(true);
opt.fontMetrics = QFontMetrics(fnt);
opt.text = model()->headerData(logicalIndex, orientation(), Qt::DisplayRole).toString();
variant = model()->headerData(logicalIndex, orientation(), Qt::DecorationRole);
opt.icon = qvariant_cast<QIcon>(variant);
if (opt.icon.isNull())
opt.icon = qvariant_cast<QPixmap>(variant);
QSize size = style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this);
if (isSortIndicatorShown())
{
int margin = style()->pixelMetric(QStyle::PM_HeaderMargin, &opt, this);
if (orientation() == Qt::Horizontal)
size.rwidth() += size.height() + margin;
else
size.rheight() += size.width() + margin;
}
return QSize(size.height(), size.width());
}
int RotatedHeaderView::sectionSizeHint(int logicalIndex) const
{
if (isSectionHidden(logicalIndex))
return 0;
if (logicalIndex < 0 || logicalIndex >= count())
return -1;
QSize size;
QVariant value = model()->headerData(logicalIndex, orientation(), Qt::SizeHintRole);
if (value.isValid())
size = qvariant_cast<QSize>(value);
else
size = sectionSizeFromContents(logicalIndex);
int hint = size.height();
return qMax(minimumSectionSize(), hint);
}
} // namespace moveit_setup_assistant
| 36.276923 | 117 | 0.700806 | [
"model"
] |
dc6ef097b6a45729584fbf90bdde9aaf563124e6 | 22,812 | cpp | C++ | src/prod/src/Common/SecurityPrincipalHelper.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Common/SecurityPrincipalHelper.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Common/SecurityPrincipalHelper.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
StringLiteral const TraceSecurityPrincipalHelper("SecurityPrincipalHelper");
#if !defined(PLATFORM_UNIX)
ErrorCode SecurityPrincipalHelper::AddMemberToLocalGroup(wstring const & parentGroup, wstring const & memberToAdd)
{
LOCALGROUP_MEMBERS_INFO_3 groupMembership;
::ZeroMemory(&groupMembership, sizeof(groupMembership));
groupMembership.lgrmi3_domainandname = const_cast<LPWSTR>(memberToAdd.c_str());
NET_API_STATUS nStatus = ::NetLocalGroupAddMembers(
NULL,
parentGroup.c_str(),
3 /*LOCALGROUP_MEMBERS_INFO level*/,
reinterpret_cast<LPBYTE>(&groupMembership),
1 /*user count*/);
if (nStatus != NERR_Success)
{
ErrorCode error;
if (nStatus == NERR_GroupNotFound)
{
error = ErrorCode(ErrorCodeValue::NotFound);
}
else if (nStatus == ERROR_MEMBER_IN_ALIAS)
{
error = ErrorCode(ErrorCodeValue::AlreadyExists);
}
else
{
error = ErrorCode::FromWin32Error(nStatus);
}
WriteTrace(
error.IsError(ErrorCodeValue::AlreadyExists) ? LogLevel::Noise : LogLevel::Warning,
TraceSecurityPrincipalHelper,
"Error adding user account {0} to group {1}: status={2}, error={3}",
memberToAdd,
parentGroup,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::RemoveMemberFromLocalGroup(std::wstring const & parentGroupAccountName, std::wstring const & memberToRemoveAccountName)
{
LOCALGROUP_MEMBERS_INFO_3 groupMembership;
::ZeroMemory(&groupMembership, sizeof(groupMembership));
groupMembership.lgrmi3_domainandname = const_cast<LPWSTR>(memberToRemoveAccountName.c_str());
NET_API_STATUS nStatus = ::NetLocalGroupDelMembers(
NULL,
parentGroupAccountName.c_str(),
3 /*LOCALGROUP_MEMBERS_INFO level*/,
reinterpret_cast<LPBYTE>(&groupMembership),
1 /*user count*/);
if (nStatus != NERR_Success)
{
ErrorCode error;
if (nStatus == NERR_GroupNotFound)
{
error = ErrorCode(ErrorCodeValue::NotFound);
}
else
{
error = ErrorCode::FromWin32Error(nStatus);
}
WriteWarning(
TraceSecurityPrincipalHelper,
"Error removing user account {0} from group {1}: status={2}, error={3}",
memberToRemoveAccountName,
parentGroupAccountName,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
#endif
ErrorCode SecurityPrincipalHelper::SetLocalGroupMembers(wstring const & groupName, vector<PSID> const & membersToSet)
{
vector<LOCALGROUP_MEMBERS_INFO_0> members;
DWORD totalEntries = 0;
for (auto iter = membersToSet.begin(); iter != membersToSet.end(); iter++)
{
LOCALGROUP_MEMBERS_INFO_0 memberInfo;
::ZeroMemory(&memberInfo, sizeof(memberInfo));
memberInfo.lgrmi0_sid = *iter;
members.push_back(memberInfo);
totalEntries++;
}
DWORD win32Error = ::NetLocalGroupSetMembers(
NULL,
groupName.c_str(),
0,
reinterpret_cast<LPBYTE>(members.data()),
totalEntries);
return ErrorCode::TraceReturn(
ErrorCode::FromWin32Error(win32Error),
TraceTaskCodes::Common,
TraceSecurityPrincipalHelper,
"SetLocalGroupMembers");
}
#if !defined(PLATFORM_UNIX)
ErrorCode SecurityPrincipalHelper::CreateUserAccount(wstring const & accountName, wstring const & password, wstring const & comment)
{
USER_INFO_4 userInfo;
::ZeroMemory(&userInfo, sizeof(userInfo));
userInfo.usri4_name = const_cast<LPWSTR>(accountName.c_str());
userInfo.usri4_password = const_cast<LPWSTR>(password.c_str());
userInfo.usri4_comment = const_cast<LPWSTR>(comment.c_str());
userInfo.usri4_flags =
UF_SCRIPT | UF_PASSWD_CANT_CHANGE | UF_DONT_EXPIRE_PASSWD | UF_NOT_DELEGATED | UF_NORMAL_ACCOUNT;
userInfo.usri4_acct_expires = TIMEQ_FOREVER;
userInfo.usri4_primary_group_id = DOMAIN_GROUP_RID_USERS;
ErrorCode error(ErrorCodeValue::Success);
NET_API_STATUS nStatus = ::NetUserAdd(NULL, 4 /* USER_INFO level*/, reinterpret_cast<LPBYTE>(&userInfo), NULL);
if (nStatus != NERR_Success)
{
if(nStatus == NERR_UserExists || nStatus == NERR_GroupExists || nStatus == ERROR_ALIAS_EXISTS)
{
error = ErrorCode(ErrorCodeValue::AlreadyExists);
}
else
{
error = ErrorCode::FromWin32Error(nStatus);
}
WriteWarning(
TraceSecurityPrincipalHelper,
"Error creating user account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::DeleteUserProfile(wstring const & accountName, SidSPtr const& sid)
{
wstring sidString;
ErrorCode error;
if(!sid)
{
SidSPtr tempSid;
error = BufferedSid::CreateSPtr(accountName, tempSid);
if (!error.IsSuccess())
{
WriteWarning(
TraceSecurityPrincipalHelper,
"GetSid for account {0} failed with {1}",
accountName,
error);
return error;
}
error = tempSid->ToString(sidString);
}
else
{
error = sid->ToString(sidString);
}
if(!error.IsSuccess())
{
WriteWarning(
TraceSecurityPrincipalHelper,
"sidUPtr->ToString for account {0} failed with {1}",
accountName,
error);
return error;
}
if (!::DeleteProfile(sidString.c_str(), NULL, NULL))
{
DWORD nStatus = ::GetLastError();
if (nStatus == ERROR_FILE_NOT_FOUND)
{
// If the profile doesn't exist, consider DeleteProfile successful
WriteNoise(
TraceSecurityPrincipalHelper,
"User profile doesn't exist: Account={0}, sid={1}",
accountName,
sidString);
error = ErrorCode::Success();
}
else
{
error = ErrorCode::FromWin32Error(nStatus);
// ERROR_INVALID_PARAMETER happens if the profile is still used by other handles
// (eg. host processes not terminated)
WriteWarning(
TraceSecurityPrincipalHelper,
"Error deleting user profile: Account={0}, sid={1}, status={2}, error={3}",
accountName,
sidString,
nStatus,
error);
return error;
}
}
return error;
}
ErrorCode SecurityPrincipalHelper::DeleteUserAccount(wstring const & accountName)
{
NET_API_STATUS nStatus = ::NetUserDel(L".", accountName.c_str());
if (nStatus != NERR_Success)
{
if(nStatus == NERR_UserNotFound)
{
WriteInfo(
TraceSecurityPrincipalHelper,
"Deleting user account {0} failed with NERR_UserNotFound",
accountName);
return ErrorCode(ErrorCodeValue::NotFound);
}
else
{
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error deleting user account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::DeleteUserAccountIgnoreDeleteProfileError(wstring const & accountName, Common::SidSPtr const& sid)
{
ErrorCode error = DeleteUserProfile(accountName, sid);
error.ReadValue();// Ignore delete profile error.
NET_API_STATUS nStatus = ::NetUserDel(L".", accountName.c_str());
if (nStatus != NERR_Success)
{
if(nStatus == NERR_UserNotFound)
{
WriteInfo(
TraceSecurityPrincipalHelper,
"Deleting user account {0} failed with NERR_UserNotFound",
accountName);
return ErrorCode(ErrorCodeValue::NotFound);
}
else
{
error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error deleting user account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::CreateGroupAccount(wstring const & groupName, wstring const & comment)
{
LOCALGROUP_INFO_1 groupInfo;
groupInfo.lgrpi1_name = const_cast<LPWSTR>(groupName.c_str());
groupInfo.lgrpi1_comment = const_cast<LPWSTR>(comment.c_str());
NET_API_STATUS nStatus = ::NetLocalGroupAdd(
NULL,
1 /* Information level */,
reinterpret_cast<LPBYTE>(&groupInfo),
NULL);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_ALIAS_EXISTS || nStatus == NERR_GroupExists || nStatus == NERR_UserExists)
{
return ErrorCode(ErrorCodeValue::AlreadyExists);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error creating group account {0}: status={1}, error={2}",
groupName,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::GetMembers(wstring const & accountName, __out vector<wstring> & members)
{
PLOCALGROUP_MEMBERS_INFO_1 localGroupMembersInfo = NULL;
DWORD entryReadCount = 0;
DWORD totalEntryCount = 0;
NET_API_STATUS nStatus = NetLocalGroupGetMembers(
NULL /*serverName*/,
accountName.c_str() /*accountName*/,
1 /*level*/,
(LPBYTE *) &localGroupMembersInfo,
MAX_PREFERRED_LENGTH,
&entryReadCount,
&totalEntryCount,
NULL);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_NO_SUCH_ALIAS || nStatus == NERR_GroupNotFound)
{
return ErrorCode(ErrorCodeValue::NotFound);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error getting group members for account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
if (localGroupMembersInfo != NULL)
{
PLOCALGROUP_MEMBERS_INFO_1 currentMembersInfo = localGroupMembersInfo;
for (DWORD i = 0; i < entryReadCount; ++i)
{
ASSERT_IF(currentMembersInfo == NULL, "Buffer shouldn't be null");
members.push_back(wstring(currentMembersInfo->lgrmi1_name));
++currentMembersInfo;
}
NetApiBufferFree(localGroupMembersInfo);
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::GetMembership(wstring const & accountName, __out vector<wstring> & memberOf)
{
LPLOCALGROUP_USERS_INFO_0 localGroupInfo = NULL;
DWORD entryReadCount = 0;
DWORD totalEntryCount = 0;
NET_API_STATUS nStatus = NetUserGetLocalGroups(
NULL /*serverName*/,
accountName.c_str() /*userName*/,
0 /*LOCAL_GROUP_USERS_INFO level*/,
LG_INCLUDE_INDIRECT,
(LPBYTE *) &localGroupInfo,
MAX_PREFERRED_LENGTH,
&entryReadCount,
&totalEntryCount);
if (nStatus != NERR_Success)
{
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error getting user account information for {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
if (localGroupInfo != NULL)
{
LPLOCALGROUP_USERS_INFO_0 currentGroupInfo = localGroupInfo;
for (DWORD i = 0; i < entryReadCount; ++i)
{
ASSERT_IF(currentGroupInfo == NULL, "Buffer shouldn't be null");
memberOf.push_back(wstring(currentGroupInfo->lgrui0_name));
++currentGroupInfo;
}
NetApiBufferFree(localGroupInfo);
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::DeleteGroupAccount(wstring const & groupName)
{
NET_API_STATUS nStatus = ::NetLocalGroupDel(L".", groupName.c_str());
if (nStatus != NERR_Success)
{
if(nStatus == NERR_GroupNotFound)
{
WriteInfo(
TraceSecurityPrincipalHelper,
"Deleting group account {0} failed with NERR_GroupNotFound",
groupName);
return ErrorCode(ErrorCodeValue::NotFound);
}
else
{
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error deleting group account {0}: status={1}, error={2}",
groupName,
nStatus,
error);
return error;
}
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::GetGroupComment(std::wstring const & accountName, __out wstring & comment)
{
// Get group info
PLOCALGROUP_INFO_1 groupInfo = NULL;
NET_API_STATUS nStatus = ::NetLocalGroupGetInfo(
NULL /*serverName*/,
accountName.c_str(),
1 /*LOCALGROUP_INFO level*/,
(LPBYTE*) &groupInfo);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_NO_SUCH_ALIAS || nStatus == NERR_GroupNotFound)
{
return ErrorCode(ErrorCodeValue::NotFound);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error getting group information for account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
ASSERT_IF(groupInfo == NULL, "groupInfo should not be null");
comment = wstring(groupInfo->lgrpi1_comment);
WriteNoise(
TraceSecurityPrincipalHelper,
"Group {0}: retrieved comment \"{1}\"",
accountName,
comment);
NetApiBufferFree(groupInfo);
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::GetUserComment(std::wstring const & accountName, __out wstring & comment)
{
// Get group info
LPUSER_INFO_1 userInfo = NULL;
NET_API_STATUS nStatus = ::NetUserGetInfo(
NULL /*serverName*/,
accountName.c_str(),
1 /*LOCALUSER_INFO level*/,
(LPBYTE*) &userInfo);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_NO_SUCH_ALIAS || nStatus == NERR_UserNotFound)
{
return ErrorCode(ErrorCodeValue::NotFound);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Error getting user information for account {0}: status={1}, error={2}",
accountName,
nStatus,
error);
return error;
}
ASSERT_IF(userInfo == NULL, "user info should not be null");
comment = wstring(userInfo->usri1_comment);
WriteNoise(
TraceSecurityPrincipalHelper,
"User {0}: retrieved comment \"{1}\"",
accountName,
comment);
NetApiBufferFree(userInfo);
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::UpdateUserComment(wstring const & accountName, wstring const & comment)
{
DWORD errorIndex;
USER_INFO_1007 commentUserInfo;
::ZeroMemory(&commentUserInfo, sizeof(commentUserInfo));
commentUserInfo.usri1007_comment = const_cast<LPWSTR>(comment.c_str());
NET_API_STATUS nStatus = NetUserSetInfo(
NULL /*serverName*/,
accountName.c_str(),
1007 /*LOCAL_GROUP_INFO level*/,
reinterpret_cast<LPBYTE>(&commentUserInfo),
&errorIndex);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_NO_SUCH_ALIAS || nStatus == NERR_UserNotFound)
{
return ErrorCode(ErrorCodeValue::NotFound);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Group {0}: Error updating user comment: newComment={1}, status={2}, error={3}",
accountName,
comment,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::UpdateGroupComment(wstring const & accountName, wstring const & comment)
{
DWORD errorIndex;
LOCALGROUP_INFO_1002 commentGroupInfo;
::ZeroMemory(&commentGroupInfo, sizeof(commentGroupInfo));
commentGroupInfo.lgrpi1002_comment = const_cast<LPWSTR>(comment.c_str());
NET_API_STATUS nStatus = NetLocalGroupSetInfo(
NULL /*serverName*/,
accountName.c_str(),
1002 /*LOCAL_GROUP_INFO level*/,
reinterpret_cast<LPBYTE>(&commentGroupInfo),
&errorIndex);
if (nStatus != NERR_Success)
{
if (nStatus == ERROR_NO_SUCH_ALIAS || nStatus == NERR_GroupNotFound)
{
return ErrorCode(ErrorCodeValue::NotFound);
}
auto error = ErrorCode::FromWin32Error(nStatus);
WriteWarning(
TraceSecurityPrincipalHelper,
"Group {0}: Error updating group comment: newComment={1}, status={2}, error={3}",
accountName,
comment,
nStatus,
error);
return error;
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode SecurityPrincipalHelper::AcquireMutex(wstring const& mutexName, __out MutexHandleUPtr & mutex)
{
mutex = MutexHandle::CreateUPtr(mutexName);
WriteNoise(TraceSecurityPrincipalHelper, "{0}: Wait for mutex", mutexName);
auto error = mutex->WaitOne();
if (!error.IsSuccess())
{
WriteTrace(
error.ToLogLevel(),
TraceSecurityPrincipalHelper,
"{0}: Error waiting for mutex: error={1}",
mutexName,
error);
}
return error;
}
wstring SecurityPrincipalHelper::GetMembershipString(vector<wstring> const& membership)
{
wstring membershipString(L"Membership = ");
StringWriter writer(membershipString);
for (auto it = membership.begin(); it != membership.end(); ++it)
{
if(it == membership.begin())
{
writer.Write("{0}", *it);
}
else
{
writer.Write(",{0}", *it);
}
}
return membershipString;
}
ErrorCode SecurityPrincipalHelper::DeleteUsersWithCommentPrefix(wstring const & prefix)
{
ErrorCode lastError(ErrorCodeValue::Success);
LPUSER_INFO_1 pBuff = NULL;
DWORD entriesRead = 0;
DWORD totalEntries = 0;
LPDWORD resumeHandle = 0;
NET_API_STATUS status = ::NetUserEnum(
NULL /*local server*/,
1 /*LOCALGROUP_INFO level*/,
FILTER_NORMAL_ACCOUNT,
(LPBYTE *)&pBuff,
MAX_PREFERRED_LENGTH,
&entriesRead,
&totalEntries,
resumeHandle /*resume handle*/);
lastError = ErrorCode::FromWin32Error(status);
if (status == NERR_Success)
{
LPUSER_INFO_1 p;
if ((p = pBuff) != NULL)
{
for (DWORD i = 0; i < entriesRead; i++)
{
wstring comment(p->usri1_comment);
wstring name(p->usri1_name);
if (comment.substr(0, prefix.size()).compare(prefix) == 0)
{
NET_API_STATUS err = ::NetUserDel(L".", name.c_str());
if (err != NERR_Success)
{
lastError = ErrorCode::FromWin32Error(err);
WriteWarning(
TraceSecurityPrincipalHelper,
"Failed to remove user {0} with comment prefix {1}: error={2}",
name,
prefix,
lastError);
}
}
++p;
}
}
}
if (pBuff != NULL)
{
NetApiBufferFree(pBuff);
}
return lastError;
}
ErrorCode SecurityPrincipalHelper::DeleteGroupWithCommentPrefix(wstring const & prefix)
{
ErrorCode lastError(ErrorCodeValue::Success);
LPLOCALGROUP_INFO_1 pBuff = NULL;
DWORD entriesRead = 0;
DWORD totalEntries = 0;
DWORD_PTR resumeHandle = 0;
NET_API_STATUS status = ::NetLocalGroupEnum(
NULL /*local server*/,
1 /*LOCALGROUP_INFO level*/,
(LPBYTE *)&pBuff,
MAX_PREFERRED_LENGTH,
&entriesRead,
&totalEntries,
&resumeHandle /*resume handle*/);
lastError = ErrorCode::FromWin32Error(status);
if (status == NERR_Success)
{
LPLOCALGROUP_INFO_1 p;
if ((p = pBuff) != NULL)
{
for (DWORD i = 0; i < entriesRead; i++)
{
wstring comment(p->lgrpi1_comment);
wstring name(p->lgrpi1_name);
if (comment.substr(0, prefix.size()).compare(prefix) == 0)
{
NET_API_STATUS err = ::NetLocalGroupDel(L".", name.c_str());
if (err != NERR_Success)
{
lastError = ErrorCode::FromWin32Error(err);
WriteWarning(
TraceSecurityPrincipalHelper,
"Failed to remove group {0} with comment prefix {1}: error={2}",
name,
prefix,
lastError);
}
}
++p;
}
}
}
if (pBuff != NULL)
{
NetApiBufferFree(pBuff);
}
return lastError;
}
#endif
| 31.249315 | 154 | 0.591794 | [
"vector"
] |
dc736f249ce835d1c631c874c5bcf7c631756079 | 1,633 | hpp | C++ | include/cppJsonGraph/graphNode.hpp | nallj/cppJsonGraph | 09ea8ed216758b72d5e8e386f55d3c406436ea79 | [
"MIT"
] | 1 | 2021-03-09T06:43:21.000Z | 2021-03-09T06:43:21.000Z | include/cppJsonGraph/graphNode.hpp | nallj/cppJsonGraph | 09ea8ed216758b72d5e8e386f55d3c406436ea79 | [
"MIT"
] | null | null | null | include/cppJsonGraph/graphNode.hpp | nallj/cppJsonGraph | 09ea8ed216758b72d5e8e386f55d3c406436ea79 | [
"MIT"
] | null | null | null | #ifndef NALLJ_CJG_GRAPH_NODE
#define NALLJ_CJG_GRAPH_NODE
#include <unordered_map>
// Remove later.
#include <iostream>
#include <nlohmann/json.hpp>
#include "base.hpp"
#include "graph.hpp"
using json = nlohmann::json;
namespace nallj {
// Needed forward declaration.
class graphNode;
using nodePtr = std::shared_ptr<graphNode>;
template<class T>
using lookupMap = std::unordered_map<std::string, T>;
using nodeMap = lookupMap<nodePtr>;
using nodeValList = std::vector<graphNode>;
class graphNode : public base {
// Unrequired items
std::string label_;
// Internal
bool labelIsSet_;
nodeMap traversableNeighbors_; // TODO: Change to a 'destination node key' to edge map.
public:
graphNode();
graphNode(const graphNode& node);
graphNode(const json& jsonNode);
// Accessors
std::string getLabel() const;
bool getLabelIsSet() const;
lookupMap<graphNode> getTraversableNeighborMap() const;
nodeValList getTraversableNeighbors() const;
bool hasTraversableNeighbor(std::string key) const;
// Mutators
void addTraversableNeighbor(std::string key, nodePtr node);
void clearTraversableNeighbors();
void removeTraversableNeighbor(std::string key);
void setLabel(std::string label);
void unsetLabel();
// Methods
// TODO: Figure out why utility.hpp doesn't work.
template <typename T>
bool hydrateAndCheckIfSet(const json& jsonNode, const char* itemKey, T& variable);
// TODO: Place in utility.hpp when ready.
bool hydrateMetadataAndCheckIfSet(const json& jsonNode);
json toJson() const;
};
}
#endif
| 25.515625 | 91 | 0.710349 | [
"vector"
] |
dc737f3c9b6f90f9e871b7b1417fca3a3076acfc | 18,724 | cpp | C++ | src/uscxml/plugins/Factory.cpp | alexzhornyak/uscxml | 82b44ceeefbe1dc12fc606dc1948f9cebaf67a08 | [
"BSD-2-Clause"
] | 1 | 2020-01-09T13:51:21.000Z | 2020-01-09T13:51:21.000Z | src/uscxml/plugins/Factory.cpp | galaxy1978/uscxml | 8be7b9cb67177bb0e34ca5c5cdb8508319bcda2d | [
"BSD-2-Clause"
] | 1 | 2021-05-18T12:13:30.000Z | 2021-05-18T12:14:50.000Z | src/uscxml/plugins/Factory.cpp | galaxy1978/uscxml | 8be7b9cb67177bb0e34ca5c5cdb8508319bcda2d | [
"BSD-2-Clause"
] | 1 | 2021-04-08T08:57:40.000Z | 2021-04-08T08:57:40.000Z | /**
* @file
* @author 2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* 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.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#include "uscxml/config.h"
#include "uscxml/plugins/Factory.h"
#include "uscxml/messages/Data.h"
#include "uscxml/Interpreter.h"
#include "uscxml/interpreter/Logging.h"
#include "uscxml/plugins/ExecutableContent.h"
#include "uscxml/plugins/ExecutableContentImpl.h"
#include "uscxml/plugins/EventHandler.h"
#include "uscxml/plugins/IOProcessor.h"
#include "uscxml/plugins/IOProcessorImpl.h"
#include "uscxml/plugins/Invoker.h"
#include "uscxml/plugins/InvokerImpl.h"
#include "uscxml/plugins/DataModelImpl.h"
extern "C" {
#include <event2/event.h>
}
#if 0
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include "uscxml/util/DOM.h"
#endif
// see http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system
/*** BEGIN PLUGINS ***/
#ifdef BUILD_AS_PLUGINS
# include "uscxml/plugins/Plugins.h"
#else
#ifdef WITH_IOPROC_SCXML
# include "uscxml/plugins/ioprocessor/scxml/SCXMLIOProcessor.h"
#endif
#ifdef WITH_IOPROC_BASICHTTP
# include "uscxml/plugins/ioprocessor/basichttp/BasicHTTPIOProcessor.h"
#endif
#include "uscxml/plugins/datamodel/null/NullDataModel.h"
#if defined WITH_DM_ECMA_V8
# include "uscxml/plugins/datamodel/ecmascript/v8/V8DataModel.h"
#endif
#ifdef WITH_DM_ECMA_JSC
# include "uscxml/plugins/datamodel/ecmascript/JavaScriptCore/JSCDataModel.h"
#endif
#ifdef WITH_DM_LUA
# include "uscxml/plugins/datamodel/lua/LuaDataModel.h"
#endif
#ifdef WITH_DM_C89
# include "uscxml/plugins/datamodel/c89/C89DataModel.h"
#endif
#ifdef WITH_DM_PROMELA
# include "uscxml/plugins/datamodel/promela/PromelaDataModel.h"
#endif
#ifdef WITH_INV_SCXML
# include "uscxml/plugins/invoker/scxml/USCXMLInvoker.h"
#endif
#ifdef WITH_INV_DIRMON
# include "uscxml/plugins/invoker/dirmon/DirMonInvoker.h"
#endif
#endif
/*** END PLUGINS ***/
namespace uscxml {
Factory::Factory(Factory* parentFactory) : _parentFactory(parentFactory) {
}
Factory::Factory(const std::string& pluginPath, Factory* parentFactory) : _parentFactory(parentFactory), _pluginPath(pluginPath) {
}
Factory::Factory(const std::string& pluginPath) : _parentFactory(NULL), _pluginPath(pluginPath) {
}
void Factory::setDefaultPluginPath(const std::string& path) {
_defaultPluginPath = path;
}
std::string Factory::getDefaultPluginPath() {
return _defaultPluginPath;
}
Factory::~Factory() {
#ifdef BUILD_AS_PLUGINS
pluma.unloadAll();
#endif
}
void Factory::registerPlugins() {
/*** PLUGINS ***/
#ifdef BUILD_AS_PLUGINS
if (_pluginPath.length() == 0) {
// try to read USCXML_PLUGIN_PATH environment variable
_pluginPath = (getenv("USCXML_PLUGIN_PATH") != NULL ? getenv("USCXML_PLUGIN_PATH") : "");
}
if (_pluginPath.length() > 0) {
pluma.acceptProviderType<InvokerImplProvider>();
pluma.acceptProviderType<IOProcessorImplProvider>();
pluma.acceptProviderType<DataModelImplProvider>();
pluma.acceptProviderType<ExecutableContentImplProvider>();
pluma.loadFromFolder(_pluginPath, true);
std::vector<InvokerImplProvider*> invokerProviders;
pluma.getProviders(invokerProviders);
for (auto provider : invokerProviders) {
InvokerImpl* invoker = provider->create();
registerInvoker(invoker);
}
std::vector<IOProcessorImplProvider*> ioProcessorProviders;
pluma.getProviders(ioProcessorProviders);
for (auto provider : ioProcessorProviders) {
IOProcessorImpl* ioProcessor = provider->create();
registerIOProcessor(ioProcessor);
}
std::vector<DataModelImplProvider*> dataModelProviders;
pluma.getProviders(dataModelProviders);
for (auto provider : dataModelProviders) {
DataModelImpl* dataModel = provider->create();
registerDataModel(dataModel);
}
std::vector<ExecutableContentImplProvider*> execContentProviders;
pluma.getProviders(execContentProviders);
for (auto provider : execContentProviders) {
ExecutableContentImpl* execContent = provider->create();
registerExecutableContent(execContent);
}
} else {
ERROR_EXECUTION_THROW("No path to plugins known, export USCXML_PLUGIN_PATH or pass path as parameter");
}
#else
#ifdef WITH_IOPROC_SCXML
{
registerIOProcessor(std::shared_ptr<SCXMLIOProcessor>(new SCXMLIOProcessor));
}
#endif
#ifdef WITH_IOPROC_BASICHTTP
{
registerIOProcessor(std::shared_ptr<BasicHTTPIOProcessor>(new BasicHTTPIOProcessor));
}
#endif
#ifdef WITH_DM_ECMA_V8
{
registerDataModel(std::shared_ptr<V8DataModel>(new V8DataModel));
}
#endif
#ifdef WITH_DM_ECMA_JSC
{
registerDataModel(std::shared_ptr<JSCDataModel>(new JSCDataModel));
}
#endif
#ifdef WITH_DM_LUA
{
registerDataModel(std::shared_ptr<LuaDataModel>(new LuaDataModel));
}
#endif
#ifdef WITH_DM_C89
{
registerDataModel(std::shared_ptr<C89DataModel>(new C89DataModel));
}
#endif
#ifdef WITH_DM_PROMELA
{
registerDataModel(std::shared_ptr<PromelaDataModel>(new PromelaDataModel));
}
#endif
{
registerDataModel(std::shared_ptr<NullDataModel>(new NullDataModel));
}
#ifdef WITH_INV_SCXML
{
registerInvoker(std::shared_ptr<USCXMLInvoker>(new USCXMLInvoker));
}
#endif
#ifdef WITH_INV_DIRMON
{
registerInvoker(std::shared_ptr<DirMonInvoker>(new DirMonInvoker));
}
#endif
#endif
/*** PLUGINS ***/
}
#define LIST_COMPONENTS(type, name) \
auto iter = name.begin(); \
while(iter != name.end()) { \
std::list<std::string> names = iter->second->getNames(); \
std::list<std::string>::iterator nameIter = names.begin(); \
if (nameIter != names.end()) { \
LOGD(USCXML_VERBATIM) << "\t" << *nameIter; \
nameIter++; \
std::string seperator = ""; \
if (nameIter != names.end()) { \
LOGD(USCXML_VERBATIM) << "\t("; \
while(nameIter != names.end()) { \
LOGD(USCXML_VERBATIM) << seperator << *nameIter; \
seperator = ", "; \
nameIter++; \
} \
LOGD(USCXML_VERBATIM) << ")"; \
} \
LOGD(USCXML_VERBATIM) << "\n"; \
} \
iter++; \
}
void Factory::listComponents() {
{
LOGD(USCXML_VERBATIM) << "Available Datamodels:" << std::endl;
LIST_COMPONENTS(DataModelImpl, _dataModels);
LOGD(USCXML_VERBATIM) << "\n";
}
{
LOGD(USCXML_VERBATIM) << "Available Invokers:" << std::endl;
LIST_COMPONENTS(InvokerImpl, _invokers);
LOGD(USCXML_VERBATIM) << "\n";
}
{
LOGD(USCXML_VERBATIM) << "Available I/O Processors:" << std::endl;
LIST_COMPONENTS(IOProcessorImpl, _ioProcessors);
LOGD(USCXML_VERBATIM) << "\n";
}
{
LOGD(USCXML_VERBATIM) << "Available Elements:" << std::endl;
auto iter = _executableContent.begin();
while(iter != _executableContent.end()) {
LOGD(USCXML_VERBATIM) << "\t" << iter->second->getNamespace() << " / " << iter->second->getLocalName() << std::endl;
iter++;
}
LOGD(USCXML_VERBATIM) << "\n";
}
}
void Factory::registerCustomPlugins(const std::set<PluginType> &pluginTypes)
{
#ifdef WITH_IOPROC_SCXML
if (pluginTypes.find(ptSCXMLIOProcessor) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerIOProcessor(std::shared_ptr<SCXMLIOProcessor>(new SCXMLIOProcessor));
}
#endif
#ifdef WITH_IOPROC_BASICHTTP
if (pluginTypes.find(ptBasicHTTPIOProcessor) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerIOProcessor(std::shared_ptr<BasicHTTPIOProcessor>(new BasicHTTPIOProcessor));
}
#endif
#ifdef WITH_DM_ECMA_V8
if (pluginTypes.find(ptV8DataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<V8DataModel>(new V8DataModel));
}
#endif
#ifdef WITH_DM_ECMA_JSC
if (pluginTypes.find(ptJSCDataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<JSCDataModel>(new JSCDataModel));
}
#endif
#ifdef WITH_DM_LUA
if (pluginTypes.find(ptLuaDataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<LuaDataModel>(new LuaDataModel));
}
#endif
#ifdef WITH_DM_C89
if (pluginTypes.find(ptC89DataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<C89DataModel>(new C89DataModel));
}
#endif
#ifdef WITH_DM_PROMELA
if (pluginTypes.find(ptPromelaDataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<PromelaDataModel>(new PromelaDataModel));
}
#endif
if (pluginTypes.find(ptNullDataModel) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerDataModel(std::shared_ptr<NullDataModel>(new NullDataModel));
}
#ifdef WITH_INV_SCXML
if (pluginTypes.find(ptUSCXMLInvoker) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerInvoker(std::shared_ptr<USCXMLInvoker>(new USCXMLInvoker));
}
#endif
#ifdef WITH_INV_DIRMON
if (pluginTypes.find(ptDirMonInvoker) != pluginTypes.end() || pluginTypes.find(ptALL) != pluginTypes.end()) {
registerInvoker(std::shared_ptr<DirMonInvoker>(new DirMonInvoker));
}
#endif
}
void Factory::registerIOProcessor(std::shared_ptr<IOProcessorImpl> ioProcessor) {
std::list<std::string> names = ioProcessor->getNames();
std::list<std::string>::iterator nameIter = names.begin();
if (nameIter != names.end()) {
std::string canonicalName = *nameIter;
_ioProcessors[canonicalName] = ioProcessor;
while(nameIter != names.end()) {
_ioProcessorAliases[*nameIter] = canonicalName;
nameIter++;
}
}
}
void Factory::registerDataModel(std::shared_ptr<DataModelImpl> dataModel) {
std::list<std::string> names = dataModel->getNames();
std::list<std::string>::iterator nameIter = names.begin();
if (nameIter != names.end()) {
std::string canonicalName = *nameIter;
_dataModels[canonicalName] = dataModel;
while(nameIter != names.end()) {
_dataModelAliases[*nameIter] = canonicalName;
nameIter++;
}
}
}
void Factory::registerInvoker(std::shared_ptr<InvokerImpl> invoker) {
std::list<std::string> names = invoker->getNames();
std::list<std::string>::iterator nameIter = names.begin();
if (nameIter != names.end()) {
std::string canonicalName = *nameIter;
_invokers[canonicalName] = invoker;
while(nameIter != names.end()) {
_invokerAliases[*nameIter] = canonicalName;
nameIter++;
}
}
}
void Factory::registerExecutableContent(std::shared_ptr<ExecutableContentImpl> executableContent) {
std::string localName = executableContent->getLocalName();
std::string nameSpace = executableContent->getNamespace();
_executableContent[std::make_pair(localName, nameSpace)] = executableContent;
}
std::map<std::string, IOProcessorImpl*> Factory::getIOProcessors() {
std::map<std::string, IOProcessorImpl*> ioProcs;
if (_parentFactory) {
ioProcs = _parentFactory->getIOProcessors();
}
for (const auto &ioProcIter : _ioProcessors) {
ioProcs.insert(std::make_pair(ioProcIter.first, ioProcIter.second.get()));
}
return ioProcs;
}
bool Factory::hasInvoker(const std::string& type) {
if (_invokerAliases.find(type) != _invokerAliases.end()) {
return true;
} else if(_parentFactory) {
return _parentFactory->hasInvoker(type);
}
return false;
}
std::shared_ptr<InvokerImpl> Factory::createInvoker(const std::string& type, InvokerCallbacks* callbacks) {
// do we have this type ourself?
if (_invokerAliases.find(type) != _invokerAliases.end()) {
std::string canonicalName = _invokerAliases[type];
if (_invokers.find(canonicalName) != _invokers.end()) {
std::shared_ptr<InvokerImpl> invoker = _invokers[canonicalName]->create(callbacks);
return invoker;
}
}
// lookup in parent factory
if (_parentFactory) {
return _parentFactory->createInvoker(type, callbacks);
} else {
ERROR_EXECUTION_THROW("No Invoker named '" + type + "' known");
}
return std::shared_ptr<InvokerImpl>();
}
bool Factory::hasDataModel(const std::string& type) {
if (_dataModelAliases.find(type) != _dataModelAliases.end()) {
return true;
} else if(_parentFactory) {
return _parentFactory->hasDataModel(type);
}
return false;
}
std::shared_ptr<DataModelImpl> Factory::createDataModel(const std::string& type, DataModelCallbacks* callbacks) {
// do we have this type ourself?
if (_dataModelAliases.find(type) != _dataModelAliases.end()) {
std::string canonicalName = _dataModelAliases[type];
if (_dataModels.find(canonicalName) != _dataModels.end()) {
std::shared_ptr<DataModelImpl> dataModel = _dataModels[canonicalName]->create(callbacks);
return dataModel;
}
}
// lookup in parent factory
if (_parentFactory) {
return _parentFactory->createDataModel(type, callbacks);
} else {
ERROR_EXECUTION_THROW("No Datamodel name '" + type + "' known");
}
return std::shared_ptr<DataModelImpl>();
}
bool Factory::hasIOProcessor(const std::string& type) {
if (_ioProcessorAliases.find(type) != _ioProcessorAliases.end()) {
return true;
} else if(_parentFactory) {
return _parentFactory->hasIOProcessor(type);
}
return false;
}
std::shared_ptr<IOProcessorImpl> Factory::createIOProcessor(const std::string& type, IOProcessorCallbacks* callbacks) {
// do we have this type ourself?
if (_ioProcessorAliases.find(type) != _ioProcessorAliases.end()) {
std::string canonicalName = _ioProcessorAliases[type];
if (_ioProcessors.find(canonicalName) != _ioProcessors.end()) {
std::shared_ptr<IOProcessorImpl> ioProc = _ioProcessors[canonicalName]->create(callbacks);
// ioProc->setInterpreter(interpreter);
return ioProc;
}
}
// lookup in parent factory
if (_parentFactory) {
return _parentFactory->createIOProcessor(type, callbacks);
} else {
ERROR_EXECUTION_THROW("No IOProcessor named '" + type + "' known");
}
return std::shared_ptr<IOProcessorImpl>();
}
bool Factory::hasExecutableContent(const std::string& localName, const std::string& nameSpace) {
std::string actualNameSpace = (nameSpace.length() == 0 ? "http://www.w3.org/2005/07/scxml" : nameSpace);
if (_executableContent.find(std::make_pair(localName, actualNameSpace)) != _executableContent.end()) {
return true;
} else if(_parentFactory) {
return _parentFactory->hasExecutableContent(localName, nameSpace);
}
return false;
}
std::shared_ptr<ExecutableContentImpl> Factory::createExecutableContent(const std::string& localName, const std::string& nameSpace, InterpreterImpl* interpreter) {
// do we have this type in this factory?
std::string actualNameSpace = (nameSpace.length() == 0 ? "http://www.w3.org/2005/07/scxml" : nameSpace);
if (_executableContent.find(std::make_pair(localName, actualNameSpace)) != _executableContent.end()) {
std::shared_ptr<ExecutableContentImpl> execContent = _executableContent[std::make_pair(localName, actualNameSpace)]->create(interpreter);
execContent->setInterpreter(interpreter);
return execContent;
}
// lookup in parent factory
if (_parentFactory) {
return _parentFactory->createExecutableContent(localName, nameSpace, interpreter);
} else {
ERROR_EXECUTION_THROW("No Executable content name '" + localName + "' in namespace '" + actualNameSpace + "' known");
}
return std::shared_ptr<ExecutableContentImpl>();
}
void DataModelImpl::addExtension(DataModelExtension* ext) {
ERROR_EXECUTION_THROW("DataModel does not support extensions");
}
size_t DataModelImpl::replaceExpressions(std::string& content) {
std::stringstream ss;
size_t replacements = 0;
size_t indent = 0;
size_t pos = 0;
size_t start = std::string::npos;
size_t end = 0;
while (true) {
// find any of ${}
pos = content.find_first_of("${}", pos);
if (pos == std::string::npos) {
ss << content.substr(end, content.length() - end);
break;
}
if (content[pos] == '$') {
if (content.size() > pos && content[pos+1] == '{') {
pos++;
start = pos + 1;
// copy everything in between
ss << content.substr(end, (start - 2) - end);
}
} else if (content[pos] == '{' && start != std::string::npos) {
indent++;
} else if (content[pos] == '}' && start != std::string::npos) {
if (!indent) {
end = pos;
// we found a token to substitute
std::string expr = content.substr(start, end - start);
end++;
try {
Data data = getAsData(expr);
// if (data.type == Data::VERBATIM) {
// ss << "\"" << data.atom << "\"";
// } else {
// ss << data.atom;
// }
if (data.atom.length() > 0) {
ss << data.atom;
} else {
ss << Data::toJSON(data);
}
replacements++;
} catch (Event e) {
// insert unsubstituted
start -= 2;
ss << content.substr(start, end - start);
}
start = std::string::npos;
} else {
indent--;
}
}
pos++;
}
if (replacements)
content = ss.str();
return replacements;
}
Factory & Factory::getInstance()
{
static Factory instance(Factory::_defaultPluginPath);
return instance;
}
void Factory::cleanup()
{
HTTPServer::cleanup();
URLFetcher::cleanup();
libevent_global_shutdown();
}
void IOProcessorImpl::eventToSCXML(Event& event,
const std::string& type,
const std::string& origin,
bool internal) {
if (event.eventType == 0)
event.eventType = (internal ? Event::INTERNAL : Event::EXTERNAL);
if (event.origin.length() == 0 && origin.length() > 0)
event.origin = origin;
if (event.origintype.length() == 0)
event.origintype = type;
if (internal) {
_callbacks->enqueueInternal(event);
} else {
_callbacks->enqueueExternal(event);
}
}
void InvokerImpl::eventToSCXML(Event& event,
const std::string& type,
const std::string& invokeId,
bool internal) {
if (event.invokeid.length() == 0)
event.invokeid = invokeId;
if (event.eventType == 0)
event.eventType = (internal ? Event::INTERNAL : Event::EXTERNAL);
if (event.origin.length() == 0 && invokeId.length() > 0)
event.origin = "#_" + invokeId;
if (event.origintype.length() == 0)
event.origintype = type;
if (internal) {
_callbacks->enqueueInternal(event);
} else {
_callbacks->enqueueExternal(event);
}
}
std::string Factory::_defaultPluginPath;
Factory* Factory::_instance = NULL;
}
| 28.850539 | 163 | 0.711333 | [
"vector"
] |
dc7cc067940d6ce5d1cbc342befe4f382b2cf27c | 5,118 | hxx | C++ | main/sd/source/ui/inc/taskpane/TitleBar.hxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | null | null | null | main/sd/source/ui/inc/taskpane/TitleBar.hxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | 5 | 2020-04-04T18:48:53.000Z | 2020-09-18T22:42:00.000Z | main/sd/source/ui/inc/taskpane/TitleBar.hxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | null | null | null | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 SD_TASKPANE_TITLE_BAR_HXX
#define SD_TASKPANE_TITLE_BAR_HXX
#include "taskpane/TaskPaneTreeNode.hxx"
#include <vcl/image.hxx>
#include <tools/string.hxx>
#include <vcl/window.hxx>
#include <memory>
class Rectangle;
class String;
class VirtualDevice;
namespace sd { namespace toolpanel {
/** The title bar above a control in a sub tool panel.
<p>The title bar shows two kinds of indicators: 1) Expansion is
displayed by two sets of two bitmaps, a triangle pointing to the right
resp. a minus in a square indicates that the control is collapsed, a
triangle pointing down resp. a plus in a square stands for an expanded
control. 2) Keyboard focus is indicated by a dotted rectangle.
*/
class TitleBar
: public ::Window,
public TreeNode
{
public:
enum TitleBarType {
TBT_SUB_CONTROL_HEADLINE
};
/** Create a new title bar whose content, the given title string,
will be formatted according to the given type.
*/
TitleBar (
::Window* pParent,
const String& rsTitle,
TitleBarType eType,
bool bIsExpandable);
virtual ~TitleBar (void);
virtual Size GetPreferredSize (void);
virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeight);
virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth);
virtual bool IsResizable (void);
virtual ::Window* GetWindow (void);
virtual sal_Int32 GetMinimumWidth (void);
virtual void Paint (const Rectangle& rBoundingBox);
virtual bool Expand (bool bFlag = true);
virtual bool IsExpanded (void) const;
virtual void SetEnabledState(bool bFlag);
virtual void GetFocus (void);
virtual void LoseFocus (void);
virtual void MouseMove(const MouseEvent& rEvent);
/** Empty implementation prevents forwarding to docking window.
*/
virtual void MouseButtonDown (const MouseEvent& rEvent);
/** Empty implementation prevents forwarding to docking window.
*/
virtual void MouseButtonUp (const MouseEvent& rEvent);
virtual void DataChanged (const DataChangedEvent& rEvent);
String GetTitle (void) const;
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible > CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent);
private:
TitleBarType meType;
String msTitle;
bool mbExpanded;
bool mbFocused;
// Size of the bounding box that encloses the title string.
::std::auto_ptr<VirtualDevice> mpDevice;
bool mbIsExpandable;
/** Return whether this TitleBar object has an expansion indicator
bitmap. It is safe to call GetExpansionIndicator() when this method
returns <FALSE/> but unnecessary.
*/
bool HasExpansionIndicator (void) const;
/** Return the image of the expansion indicator.
@return
When there is no expansion indicator for this TitleBar object,
then an empty Image is returned. You better call
HasExpansionIndicator() to prevent this.
*/
Image GetExpansionIndicator (void) const;
/** Calculate the bounding box of the title text. This takes into
account indentation due to an expansion indicator and the given
available width. When the text can not be displayed on one line, it
is broken into multiple lines.
@param nAvailableWidth
When 0 is given then the natural text width is used, i.e. the
text is not broken into multiple lines.
*/
Rectangle CalculateTextBoundingBox (
int nAvailableWidth,
bool bEmphasizeExpanded);
/** Add some space to the given text box and return the bounding box of
the title bar.
*/
Rectangle CalculateTitleBarBox (
const Rectangle& rTextBox,
int nTitleBarWidth);
void PaintSubPanelHeadLineBar (void);
void PaintBackground (const Rectangle& rTextBox);
/// Paint a focus indicator that encloses the given rectangle.
void PaintFocusIndicator (const Rectangle& rIndicatorBox);
Rectangle PaintExpansionIndicator (const Rectangle& rTextBox);
void PaintText (const Rectangle& rTextBox);
sal_uInt16 GetTextStyle (void);
const static int snIndentationWidth;
// Default constructor, copy constructor, and assignment are not supported.
TitleBar (void);
TitleBar (const TitleBar&);
TitleBar& operator= (const TitleBar&);
using Window::GetWindow;
};
} } // end of namespace ::sd::toolpanel
#endif
| 30.831325 | 76 | 0.739156 | [
"object"
] |
dc8640cb73d94a1cd7d6f895a6c7c4ac0af0a174 | 2,031 | cpp | C++ | src/dolfin/la/GenericMatrix.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | src/dolfin/la/GenericMatrix.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | src/dolfin/la/GenericMatrix.cpp | szmurlor/fiver | 083251420eb934d860c99dcf1eb07ae5b8ba7e8c | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2010 Anders Logg
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
//
// First added: 2010-02-23
// Last changed: 2011-03-17
#include <boost/scoped_array.hpp>
#include <dolfin/common/constants.h>
#include "GenericMatrix.h"
using namespace dolfin;
//-----------------------------------------------------------------------------
void GenericMatrix::ident_zeros()
{
std::vector<uint> columns;
std::vector<double> values;
std::vector<uint> zero_rows;
// Check which rows are zero
for (uint row = 0; row < size(0); row++)
{
// Get value for row
getrow(row, columns, values);
// Get maximum value in row
double max = 0.0;
for (uint k = 0; k < values.size(); k++)
max = std::max(max, std::abs(values[k]));
// Check if row is zero
if (max < DOLFIN_EPS)
zero_rows.push_back(row);
}
// Write a message
log(TRACE, "Found %d zero row(s), inserting ones on the diagonal.", zero_rows.size());
// Insert one on the diagonal for rows with only zeros. Note that we
// are not calling ident() since that fails in PETSc if nothing
// has been assembled into those rows.
for (uint i = 0; i < zero_rows.size(); i++)
{
std::pair<uint, uint> ij(zero_rows[i], zero_rows[i]);
setitem(ij, 1.0);
}
// Apply changes
apply("insert");
}
//-----------------------------------------------------------------------------
| 30.772727 | 88 | 0.623338 | [
"vector"
] |
dc872fe84fdcd064df0300b9843a48fa6219274f | 828 | cpp | C++ | cpp/linearalgebra/tridiagonal.cpp | DinhLantstk789/codelibrary | d7dac1b8ac42fabeb42a087f205761fcbcfe982e | [
"Unlicense"
] | 1 | 2019-08-27T22:55:45.000Z | 2019-08-27T22:55:45.000Z | cpp/linearalgebra/tridiagonal.cpp | DinhLantstk789/codelibrary | d7dac1b8ac42fabeb42a087f205761fcbcfe982e | [
"Unlicense"
] | null | null | null | cpp/linearalgebra/tridiagonal.cpp | DinhLantstk789/codelibrary | d7dac1b8ac42fabeb42a087f205761fcbcfe982e | [
"Unlicense"
] | 1 | 2019-11-09T19:35:52.000Z | 2019-11-09T19:35:52.000Z | #include <bits/stdc++.h>
using namespace std;
// https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
template<class T>
vector<T> tridiagonal_solve(vector<T> diag, const vector<T> &super, const vector<T> &sub, vector<T> b) {
for (int i = 0; i < b.size() - 1; ++i) {
diag[i + 1] -= super[i] * sub[i] / diag[i];
b[i + 1] -= b[i] * sub[i] / diag[i];
}
for (int i = b.size() - 1; i > 0; --i) {
b[i] /= diag[i];
b[i - 1] -= b[i] * super[i - 1];
}
b[0] /= diag[0];
return b;
}
// usage example
int main() {
// -1 1 0 x[0] 5
// 3 -1 2 * x[1] = 6
// 0 4 -1 x[2] 7
vector<double> x = tridiagonal_solve<double>({-1, -1, -1}, {1, 2}, {3, 4}, {5, 6, 7});
for (double v : x) cout << fixed << setprecision(5) << v << " ";
cout << endl;
}
| 27.6 | 104 | 0.480676 | [
"vector"
] |
dc879131ed59b32bc9cd454e6538b67ea3780681 | 713 | cc | C++ | shrink_to_fit.cc | pycpp/sfinae-test | 92691a0365410d0a612432ba51251c58232cbab8 | [
"MIT"
] | null | null | null | shrink_to_fit.cc | pycpp/sfinae-test | 92691a0365410d0a612432ba51251c58232cbab8 | [
"MIT"
] | null | null | null | shrink_to_fit.cc | pycpp/sfinae-test | 92691a0365410d0a612432ba51251c58232cbab8 | [
"MIT"
] | null | null | null | // :copyright: (c) 2017-2018 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup Tests
* \brief `shrink_to_fit` and `has_shrink_to_fit` unittests.
*/
#include <pycpp/sfinae/shrink_to_fit.h>
#include <gtest/gtest.h>
#include <list>
#include <vector>
PYCPP_USING_NAMESPACE
// TESTS
// -----
TEST(shrink_to_fit, shrink_to_fit)
{
std::list<int> l;
std::vector<int> v;
shrink_to_fit()(l);
shrink_to_fit()(v);
}
TEST(shrink_to_fit, has_shrink_to_fit)
{
using list_type = std::list<int>;
using vector_type = std::vector<int>;
static_assert(!has_shrink_to_fit<list_type>::value, "");
static_assert(has_shrink_to_fit<vector_type>::value, "");
}
| 19.805556 | 61 | 0.680224 | [
"vector"
] |
dc8ad0ed8531355732947e343ba0e03c4fc98772 | 16,757 | cpp | C++ | openstudiocore/src/model/AvailabilityManagerOptimumStart.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/model/AvailabilityManagerOptimumStart.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/model/AvailabilityManagerOptimumStart.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "AvailabilityManagerOptimumStart.hpp"
#include "AvailabilityManagerOptimumStart_Impl.hpp"
#include "Model.hpp"
#include "Model_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "ScheduleTypeLimits.hpp"
#include "ScheduleTypeRegistry.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/OS_AvailabilityManager_OptimumStart_FieldEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
AvailabilityManagerOptimumStart_Impl::AvailabilityManagerOptimumStart_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == AvailabilityManagerOptimumStart::iddObjectType());
}
AvailabilityManagerOptimumStart_Impl::AvailabilityManagerOptimumStart_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == AvailabilityManagerOptimumStart::iddObjectType());
}
AvailabilityManagerOptimumStart_Impl::AvailabilityManagerOptimumStart_Impl(const AvailabilityManagerOptimumStart_Impl& other,
Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& AvailabilityManagerOptimumStart_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType AvailabilityManagerOptimumStart_Impl::iddObjectType() const {
return AvailabilityManagerOptimumStart::iddObjectType();
}
std::vector<ScheduleTypeKey> AvailabilityManagerOptimumStart_Impl::getScheduleTypeKeys(const Schedule& schedule) const
{
std::vector<ScheduleTypeKey> result;
UnsignedVector fieldIndices = getSourceIndices(schedule.handle());
UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());
if (std::find(b,e,OS_AvailabilityManager_OptimumStartFields::ApplicabilitySchedule) != e)
{
result.push_back(ScheduleTypeKey("AvailabilityManagerOptimumStart","Applicability Schedule"));
}
if (std::find(b,e,OS_AvailabilityManager_OptimumStartFields::FanSchedule) != e)
{
result.push_back(ScheduleTypeKey("AvailabilityManagerOptimumStart","Fan Schedule"));
}
return result;
}
Schedule AvailabilityManagerOptimumStart_Impl::applicabilitySchedule() const {
boost::optional<Schedule> value = optionalApplicabilitySchedule();
if (!value) {
LOG_AND_THROW(briefDescription() << " does not have an Applicability Schedule attached.");
}
return value.get();
}
std::string AvailabilityManagerOptimumStart_Impl::controlType() const {
boost::optional<std::string> value = getString(OS_AvailabilityManager_OptimumStartFields::ControlType,true);
OS_ASSERT(value);
return value.get();
}
boost::optional<ThermalZone> AvailabilityManagerOptimumStart_Impl::controlZone() const {
return getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_AvailabilityManager_OptimumStartFields::ControlZone);
}
double AvailabilityManagerOptimumStart_Impl::maximumValueforOptimumStartTime() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::MaximumValueforOptimumStartTime,true);
OS_ASSERT(value);
return value.get();
}
std::string AvailabilityManagerOptimumStart_Impl::controlAlgorithm() const {
boost::optional<std::string> value = getString(OS_AvailabilityManager_OptimumStartFields::ControlAlgorithm,true);
OS_ASSERT(value);
return value.get();
}
double AvailabilityManagerOptimumStart_Impl::constantTemperatureGradientduringCooling() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::ConstantTemperatureGradientduringCooling,true);
OS_ASSERT(value);
return value.get();
}
double AvailabilityManagerOptimumStart_Impl::constantTemperatureGradientduringHeating() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::ConstantTemperatureGradientduringHeating,true);
OS_ASSERT(value);
return value.get();
}
double AvailabilityManagerOptimumStart_Impl::initialTemperatureGradientduringCooling() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::InitialTemperatureGradientduringCooling,true);
OS_ASSERT(value);
return value.get();
}
double AvailabilityManagerOptimumStart_Impl::initialTemperatureGradientduringHeating() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::InitialTemperatureGradientduringHeating,true);
OS_ASSERT(value);
return value.get();
}
double AvailabilityManagerOptimumStart_Impl::constantStartTime() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_OptimumStartFields::ConstantStartTime,true);
OS_ASSERT(value);
return value.get();
}
int AvailabilityManagerOptimumStart_Impl::numberofPreviousDays() const {
boost::optional<int> value = getInt(OS_AvailabilityManager_OptimumStartFields::NumberofPreviousDays,true);
OS_ASSERT(value);
return value.get();
}
bool AvailabilityManagerOptimumStart_Impl::setApplicabilitySchedule(Schedule& schedule) {
bool result = setSchedule(OS_AvailabilityManager_OptimumStartFields::ApplicabilitySchedule,
"AvailabilityManagerOptimumStart",
"Applicability Schedule",
schedule);
return result;
}
bool AvailabilityManagerOptimumStart_Impl::setControlType(std::string controlType) {
bool result = setString(OS_AvailabilityManager_OptimumStartFields::ControlType, controlType);
return result;
}
bool AvailabilityManagerOptimumStart_Impl::setControlZone(const boost::optional<ThermalZone>& thermalZone) {
bool result(false);
if (thermalZone) {
result = setPointer(OS_AvailabilityManager_OptimumStartFields::ControlZone, thermalZone.get().handle());
}
else {
resetControlZone();
result = true;
}
return result;
}
void AvailabilityManagerOptimumStart_Impl::resetControlZone() {
bool result = setString(OS_AvailabilityManager_OptimumStartFields::ControlZone, "");
OS_ASSERT(result);
}
void AvailabilityManagerOptimumStart_Impl::setMaximumValueforOptimumStartTime(double maximumValueforOptimumStartTime) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::MaximumValueforOptimumStartTime, maximumValueforOptimumStartTime);
OS_ASSERT(result);
}
bool AvailabilityManagerOptimumStart_Impl::setControlAlgorithm(std::string controlAlgorithm) {
bool result = setString(OS_AvailabilityManager_OptimumStartFields::ControlAlgorithm, controlAlgorithm);
return result;
}
void AvailabilityManagerOptimumStart_Impl::setConstantTemperatureGradientduringCooling(double constantTemperatureGradientduringCooling) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::ConstantTemperatureGradientduringCooling, constantTemperatureGradientduringCooling);
OS_ASSERT(result);
}
void AvailabilityManagerOptimumStart_Impl::setConstantTemperatureGradientduringHeating(double constantTemperatureGradientduringHeating) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::ConstantTemperatureGradientduringHeating, constantTemperatureGradientduringHeating);
OS_ASSERT(result);
}
void AvailabilityManagerOptimumStart_Impl::setInitialTemperatureGradientduringCooling(double initialTemperatureGradientduringCooling) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::InitialTemperatureGradientduringCooling, initialTemperatureGradientduringCooling);
OS_ASSERT(result);
}
void AvailabilityManagerOptimumStart_Impl::setInitialTemperatureGradientduringHeating(double initialTemperatureGradientduringHeating) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::InitialTemperatureGradientduringHeating, initialTemperatureGradientduringHeating);
OS_ASSERT(result);
}
void AvailabilityManagerOptimumStart_Impl::setConstantStartTime(double constantStartTime) {
bool result = setDouble(OS_AvailabilityManager_OptimumStartFields::ConstantStartTime, constantStartTime);
OS_ASSERT(result);
}
bool AvailabilityManagerOptimumStart_Impl::setNumberofPreviousDays(int numberofPreviousDays) {
bool result = setInt(OS_AvailabilityManager_OptimumStartFields::NumberofPreviousDays, numberofPreviousDays);
return result;
}
boost::optional<Schedule> AvailabilityManagerOptimumStart_Impl::optionalApplicabilitySchedule() const {
return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_AvailabilityManager_OptimumStartFields::ApplicabilitySchedule);
}
} // detail
AvailabilityManagerOptimumStart::AvailabilityManagerOptimumStart(const Model& model)
: AvailabilityManager(AvailabilityManagerOptimumStart::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::AvailabilityManagerOptimumStart_Impl>());
{
auto schedule = model.alwaysOnDiscreteSchedule();
setApplicabilitySchedule(schedule);
}
setControlType("MaximumofZoneList");
setMaximumValueforOptimumStartTime(6.0);
setControlAlgorithm("AdaptiveTemperatureGradient");
setConstantTemperatureGradientduringCooling(3.0);
setConstantTemperatureGradientduringHeating(3.0);
setInitialTemperatureGradientduringCooling(2.0);
setInitialTemperatureGradientduringHeating(2.0);
setConstantStartTime(2.0);
setNumberofPreviousDays(3);
}
IddObjectType AvailabilityManagerOptimumStart::iddObjectType() {
return IddObjectType(IddObjectType::OS_AvailabilityManager_OptimumStart);
}
std::vector<std::string> AvailabilityManagerOptimumStart::controlTypeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_AvailabilityManager_OptimumStartFields::ControlType);
}
std::vector<std::string> AvailabilityManagerOptimumStart::controlAlgorithmValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_AvailabilityManager_OptimumStartFields::ControlAlgorithm);
}
Schedule AvailabilityManagerOptimumStart::applicabilitySchedule() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->applicabilitySchedule();
}
std::string AvailabilityManagerOptimumStart::controlType() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->controlType();
}
boost::optional<ThermalZone> AvailabilityManagerOptimumStart::controlZone() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->controlZone();
}
double AvailabilityManagerOptimumStart::maximumValueforOptimumStartTime() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->maximumValueforOptimumStartTime();
}
std::string AvailabilityManagerOptimumStart::controlAlgorithm() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->controlAlgorithm();
}
double AvailabilityManagerOptimumStart::constantTemperatureGradientduringCooling() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->constantTemperatureGradientduringCooling();
}
double AvailabilityManagerOptimumStart::constantTemperatureGradientduringHeating() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->constantTemperatureGradientduringHeating();
}
double AvailabilityManagerOptimumStart::initialTemperatureGradientduringCooling() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->initialTemperatureGradientduringCooling();
}
double AvailabilityManagerOptimumStart::initialTemperatureGradientduringHeating() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->initialTemperatureGradientduringHeating();
}
double AvailabilityManagerOptimumStart::constantStartTime() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->constantStartTime();
}
int AvailabilityManagerOptimumStart::numberofPreviousDays() const {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->numberofPreviousDays();
}
bool AvailabilityManagerOptimumStart::setApplicabilitySchedule(Schedule& schedule) {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setApplicabilitySchedule(schedule);
}
bool AvailabilityManagerOptimumStart::setControlType(std::string controlType) {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setControlType(controlType);
}
bool AvailabilityManagerOptimumStart::setControlZone(const ThermalZone& thermalZone) {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setControlZone(thermalZone);
}
void AvailabilityManagerOptimumStart::resetControlZone() {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->resetControlZone();
}
void AvailabilityManagerOptimumStart::setMaximumValueforOptimumStartTime(double maximumValueforOptimumStartTime) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setMaximumValueforOptimumStartTime(maximumValueforOptimumStartTime);
}
bool AvailabilityManagerOptimumStart::setControlAlgorithm(std::string controlAlgorithm) {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setControlAlgorithm(controlAlgorithm);
}
void AvailabilityManagerOptimumStart::setConstantTemperatureGradientduringCooling(double constantTemperatureGradientduringCooling) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setConstantTemperatureGradientduringCooling(constantTemperatureGradientduringCooling);
}
void AvailabilityManagerOptimumStart::setConstantTemperatureGradientduringHeating(double constantTemperatureGradientduringHeating) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setConstantTemperatureGradientduringHeating(constantTemperatureGradientduringHeating);
}
void AvailabilityManagerOptimumStart::setInitialTemperatureGradientduringCooling(double initialTemperatureGradientduringCooling) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setInitialTemperatureGradientduringCooling(initialTemperatureGradientduringCooling);
}
void AvailabilityManagerOptimumStart::setInitialTemperatureGradientduringHeating(double initialTemperatureGradientduringHeating) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setInitialTemperatureGradientduringHeating(initialTemperatureGradientduringHeating);
}
void AvailabilityManagerOptimumStart::setConstantStartTime(double constantStartTime) {
getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setConstantStartTime(constantStartTime);
}
bool AvailabilityManagerOptimumStart::setNumberofPreviousDays(int numberofPreviousDays) {
return getImpl<detail::AvailabilityManagerOptimumStart_Impl>()->setNumberofPreviousDays(numberofPreviousDays);
}
/// @cond
AvailabilityManagerOptimumStart::AvailabilityManagerOptimumStart(std::shared_ptr<detail::AvailabilityManagerOptimumStart_Impl> impl)
: AvailabilityManager(impl)
{}
/// @endcond
} // model
} // openstudio
| 45.535326 | 155 | 0.783493 | [
"vector",
"model"
] |
dc8d2a998054e55862e1321b0f2b1a6d423ad913 | 4,073 | cc | C++ | QFSClient/qfs_client_util_test.cc | aristanetworks/quantumfs | 4636946c38db75f7d1034b626a3f92b0dd77fbe0 | [
"Apache-2.0"
] | 3 | 2019-02-23T02:01:54.000Z | 2019-09-24T16:29:26.000Z | QFSClient/qfs_client_util_test.cc | aristanetworks/quantumfs | 4636946c38db75f7d1034b626a3f92b0dd77fbe0 | [
"Apache-2.0"
] | null | null | null | QFSClient/qfs_client_util_test.cc | aristanetworks/quantumfs | 4636946c38db75f7d1034b626a3f92b0dd77fbe0 | [
"Apache-2.0"
] | 2 | 2019-11-22T01:18:54.000Z | 2020-04-19T01:27:16.000Z | // Copyright (c) 2017 Arista Networks, Inc.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
#include "QFSClient/qfs_client_util.h"
#include <gtest/gtest.h>
#include <string>
#include <vector>
namespace qfsclient {
class QfsClientUtilTest : public testing::Test {
protected:
static void SetUpTestCase();
static void TearDownTestCase();
void RandomiseBlock(byte *block, size_t size);
};
void QfsClientUtilTest::SetUpTestCase() {
}
void QfsClientUtilTest::TearDownTestCase() {
}
TEST_F(QfsClientUtilTest, SplitTest) {
std::vector<std::string> tokens;
// test basic case
std::string string_to_split("dogs/cats/turtles");
util::Split(string_to_split, "/", &tokens);
ASSERT_EQ(tokens.size(), 3);
ASSERT_EQ(tokens.at(0), "dogs");
ASSERT_EQ(tokens.at(1), "cats");
ASSERT_EQ(tokens.at(2), "turtles");
string_to_split.clear();
util::Split(string_to_split, "/", &tokens);
ASSERT_EQ(tokens.size(), 0);
// test with multiple leading and intermediate delimiters
string_to_split = ("//one///two/three////four//");
util::Split(string_to_split, "/", &tokens);
ASSERT_EQ(tokens.size(), 4);
ASSERT_EQ(tokens.at(0), "one");
ASSERT_EQ(tokens.at(1), "two");
ASSERT_EQ(tokens.at(2), "three");
ASSERT_EQ(tokens.at(3), "four");
// test with no delimiters and one token
string_to_split = ("donkeys");
util::Split(string_to_split, "/", &tokens);
ASSERT_EQ(tokens.size(), 1);
ASSERT_EQ(tokens.at(0), "donkeys");
// test with empty string
string_to_split.clear();
util::Split(string_to_split, "/", &tokens);
ASSERT_EQ(tokens.size(), 0);
}
TEST_F(QfsClientUtilTest, JoinTest) {
std::vector<std::string> tokens{ "dogs", "cats", "turtles" };
std::string expected("dogs/cats/turtles");
std::string actual;
util::Join(tokens, "/", &actual);
ASSERT_STREQ(expected.c_str(), actual.c_str());
tokens.clear();
expected.clear();
util::Join(tokens, "/", &actual);
ASSERT_STREQ(expected.c_str(), actual.c_str());
}
// Test base64 encoding of a short block of data
TEST_F(QfsClientUtilTest, Base64EncodeTest) {
std::string b64;
std::vector<byte> data;
const char *data_value = "Mary had a little lamb.\001\002\003";
data.assign(data_value, data_value + strlen(data_value));
util::base64_encode(data, &b64);
ASSERT_STREQ("TWFyeSBoYWQgYSBsaXR0bGUgbGFtYi4BAgM=", b64.c_str());
}
// Test base64 encoding of a short base64 value
TEST_F(QfsClientUtilTest, Base64DecodeTest) {
std::string b64;
std::vector<byte> data, result;
b64.assign("TWFyeSBoYWQgYSBsaXR0bGUgbGFtYi4BAgM=");
const char *data_value = "Mary had a little lamb.\001\002\003";
data.assign(data_value, data_value + strlen(data_value));
util::base64_decode(b64, &result);
ASSERT_EQ(data.size(), result.size());
ASSERT_EQ(memcmp(data.data(), result.data(), data.size()), 0);
}
void QfsClientUtilTest::RandomiseBlock(byte *block, size_t size) {
unsigned int seed = time(NULL);
srand(seed);
for (size_t i = 0; i < size; i++) {
block[i] = rand_r(&seed);
}
}
// Test base64 encoding and decoding of a larger block of random data
TEST_F(QfsClientUtilTest, Base64BigTest) {
byte block[1024];
QfsClientUtilTest::RandomiseBlock(block, 1024);
std::string b64;
std::vector<byte> data, result;
data.assign(block, block + 1024);
util::base64_encode(data, &b64);
util::base64_decode(b64, &result);
ASSERT_EQ(data.size(), result.size());
ASSERT_EQ(memcmp(data.data(), result.data(), data.size()), 0);
}
// Negative test for base64 encoding and decoding
TEST_F(QfsClientUtilTest, Base64BigBadTest) {
byte block[1024];
QfsClientUtilTest::RandomiseBlock(block, 1024);
std::string b64;
std::vector<byte> data, result;
data.assign(block, block + 1024);
util::base64_encode(data, &b64);
// change the base64 string (but keep it a valid base64 string) before
// trying to decode it
b64[123] = (b64[123] == 'r' ? 'R' : 'r');
util::base64_decode(b64, &result);
ASSERT_EQ(data.size(), result.size());
ASSERT_NE(memcmp(data.data(), result.data(), data.size()), 0);
}
} // namespace qfsclient
| 24.389222 | 71 | 0.702922 | [
"vector"
] |
dc8d46077070799e289d2746461fb1ac0b82f8d6 | 5,249 | cpp | C++ | Modules/ContourModel/DataManagement/mitkContourModelSet.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | Modules/ContourModel/DataManagement/mitkContourModelSet.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | Modules/ContourModel/DataManagement/mitkContourModelSet.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModelSet.h>
#include <vtkMath.h>
#include <algorithm>
mitk::ContourModelSet::ContourModelSet() :
m_Contours(),
m_UpdateBoundingBox(true)
{
this->InitializeEmpty();
}
mitk::ContourModelSet::ContourModelSet(const mitk::ContourModelSet &other) :
mitk::BaseData(other),
m_Contours(other.m_Contours)
{
this->InitializeTimeGeometry(1);
}
mitk::ContourModelSet::~ContourModelSet()
{
this->m_Contours.clear();
}
void mitk::ContourModelSet::InitializeEmpty()
{
this->InitializeTimeGeometry(1);
m_Contours.resize(0);
}
void mitk::ContourModelSet::AddContourModel(mitk::ContourModel &contourModel)
{
this->m_Contours.push_back(&contourModel);
m_UpdateBoundingBox = true;
}
void mitk::ContourModelSet::AddContourModel(mitk::ContourModel::Pointer contourModel)
{
this->m_Contours.push_back(contourModel);
m_UpdateBoundingBox = true;
}
mitk::ContourModel* mitk::ContourModelSet::GetContourModelAt(int index) const
{
if( index >= 0 && static_cast<ContourModelListType::size_type>(index) < this->m_Contours.size() )
{
return this->m_Contours.at(index).GetPointer();
}
else
{
return NULL;
}
}
bool mitk::ContourModelSet::IsEmpty() const
{
return this->m_Contours.empty();
}
mitk::ContourModelSet::ContourModelListType* mitk::ContourModelSet::GetContourModelList()
{
return &(this->m_Contours);
}
bool mitk::ContourModelSet::RemoveContourModel(mitk::ContourModel* contourModel)
{
ContourModelSetIterator it = this->m_Contours.begin();
ContourModelSetIterator end = this->m_Contours.end();
//search for ContourModel and remove it if exists
while(it != end)
{
if((*it) == contourModel)
{
this->m_Contours.erase(it);
m_UpdateBoundingBox = true;
return true;
}
it++;
}
return false;
}
bool mitk::ContourModelSet::RemoveContourModelAt(int index)
{
if( index >= 0 && static_cast<ContourModelListType::size_type>(index) < this->m_Contours.size() )
{
this->m_Contours.erase(this->m_Contours.begin()+index);
m_UpdateBoundingBox = true;
return true;
}
else
{
return false;
}
}
void mitk::ContourModelSet::Clear()
{
this->m_Contours.clear();
m_UpdateBoundingBox = true;
}
void mitk::ContourModelSet::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
if(this->m_UpdateBoundingBox)
{
//update the bounds of the geometry according to the stored vertices
mitk::ScalarType mitkBounds[6];
//calculate the boundingbox at each timestep
typedef itk::BoundingBox<unsigned long, 3, ScalarType> BoundingBoxType;
typedef BoundingBoxType::PointsContainer PointsContainer;
int timesteps = this->GetTimeSteps();
//iterate over the timesteps
for(int currenTimeStep = 0; currenTimeStep < timesteps; currenTimeStep++)
{
//only update bounds if the contour was modified
if (this->GetMTime() > this->GetGeometry(currenTimeStep)->GetBoundingBox()->GetMTime())
{
mitkBounds[0] = 0.0;
mitkBounds[1] = 0.0;
mitkBounds[2] = 0.0;
mitkBounds[3] = 0.0;
mitkBounds[4] = 0.0;
mitkBounds[5] = 0.0;
BoundingBoxType::Pointer boundingBox = BoundingBoxType::New();
PointsContainer::Pointer points = PointsContainer::New();
mitk::ContourModelSet::ContourModelSetIterator contoursIt = this->Begin();
mitk::ContourModelSet::ContourModelSetIterator contoursEnd = this->End();
while(contoursIt!=contoursEnd)
{
mitk::ContourModel::VertexIterator it = contoursIt->GetPointer()->Begin(currenTimeStep);
mitk::ContourModel::VertexIterator end = contoursIt->GetPointer()->End(currenTimeStep);
//fill the boundingbox with the points
while(it != end)
{
Point3D currentP = (*it)->Coordinates;
BoundingBoxType::PointType p;
p.CastFrom(currentP);
points->InsertElement(points->Size(), p);
it++;
}
++contoursIt;
}
//construct the new boundingBox
boundingBox->SetPoints(points);
boundingBox->ComputeBoundingBox();
BoundingBoxType::BoundsArrayType tmp = boundingBox->GetBounds();
mitkBounds[0] = tmp[0];
mitkBounds[1] = tmp[1];
mitkBounds[2] = tmp[2];
mitkBounds[3] = tmp[3];
mitkBounds[4] = tmp[4];
mitkBounds[5] = tmp[5];
//set boundingBox at current timestep
BaseGeometry* geometry3d = this->GetGeometry(currenTimeStep);
geometry3d->SetBounds(mitkBounds);
}
}
this->m_UpdateBoundingBox = false;
}
GetTimeGeometry()->Update();
}
| 24.413953 | 99 | 0.654791 | [
"geometry"
] |
dc8d83dc62b3e2272de8348d95428a54cab1a671 | 14,026 | cpp | C++ | dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/io/src/davidsdk_grabber.cpp | hddxds/scripts_from_gi | afb8977c001b860335f9062464e600d9115ea56e | [
"Apache-2.0"
] | 2 | 2019-04-10T14:04:52.000Z | 2019-05-29T03:41:58.000Z | software/SLAM/ygz_slam_ros/Thirdparty/PCL/io/src/davidsdk_grabber.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | null | null | null | software/SLAM/ygz_slam_ros/Thirdparty/PCL/io/src/davidsdk_grabber.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T06:54:41.000Z | 2021-12-20T06:54:41.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2014-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Victor Lamoine (victor.lamoine@gmail.com)
*/
#include <pcl/pcl_config.h>
#include <pcl/io/davidsdk_grabber.h>
#include <pcl/exceptions.h>
#include <pcl/common/io.h>
#include <pcl/conversions.h>
#include <pcl/io/ply_io.h>
#include <pcl/io/vtk_lib_io.h>
#include <pcl/console/print.h>
#include <pcl/point_types.h>
// Possible improvements:
// TODO: Add presets for david::CodedLightPhaseShiftParams to enable easy scan quality changing
// TODO: Add texture support (call .Scan () instead of .Scan (false) and properly convert data
// TODO: Use mesh IDs rather than clearing all meshes every time
// TODO: In processGrabbing, start scanning again while transferring the mesh (not possible with SDK 1.5.2 because ExportMesh() is blocking)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pcl::DavidSDKGrabber::DavidSDKGrabber () :
client_connected_ (false),
running_ (false),
local_path_ ("C:/temp"),
remote_path_ ("C:/temp"),
file_format_ ("stl")
{
point_cloud_signal_ = createSignal<sig_cb_davidsdk_point_cloud> ();
mesh_signal_ = createSignal<sig_cb_davidsdk_mesh> ();
image_signal_ = createSignal<sig_cb_davidsdk_image> ();
point_cloud_image_signal_ = createSignal<sig_cb_davidsdk_point_cloud_image> ();
mesh_image_signal_ = createSignal<sig_cb_davidsdk_mesh_image> ();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pcl::DavidSDKGrabber::~DavidSDKGrabber () throw ()
{
try
{
stop ();
disconnect_all_slots<sig_cb_davidsdk_point_cloud> ();
disconnect_all_slots<sig_cb_davidsdk_mesh> ();
disconnect_all_slots<sig_cb_davidsdk_image> ();
disconnect_all_slots<sig_cb_davidsdk_point_cloud_image> ();
disconnect_all_slots<sig_cb_davidsdk_mesh_image> ();
}
catch (...)
{
// destructor never throws
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
david::ServerInfo
pcl::DavidSDKGrabber::connect (const std::string &address,
uint16_t port)
{
david::ServerInfo server_info;
if (client_connected_)
return (server_info);
try
{
david_.Connect (address, port);
client_connected_ = true;
}
catch (david::Exception& e)
{
e.PrintError ();
}
return (server_info);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::disconnect (const bool stop_server)
{
if (!client_connected_)
return;
try
{
david_.Disconnect (stop_server);
}
catch (david::Exception& e)
{
e.PrintError ();
}
client_connected_ = false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::start ()
{
if (isRunning ())
return;
frequency_.reset ();
running_ = true;
grabber_thread_ = boost::thread (&pcl::DavidSDKGrabber::processGrabbing, this);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::stop ()
{
if (running_)
{
running_ = false; // Stop processGrabbing () callback
grabber_thread_.join (); // join () waits for the thread to finish it's last iteration
// See: http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.thread.join
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::DavidSDKGrabber::isRunning () const
{
return (running_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::DavidSDKGrabber::isConnected () const
{
return (client_connected_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::DavidSDKGrabber::getName () const
{
return ("DavidSDKGrabber");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::DavidSDKGrabber::getLocalPath ()
{
return (local_path_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::DavidSDKGrabber::getRemotePath ()
{
return (remote_path_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setFileFormatToOBJ ()
{
file_format_ = "obj";
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setFileFormatToPLY ()
{
file_format_ = "ply";
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setFileFormatToSTL ()
{
file_format_ = "stl";
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::DavidSDKGrabber::getFileFormat ()
{
return (file_format_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setLocalPath (std::string path)
{
local_path_ = path;
if (path.empty ())
local_path_ = "C:/temp";
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setRemotePath (std::string path)
{
remote_path_ = path;
if (path.empty ())
remote_path_ = local_path_;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::setLocalAndRemotePaths (std::string local_path,
std::string remote_path)
{
setLocalPath (local_path);
setRemotePath (remote_path);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::DavidSDKGrabber::calibrate (double grid_size)
{
if (!client_connected_ || running_)
return (false);
try
{
david_.sls ().Calibrate (grid_size);
}
catch (david::Exception& e)
{
e.PrintError ();
return (false);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::DavidSDKGrabber::grabSingleCloud (pcl::PointCloud<pcl::PointXYZ> &cloud)
{
if (!client_connected_ || running_)
return (false);
try
{
david_.sls ().Scan (false);
david_.fusion ().DeleteAllMeshes ();
david_.sls ().AddScanToShapeFusion ();
david_.sls ().ExportMesh (remote_path_ + "scan." + file_format_);
pcl::PolygonMesh mesh;
if (file_format_ == "obj")
{
if (pcl::io::loadPolygonFileOBJ (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else if (file_format_ == "ply")
{
if (pcl::io::loadPolygonFilePLY (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else if (file_format_ == "stl")
{
if (pcl::io::loadPolygonFileSTL (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else
return (false);
pcl::fromPCLPointCloud2 (mesh.cloud, cloud);
}
catch (david::Exception& e)
{
e.PrintError ();
return (false);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::DavidSDKGrabber::grabSingleMesh (pcl::PolygonMesh &mesh)
{
if (!client_connected_ || running_)
return (false);
try
{
david_.sls ().Scan (false);
david_.fusion ().DeleteAllMeshes ();
david_.sls ().AddScanToShapeFusion ();
david_.sls ().ExportMesh (remote_path_ + "scan." + file_format_);
if (file_format_ == "obj")
{
if (pcl::io::loadPolygonFileOBJ (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else if (file_format_ == "ply")
{
if (pcl::io::loadPolygonFilePLY (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else if (file_format_ == "stl")
{
if (pcl::io::loadPolygonFileSTL (local_path_ + "scan." + file_format_, mesh) == 0)
return (false);
}
else
return (false);
}
catch (david::Exception& e)
{
e.PrintError ();
return (false);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float
pcl::DavidSDKGrabber::getFramesPerSecond () const
{
boost::mutex::scoped_lock lock (fps_mutex_);
return (frequency_.getFrequency ());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::DavidSDKGrabber::processGrabbing ()
{
bool continue_grabbing = running_;
while (continue_grabbing)
{
try
{
// Publish cloud / images
if (num_slots<sig_cb_davidsdk_point_cloud> () > 0 || num_slots<sig_cb_davidsdk_mesh> () > 0 || num_slots<sig_cb_davidsdk_image> () > 0
|| num_slots<sig_cb_davidsdk_point_cloud_image> () > 0 || num_slots<sig_cb_davidsdk_mesh_image> () > 0)
{
pcl::PolygonMesh::Ptr mesh;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
boost::shared_ptr<pcl::PCLImage> image;
fps_mutex_.lock ();
frequency_.event ();
fps_mutex_.unlock ();
// We need the image
if (num_slots<sig_cb_davidsdk_image> () > 0 || num_slots<sig_cb_davidsdk_point_cloud_image> () > 0 || num_slots<sig_cb_davidsdk_mesh_image> () > 0)
{
image.reset (new pcl::PCLImage);
int width, height;
david_.sls ().GetLiveImage (image->data, width, height);
image->width = (uint32_t) width;
image->height = (uint32_t) height;
image->encoding = "CV_8UC1";
}
// We need the cloud or mesh
if (num_slots<sig_cb_davidsdk_point_cloud> () > 0 || num_slots<sig_cb_davidsdk_mesh> () > 0 || num_slots<sig_cb_davidsdk_point_cloud_image> () > 0
|| num_slots<sig_cb_davidsdk_mesh_image> () > 0)
{
mesh.reset (new pcl::PolygonMesh);
david_.sls ().Scan (false);
david_.fusion ().DeleteAllMeshes ();
david_.sls ().AddScanToShapeFusion ();
david_.sls ().ExportMesh (remote_path_ + "scan." + file_format_);
if (file_format_ == "obj")
{
if (pcl::io::loadPolygonFileOBJ (local_path_ + "scan." + file_format_, *mesh) == 0)
return;
}
else if (file_format_ == "ply")
{
if (pcl::io::loadPolygonFilePLY (local_path_ + "scan." + file_format_, *mesh) == 0)
return;
}
else if (file_format_ == "stl")
{
if (pcl::io::loadPolygonFileSTL (local_path_ + "scan." + file_format_, *mesh) == 0)
return;
}
else
return;
if (num_slots<sig_cb_davidsdk_point_cloud> () > 0 || num_slots<sig_cb_davidsdk_point_cloud_image> () > 0)
{
cloud.reset (new PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2 (mesh->cloud, *cloud);
}
}
// Publish signals
if (num_slots<sig_cb_davidsdk_point_cloud_image> () > 0)
point_cloud_image_signal_->operator () (cloud, image);
if (num_slots<sig_cb_davidsdk_mesh_image> () > 0)
mesh_image_signal_->operator () (mesh, image);
else if (num_slots<sig_cb_davidsdk_point_cloud> () > 0)
point_cloud_signal_->operator () (cloud);
else if (num_slots<sig_cb_davidsdk_mesh> () > 0)
mesh_signal_->operator () (mesh);
else if (num_slots<sig_cb_davidsdk_image> () > 0)
image_signal_->operator () (image);
}
continue_grabbing = running_;
}
catch (david::Exception& e)
{
e.PrintError ();
}
}
}
| 31.44843 | 155 | 0.527877 | [
"mesh"
] |
dc8f5630ea2bf7ce468b57ce46f6214a3444452a | 7,123 | cpp | C++ | src/snake_game.cpp | yisonPylkita/snake-game | 16c0740bd158b22f338d0c80405020a77a2291c5 | [
"MIT"
] | 1 | 2020-11-11T10:04:35.000Z | 2020-11-11T10:04:35.000Z | src/snake_game.cpp | yisonPylkita/snake-game | 16c0740bd158b22f338d0c80405020a77a2291c5 | [
"MIT"
] | null | null | null | src/snake_game.cpp | yisonPylkita/snake-game | 16c0740bd158b22f338d0c80405020a77a2291c5 | [
"MIT"
] | null | null | null | #include <array>
#include <chrono>
#include <memory>
#include <vector>
#include <deque>
#include <random>
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
namespace {
namespace resources {
namespace textures {
constexpr uint32_t snake_segment_body = 0x01u;
// constexpr uint32_t snake_segment_head = 0x02u;
}
}
struct ResourceManager
{
void init()
{
load_texture("./assets/snake_segment_body.bmp", resources::textures::snake_segment_body);
}
const sf::Texture & texture(uint32_t resource_id) const
{
if (_textures.find(resource_id) == _textures.end())
throw std::invalid_argument("Texture '" + std::to_string(resource_id) + "' was not loaded");
return _textures.at(resource_id);
}
private:
void load_texture(const std::string &file_path, uint32_t id)
{
sf::Texture texture;
if (!texture.loadFromFile(file_path))
throw std::runtime_error("Texture '" + file_path + "' not found");
_textures[id] = texture;
}
private:
std::map<uint32_t, sf::Texture> _textures;
};
ResourceManager resource_manager;
struct SnakeSegment : public sf::Drawable
{
static constexpr uint32_t size_x = 50;
static constexpr uint32_t size_y = 50;
uint32_t pos_x;
uint32_t pos_y;
private :
void draw(sf::RenderTarget &target, sf::RenderStates states) const override
{
sf::Sprite segment_sprite;
segment_sprite.setPosition(pos_x, pos_y);
segment_sprite.setTexture(resource_manager.texture(resources::textures::snake_segment_body));
target.draw(segment_sprite, states);
}
};
struct Snake : public sf::Drawable
{
public:
void init() {
// Snake should start with a one segment
auto segment = SnakeSegment();
segment.pos_x = 600;
segment.pos_y = 300;
_segments.push_back(segment);
}
void set_direction(sf::Keyboard::Key direction) {
// Don't do 180 turns
using sf::Keyboard;
if (_direction == Keyboard::Left && direction == Keyboard::Right ||
_direction == Keyboard::Right && direction == Keyboard::Left ||
_direction == Keyboard::Up && direction == Keyboard::Down ||
_direction == Keyboard::Down && direction == Keyboard::Up) {
return;
}
_direction = direction;
}
void take_step() {
using sf::Keyboard;
auto new_snake_head_segment = _segments.front();
if (_direction == Keyboard::Up) {
new_snake_head_segment.pos_y -= SnakeSegment::size_y;
} else if (_direction == Keyboard::Down) {
new_snake_head_segment.pos_y += SnakeSegment::size_y;
} else if (_direction == Keyboard::Left) {
new_snake_head_segment.pos_x -= SnakeSegment::size_x;
} else if (_direction == Keyboard::Right) {
new_snake_head_segment.pos_x += SnakeSegment::size_x;
}
_segments.pop_back();
_segments.push_front(new_snake_head_segment);
}
sf::Vector2u last_segment_position() const {
const auto &segment = _segments.back();
return {segment.pos_x, segment.pos_y};
}
/// Will add given segment at the end of sanke segments
void make_longer(sf::Vector2u new_segment_position) {
auto segment = SnakeSegment{};
segment.pos_x = new_segment_position.x;
segment.pos_y = new_segment_position.y;
_segments.push_back(segment);
}
protected:
const std::deque<SnakeSegment> & get_segments() const
{
return _segments;
}
private :
void draw(sf::RenderTarget &target, sf::RenderStates states) const override
{
for (const auto &segment : _segments)
target.draw(segment, states);
}
private:
sf::Keyboard::Key _direction = sf::Keyboard::Up;
std::deque<SnakeSegment> _segments;
};
struct Candy : public sf::Drawable
{
void init() {
_rect.setSize(sf::Vector2f(50.f, 50.f));
_rect.setPosition(_position);
_rect.setFillColor(sf::Color::Red);
}
sf::Vector2u position() const {
return {static_cast<uint32_t>(_position.x), static_cast<uint32_t>(_position.y)};
}
void set_position(sf::Vector2u new_position) {
_position = sf::Vector2f(static_cast<float>(new_position.x), static_cast<float>(new_position.y));
_rect.setPosition(_position);
}
private :
void draw(sf::RenderTarget &target, sf::RenderStates states) const override
{
target.draw(_rect);
}
private:
sf::Vector2f _position = sf::Vector2f(50.f, 50.f);
sf::RectangleShape _rect;
};
Candy candy;
Snake snake{};
void handle_key(sf::Event::KeyEvent key) {
const auto direction = key.code;
if (direction == sf::Keyboard::Up || direction == sf::Keyboard::Down ||
direction == sf::Keyboard::Left || direction == sf::Keyboard::Right) {
snake.set_direction(key.code);
}
}
sf::Vector2u random_position() {
static std::random_device random_dev{};
static std::default_random_engine engine(random_dev());
std::uniform_int_distribution<uint32_t> uniform_dist(1, 14);
return {uniform_dist(engine) * 50, uniform_dist(engine) * 50};
}
void update_game() {
snake.take_step();
if (snake.last_segment_position() == candy.position()) {
snake.make_longer(candy.position());
// spawn candy at random position
candy.set_position(random_position());
}
}
void render_game_frame(sf::RenderWindow &window) {
window.clear(sf::Color::White);
window.draw(candy);
window.draw(snake);
window.display();
}
int main_impl()
{
resource_manager.init();
snake.init();
candy.init();
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
const sf::Time TimePerFrame = sf::seconds(1.f/60.f);
sf::RenderWindow window(sf::VideoMode(1280, 720), "Snake - the game");
window.setFramerateLimit(7);
// window.setVerticalSyncEnabled(true);
constexpr uint32_t time_step_in_ms = 16;
while (window.isOpen()) {
// sf::Time dt = clock.restart();
// timeSinceLastUpdate += dt;
// while (timeSinceLastUpdate > TimePerFrame) {
// timeSinceLastUpdate -= TimePerFrame;
// update_game(TimePerFrame.asMilliseconds());
update_game();
// }
// render game world
render_game_frame(window);
// handle user actions
sf::Event event{};
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::KeyPressed) {
handle_key(event.key);
}
}
}
return EXIT_SUCCESS;
}
}
int main()
{
int exit_code = EXIT_FAILURE;
try {
exit_code = main_impl();
} catch (const std::exception &ex) {
std::cout << "Unhandled exception " - ex.what() << std::endl;
} catch (...) {
std::cout << "Unhandled unrecognized exception" << std::endl;
}
return exit_code;
}
| 27.933333 | 105 | 0.628527 | [
"render",
"vector"
] |
dc9082584cf405eaa44cdaf887f7c30e3360d0cb | 37,200 | cpp | C++ | sparse/testing/testing_zgemv_cpu_gpu.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | 13 | 2018-03-25T01:03:31.000Z | 2022-03-31T09:12:23.000Z | sparse/testing/testing_zgemv_cpu_gpu.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | null | null | null | sparse/testing/testing_zgemv_cpu_gpu.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | 7 | 2018-03-24T23:33:28.000Z | 2022-01-25T18:41:03.000Z | /*
-- MAGMA (version 2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date
@precisions normal z -> c d s
@author Stephen Wood
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "magma_v2.h"
#include "magmasparse.h"
#include "testings.h"
/*******************************************************************************
Purpose
-------
ZGEMV performs one of the matrix-vector operations on the CPU
y := alpha*A*x + beta*y, or y := alpha*A^T*x + beta*y, or
y := alpha*A^H*x + beta*y,
where alpha and beta are scalars, x and y are vectors and A is an
m by n matrix.
Arguments
---------
@param[in]
transA transA is CHARACTER*1
On entry, TRANS specifies the operation to be performed as
follows:
transA = 'N' or 'n' y := alpha*A*x + beta*y.
transA = 'T' or 't' y := alpha*A^T*x + beta*y.
transA = 'C' or 'c' y := alpha*A^H*x + beta*y.
@param[in]
flip magma_int_t
0: transA unchanged, 1: transA reversed
@param[in]
m magma_int_t
number of rows of the matrix A.
@param[in]
n magma_int_t
number of columns of the matrix A.
@param[in]
alpha magmaDoubleComplex
scalar.
@param[in]
dA magma_z_matrix
input matrix dA.
@param[in]
aoff magma_int_t
the offset for the elements of dA.
@param[in]
ldda magma_int_t
the increment for the elements of dA.
@param[in]
dx magma_z_matrix
input vector dx.
@param[in]
xoff magma_int_t
the offset for the elements of dx.
@param[in]
incx magma_int_t
the increment for the elements of dx.
@param[in]
beta magmaDoubleComplex
scalar.
@param[in,out]
dy magma_z_matrix *
input vector dy.
@param[in]
yoff magma_int_t
the offset for the elements of dy.
@param[in]
incy magma_int_t
the increment for the elements of dy.
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zblas
*******************************************************************************/
extern "C"
void
magmablas_zgemv_cpu(
magma_trans_t transA, magma_int_t flip,
magma_int_t m, magma_int_t n,
magmaDoubleComplex alpha,
magma_z_matrix dA, magma_int_t aoff, magma_int_t ldda,
magma_z_matrix dx, magma_int_t xoff, magma_int_t incx,
magmaDoubleComplex beta,
magma_z_matrix *dy, magma_int_t yoff, magma_int_t incy,
magma_queue_t queue )
{
magma_int_t info = MAGMA_NOTCONVERGED;
magma_z_matrix A = {Magma_CSR}, x = {Magma_CSR}, y = {Magma_CSR};
TESTING_CHECK( magma_zmtransfer( dA, &A, Magma_DEV, Magma_CPU, queue ));
TESTING_CHECK( magma_zmtransfer( dx, &x, Magma_DEV, Magma_CPU, queue ));
TESTING_CHECK( magma_zmtransfer( *dy, &y, Magma_DEV, Magma_CPU, queue ));
printf("\nmagmablas_zgemv_cpu m=%d, n=%d ldda=%d\n",
A.num_rows, A.num_cols, A.ld);
if (flip==0) {
blasf77_zgemv( lapack_trans_const(transA),
&m, &n, &alpha, &A.val[aoff], &ldda, &x.val[xoff],
&incx, &beta, &y.val[yoff], &incy);
}
else if (flip==1) {
magma_trans_t transtmp;
if (transA==MagmaNoTrans)
transtmp = MagmaTrans;
else if (transA==MagmaTrans)
transtmp = MagmaNoTrans;
else if (transA==MagmaConjTrans) {
transtmp = MagmaNoTrans;
// TODO: congugate A.
}
blasf77_zgemv( lapack_trans_const(transtmp),
&m, &n, &alpha, &A.val[aoff], &ldda, &x.val[xoff],
&incx, &beta, &y.val[yoff], &incy);
}
TESTING_CHECK( magma_zmtransfer( y, dy, Magma_CPU, Magma_DEV, queue ));
cleanup:
// free resources
magma_zmfree( &A, queue );
magma_zmfree( &x, queue );
magma_zmfree( &y, queue );
}
/*******************************************************************************
Purpose
-------
Prints the residual of an input vector with respect to two reference
vectors.
Arguments
---------
@param[in]
dofs magma_int_t
number of elements in vectors.
@param[in]
dy magmaDoubleComplex_ptr
input vector dx.
@param[in]
dyTrans magmaDoubleComplex_ptr
first reference vector dx.
@param[in]
dyNoTrans magmaDoubleComplex_ptr
second reference vector dx.
@param[in]
dytmp magmaDoubleComplex_ptr
workspace.
@param[in]
ref magmaDoubleComplex
reference residual.
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zblas
*******************************************************************************/
extern "C"
void
magma_print_residual(
magma_int_t dofs,
magmaDoubleComplex_ptr dy,
magmaDoubleComplex_ptr dyTrans,
magmaDoubleComplex_ptr dyNoTrans,
magmaDoubleComplex_ptr dytmp,
magmaDoubleComplex ref,
magma_queue_t queue )
{
#define PRECISION_z
#if defined(PRECISION_d)
const magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magmaDoubleComplex res;
magma_zcopy( dofs, dy, 1, dytmp, 1, queue ); // dy to dytmp
magma_zaxpy( dofs, c_neg_one, dyTrans, 1, dy, 1, queue ); // dy = dy - y_ref
res = magma_dznrm2( dofs, dy, 1, queue ); // res = ||dy||
res /= ref;
printf("|y-yTrans|/|yTrans| = %20.16e\n", res);
magma_zaxpy( dofs, c_neg_one, dyNoTrans, 1, dytmp, 1, queue ); // dy = dy - y_ref
res = magma_dznrm2( dofs, dytmp, 1, queue ); // res = ||dy||
res /= ref;
printf("|y-yNoTrans|/|yNoTrans| = %20.16e\n", res);
#endif
}
/* ////////////////////////////////////////////////////////////////////////////
-- testing_zgemv() to determine interaction of row-major and column-major
ordering between zvinit(), magmablas_zgemv() on GPU, and blasf77_zgemv() on
CPU through hard-coded A matrix of doubles, a unit vector, x, and reference
solutions yNoTrans = A*x, yTrans = A'*x.
TODO: implement tests for complex A and x.
*/
int main( int argc, char** argv )
{
magma_int_t info = 0;
TESTING_CHECK( magma_init() );
magma_print_environment();
magma_zopts zopts;
magma_queue_t queue;
magma_queue_create( 0, &queue );
magmaDoubleComplex c_one = MAGMA_Z_MAKE(1.0, 0.0);
magmaDoubleComplex c_zero = MAGMA_Z_MAKE(0.0, 0.0);
const magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
const magma_int_t c_flip = 0;
magmaDoubleComplex ref, refsub, refsublr, res;
magma_z_matrix A={Magma_CSR}, dA={Magma_CSR};
magma_z_matrix dx={Magma_CSR}, dy={Magma_CSR}, dytmp={Magma_CSR};
magma_z_matrix yNoTrans={Magma_CSR}, dyNoTrans={Magma_CSR};
magma_z_matrix yTrans={Magma_CSR}, dyTrans={Magma_CSR};
magma_z_matrix yNoTranssub={Magma_CSR}, dyNoTranssub={Magma_CSR};
magma_z_matrix yTranssub={Magma_CSR}, dyTranssub={Magma_CSR};
magma_z_matrix yNoTranssublr={Magma_CSR}, dyNoTranssublr={Magma_CSR};
magma_z_matrix yTranssublr={Magma_CSR}, dyTranssublr={Magma_CSR};
#define PRECISION_z
#if defined(PRECISION_d)
TESTING_CHECK( magma_zvinit( &A, Magma_CPU, 4, 4, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dA, Magma_DEV, 4, 4, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dx, Magma_DEV, 4, 1, c_one, queue ));
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dytmp, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTrans, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTrans, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTrans, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTrans, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTranssub, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTranssub, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTranssub, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTranssub, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTranssublr, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTranssublr, Magma_DEV, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTranssublr, Magma_CPU, 4, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTranssublr, Magma_DEV, 4, 1, c_zero, queue ));
printf("+++++++++++++++++++++++++++++++++\n");
printf("ZGEMV operation on GPU and CPU compared for 4x4 matrix\n");
printf("+++++++++++++++++++++++++++++++++\n");
for (magma_int_t k=0; k<A.num_rows*A.num_cols; k++) {
A.val[k] = MAGMA_Z_MAKE(k, 0.);
}
printf("A set on cpu\n");
yTrans.val[0]=24.; yTrans.val[1]=28.; yTrans.val[2]=32.; yTrans.val[3]=36.;
yNoTrans.val[0]=6.; yNoTrans.val[1]=22.; yNoTrans.val[2]=38.; yNoTrans.val[3]=54.;
yTranssub.val[2]=38.; yTranssub.val[3]=54.;
yNoTranssub.val[0]=20.; yNoTranssub.val[1]=22.; yNoTranssub.val[2]=24.; yNoTranssub.val[3]=26.;
yTranssublr.val[2]=24.; yTranssublr.val[3]=26.;
yNoTranssublr.val[2]=21.; yNoTranssublr.val[3]=29.;
printf("y refs set on cpu\n");
TESTING_CHECK( magma_zmtransfer( A, &dA, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTrans, &dyNoTrans, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTrans, &dyTrans, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTranssub, &dyNoTranssub, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTranssub, &dyTranssub, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTranssublr, &dyNoTranssublr, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTranssublr, &dyTranssublr, Magma_CPU, Magma_DEV, queue ));
printf("Reference answer yTrans:\n");
magma_zprint_matrix(yTrans, queue);
printf("Reference answer yNoTrans:\n");
magma_zprint_matrix(yNoTrans, queue);
ref = magma_dznrm2( A.num_rows, dyNoTrans.dval, 1, queue );
refsub = magma_dznrm2( 2, &dyNoTranssub.dval[2], 1, queue );
refsublr = magma_dznrm2( 2, &dyNoTranssublr.dval[2], 1, queue );
printf("=======\tbefore magma_zgemv NoTrans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(dA, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magmablas_zgemv( MagmaNoTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv Trans line %d\n", __LINE__);
magmablas_zgemv( MagmaTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu Trans line row x col; ld %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv ConjTrans line %d\n", __LINE__);
magmablas_zgemv( MagmaConjTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv ConjTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
magmablas_zgemv_cpu( MagmaConjTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu ConjTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv NoTrans 2x4 lower submatrix line %d\n", __LINE__);
magmablas_zgemv( MagmaNoTrans, 2, dA.num_cols, c_one, &dA.dval[2*dA.ld], dA.ld,
dx.dval, 1, c_zero, &dy.dval[2], 1, queue );
printf("\tafter magma_zgemv NoTrans subrow x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, 2, dA.num_cols, c_one, dA, 2*dA.ld, dA.ld,
dx, 0, 1, c_zero, &dy, 2, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans subrow x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, dA.num_cols, 2, c_one, &dA.dval[2*dA.ld], dA.ld,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_cols, 2, c_one, dA, 2*dA.ld, dA.ld,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
magmablas_zgemv( MagmaTrans, dA.num_cols, 2, c_one, &dA.dval[2*dA.ld], dA.ld,
dx.dval, 1, c_zero, &dy.dval[2], 1, queue );
printf("\tafter magma_zgemv Trans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_cols, 2, c_one, dA, 2*dA.ld, dA.ld,
dx, 0, 1, c_zero, &dy, 2, 1, queue );
printf("\tafter magma_zgemv_cpu Trans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssub.dval[2], &dyNoTranssub.dval[2],
&dytmp.dval[2], refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 4, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv NoTrans 2x2 lower right submatrix line %d\n", __LINE__);
magmablas_zgemv( MagmaNoTrans, 2, 2, c_one, &dA.dval[2*dA.ld+2], dA.ld,
&dx.dval[2], 1, c_zero, &dy.dval[2], 1, queue );
printf("\tafter magma_zgemv NoTrans subrow x subcol; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssublr.dval[2], &dyNoTranssublr.dval[2],
&dytmp.dval[2], refsublr, queue );
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, 2, 2, c_one, dA, 2*dA.ld+2, dA.ld,
dx, 2, 1, c_zero, &dy, 2, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans subrow x subcol; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( 2, &dy.dval[2],
&dyTranssublr.dval[2], &dyNoTranssublr.dval[2],
&dytmp.dval[2], refsublr, queue );
magma_zmfree( &A, queue );
magma_zmfree( &dA, queue );
magma_zmfree( &dx, queue );
magma_zmfree( &dy, queue );
magma_zmfree( &yNoTrans, queue );
magma_zmfree( &dyNoTrans, queue );
magma_zmfree( &yTrans, queue );
magma_zmfree( &dyTrans, queue );
magma_zmfree( &yNoTranssub, queue );
magma_zmfree( &dyNoTranssub, queue );
magma_zmfree( &yTranssub, queue );
magma_zmfree( &dyTranssub, queue );
magma_zmfree( &yNoTranssublr, queue );
magma_zmfree( &dyNoTranssublr, queue );
magma_zmfree( &yTranssublr, queue );
magma_zmfree( &dyTranssublr, queue );
printf("\n\n+++++++++++++++++++++++++++++++++\n");
printf("ZGEMV operation on GPU and CPU compared for 5x3 matrix\n");
printf("+++++++++++++++++++++++++++++++++\n");
TESTING_CHECK( magma_zvinit( &A, Magma_CPU, 5, 3, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dA, Magma_DEV, 5, 3, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dx, Magma_DEV, 5, 1, c_one, queue ));
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dytmp, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTrans, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTrans, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTrans, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTrans, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTranssub, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTranssub, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTranssub, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTranssub, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yNoTranssublr, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyNoTranssublr, Magma_DEV, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &yTranssublr, Magma_CPU, 5, 1, c_zero, queue ));
TESTING_CHECK( magma_zvinit( &dyTranssublr, Magma_DEV, 5, 1, c_zero, queue ));
for (magma_int_t k=0; k<A.num_rows*A.num_cols; k++) {
A.val[k] = MAGMA_Z_MAKE(k, 0.);
}
yTrans.val[0]=30.; yTrans.val[1]=35.; yTrans.val[2]=40.; yTrans.val[3]=0.; yTrans.val[4]=0.;
yNoTrans.val[0]=3.; yNoTrans.val[1]=12.; yNoTrans.val[2]=21.; yNoTrans.val[3]=30.; yNoTrans.val[4]=39.;
yTranssub.val[0]=21.; yTranssub.val[1]=23.; yTranssub.val[2]=25.; yTranssub.val[3]=0.; yTranssub.val[4]=0.;
yNoTranssub.val[0]=30.; yNoTranssub.val[1]=39.; yNoTranssub.val[2]=0.; yNoTranssub.val[3]=0.; yNoTranssub.val[4]=0.;
yTranssublr.val[0]=30.; yTranssublr.val[1]=33.; yTranssublr.val[2]=0.; yTranssublr.val[3]=0.; yTranssublr.val[4]=0.;
yNoTranssublr.val[0]=15.; yNoTranssublr.val[1]=21.; yNoTranssublr.val[2]=27.; yNoTranssublr.val[3]=0.; yNoTranssublr.val[4]=0.;
TESTING_CHECK( magma_zmtransfer( A, &dA, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTrans, &dyNoTrans, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTrans, &dyTrans, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTranssub, &dyNoTranssub, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTranssub, &dyTranssub, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yNoTranssublr, &dyNoTranssublr, Magma_CPU, Magma_DEV, queue ));
TESTING_CHECK( magma_zmtransfer( yTranssublr, &dyTranssublr, Magma_CPU, Magma_DEV, queue ));
printf("yTrans:\n");
magma_zprint_matrix(yTrans, queue);
printf("yNoTrans:\n");
magma_zprint_matrix(yNoTrans, queue);
ref = magma_dznrm2( A.num_rows, dyNoTrans.dval, 1, queue );
refsub = magma_dznrm2( A.num_rows, dyNoTranssub.dval, 1, queue );
refsublr = magma_dznrm2( A.num_rows, dyNoTranssublr.dval, 1, queue );
printf("=======\tbefore magma_zgemv NoTrans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(A, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
printf("A.num_rows=%d A.num_cols=%d A.ld=%d\n", dA.num_rows, dA.num_cols, dA.ld);
magmablas_zgemv( MagmaNoTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_cols, dA.num_rows, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x row; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, dA.num_cols, dA.num_rows, c_one, dA.dval, dA.num_cols, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_cols, dA.num_rows, c_one, dA, 0, dA.num_cols, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
printf("=======\tbefore magma_zgemv NoTrans 2x3 lower submatrix line %d\n", __LINE__);
printf("subrow addressing by ld:\n");
for (int p=0; p<dA.num_rows; p++) {
printf("%d %e\n", p, A.val[p*dA.ld]);
}
printf("subrow addressing by num_cols:\n");
for (int p=0; p<dA.num_rows; p++) {
printf("%d %e\n", p, A.val[p*dA.num_cols]);
}
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, 2, dA.num_cols, c_one, &dA.dval[3*dA.num_cols], dA.ld,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans subrow x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, 2, dA.num_cols, c_one, dA, 3*dA.num_cols, dA.ld,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans subrow x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, dA.num_cols, 2, c_one, &dA.dval[3*dA.num_cols], dA.ld,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_cols, 2, c_one, dA, 3*dA.num_cols, dA.ld,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, dA.num_cols, 2, c_one, &dA.dval[3*dA.num_cols], dA.num_cols,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, dA.num_cols, 2, c_one, dA, 3*dA.num_cols, dA.num_cols,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaTrans, dA.num_cols, 2, c_one, &dA.dval[3*dA.num_cols], dA.num_cols,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_cols, 2, c_one, dA, 3*dA.num_cols, dA.num_cols,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu Trans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaTrans, dA.num_cols, 2, c_one, &dA.dval[3*dA.num_cols], dA.ld,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_cols, 2, c_one, dA, 3*dA.num_cols, dA.ld,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu Trans col x subrow; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssub.dval, dyNoTranssub.dval,
dytmp.dval, ref, queue );
printf("=======\tbefore magma_zgemv NoTrans 3x2 lower right submatrix line %d\n", __LINE__);
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaNoTrans, 2, 3, c_one, &dA.dval[2*dA.num_cols+1], dA.num_cols,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv NoTrans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssublr.dval, dyNoTranssublr.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaNoTrans, c_flip, 2, 3, c_one, dA, 2*dA.num_cols+1, dA.num_cols,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu NoTrans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssublr.dval, dyNoTranssublr.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv( MagmaTrans, 2, 3, c_one, &dA.dval[2*dA.num_cols+1], dA.num_cols,
dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssublr.dval, dyNoTranssublr.dval,
dytmp.dval, refsub, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, 2, 3, c_one, dA, 2*dA.num_cols+1, dA.num_cols,
dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu Trans col x subrow; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTranssublr.dval, dyNoTranssublr.dval,
dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv Trans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(A, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
printf("A.num_rows=%d A.num_cols=%d A.ld=%d\n", A.num_rows, A.num_cols, A.ld);
magmablas_zgemv( MagmaTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu Trans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv Trans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(dA, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
printf("A.num_rows=%d A.num_cols=%d A.ld=%d\n", A.num_rows, A.num_cols, A.ld);
magmablas_zgemv( MagmaTrans, dA.num_cols, dA.num_rows, c_one, dA.dval, dA.num_cols, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv Trans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaTrans, c_flip, dA.num_cols, dA.num_rows, c_one, dA, 0, dA.num_cols, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv Trans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
printf("=======\tbefore magma_zgemv ConjTrans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(A, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
printf("A.num_rows=%d A.num_cols=%d A.ld=%d\n", A.num_rows, A.num_cols, A.ld);
magmablas_zgemv( MagmaConjTrans, dA.num_rows, dA.num_cols, c_one, dA.dval, dA.ld, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv ConjTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaConjTrans, c_flip, dA.num_rows, dA.num_cols, c_one, dA, 0, dA.ld, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv ConjTrans row x col; ld line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
printf("\tbefore magma_zgemv Trans line %d\n", __LINE__);
printf("A:\n");
magma_zprint_matrix(A, queue);
printf("x:\n");
magma_zprint_matrix(dx, queue);
printf("y:\n");
magma_zprint_matrix(dy, queue);
printf("A.num_rows=%d A.num_cols=%d A.ld=%d\n", A.num_rows, A.num_cols, A.ld);
magmablas_zgemv( MagmaConjTrans, dA.num_cols, dA.num_rows, c_one, dA.dval, dA.num_cols, dx.dval, 1, c_zero, dy.dval, 1, queue );
printf("\tafter magma_zgemv ConjTrans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
TESTING_CHECK( magma_zvinit( &dy, Magma_DEV, 5, 1, c_zero, queue ));
magmablas_zgemv_cpu( MagmaConjTrans, c_flip, dA.num_cols, dA.num_rows, c_one, dA, 0, dA.num_cols, dx, 0, 1, c_zero, &dy, 0, 1, queue );
printf("\tafter magma_zgemv_cpu ConjTrans col x row; col line %d\n", __LINE__);
printf("y:\n");
magma_zprint_matrix(dy, queue);
magma_print_residual( A.num_rows, dy.dval, dyTrans.dval, dyNoTrans.dval, dytmp.dval, ref, queue );
#endif
magma_zmfree( &A, queue );
magma_zmfree( &dA, queue );
magma_zmfree( &dx, queue );
magma_zmfree( &dy, queue );
magma_zmfree( &yNoTrans, queue );
magma_zmfree( &dyNoTrans, queue );
magma_zmfree( &yTrans, queue );
magma_zmfree( &dyTrans, queue );
magma_zmfree( &yNoTranssub, queue );
magma_zmfree( &dyNoTranssub, queue );
magma_zmfree( &yTranssub, queue );
magma_zmfree( &dyTranssub, queue );
magma_zmfree( &yNoTranssublr, queue );
magma_zmfree( &dyNoTranssublr, queue );
magma_zmfree( &yTranssublr, queue );
magma_zmfree( &dyTranssublr, queue );
magma_queue_destroy( queue );
TESTING_CHECK( magma_finalize() );
return info;
}
| 45.532436 | 139 | 0.632339 | [
"vector"
] |
dc95f713a36d7216c578b621b9e5234bf782b077 | 5,271 | cpp | C++ | test/src/test_csv_input_parser.cpp | mgavin/csvio | 6ed72ae20e4991ea14aa108c2001f6124dcb1140 | [
"MIT"
] | null | null | null | test/src/test_csv_input_parser.cpp | mgavin/csvio | 6ed72ae20e4991ea14aa108c2001f6124dcb1140 | [
"MIT"
] | null | null | null | test/src/test_csv_input_parser.cpp | mgavin/csvio | 6ed72ae20e4991ea14aa108c2001f6124dcb1140 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019 Matthew Guidry
*
* 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 <list>
#include <string>
#include <string_view>
#include <vector>
#include "csv_io.hpp"
#include "gtest/gtest.h"
namespace {
TEST(CSVInputParserTest, SplitEmptyStringToVector) {
std::string to_split{""};
std::vector<std::string> expected{""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_naive(to_split, ','));
}
TEST(CSVInputParserTest, SplitSampleStringToVector) {
std::string to_split{"a,b,c,d,e"};
std::vector<std::string> expected{"a", "b", "c", "d", "e"};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_naive(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscEmptySVToVector) {
std::string_view to_split{""};
std::vector<std::string> expected{""};
EXPECT_EQ(
expected, csvio::util::CSVInputParser<std::vector>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToVector) {
std::string_view to_split{"\"a\",\"b\",\"c\""};
std::vector<std::string> expected{"a", "b", "c"};
EXPECT_EQ(
expected, csvio::util::CSVInputParser<std::vector>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToVectorThreaded) {
std::string_view to_split{"\"a\",\"b\",\"c\""};
std::vector<std::string> expected{"a", "b", "c"};
EXPECT_EQ(
expected, csvio::util::CSVInputParser<std::vector>::delim_split_unescaped_threaded(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToVectorNoUnescape) {
std::string_view to_split{"\"a\",\"b\",\"c\""};
std::vector<std::string> expected{"\"a\"", "\"b\"", "\"c\""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_escaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToVectorWithCommas) {
std::string_view to_split{"\"a,\",\"b,\",\"c,\""};
std::vector<std::string> expected{"a,", "b,", "c,"};
EXPECT_EQ(
expected, csvio::util::CSVInputParser<std::vector>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToVectorNoUnescapeWithCommas) {
std::string_view to_split{"\"a,\",\"b,\",\"c,\""};
std::vector<std::string> expected{"\"a,\"", "\"b,\"", "\"c,\""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_escaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEmptyStringToList) {
std::string to_split{""};
std::vector<std::string> expected{""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_naive(to_split, ','));
}
TEST(CSVInputParserTest, SplitSampleStringToList) {
std::string to_split{"a,b,c,d,e"};
std::vector<std::string> expected{"a", "b", "c", "d", "e"};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::vector>::delim_split_naive(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscEmptySVToList) {
std::string_view to_split{""};
std::list<std::string> expected{""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::list>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToList) {
std::string_view to_split{"\"a\",\"b\",\"c\""};
std::list<std::string> expected{"a", "b", "c"};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::list>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToListNoUnescape) {
std::string_view to_split{"\"a\",\"b\",\"c\""};
std::list<std::string> expected{"\"a\"", "\"b\"", "\"c\""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::list>::delim_split_escaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToListWithCommas) {
std::string_view to_split{"\"a,\",\"b,\",\"c,\""};
std::list<std::string> expected{"a,", "b,", "c,"};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::list>::delim_split_unescaped(to_split, ','));
}
TEST(CSVInputParserTest, SplitEscSVToListNoUnescapeWithCommas) {
std::string_view to_split{"\"a,\",\"b,\",\"c,\""};
std::list<std::string> expected{"\"a,\"", "\"b,\"", "\"c,\""};
EXPECT_EQ(expected, csvio::util::CSVInputParser<std::list>::delim_split_escaped(to_split, ','));
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 38.757353 | 105 | 0.694176 | [
"vector"
] |
dc9b0a2ac1795f4ceac4d924fd8d481abb33eebc | 32,199 | cpp | C++ | willow/src/transforms/randomsetup.cpp | graphcore/popart | 15ce5b098638dc34a4d41ae2a7621003458df798 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/transforms/randomsetup.cpp | graphcore/popart | 15ce5b098638dc34a4d41ae2a7621003458df798 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/transforms/randomsetup.cpp | graphcore/popart | 15ce5b098638dc34a4d41ae2a7621003458df798 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#include <popart/error.hpp>
#include <popart/graph.hpp>
#include <popart/ir.hpp>
#include <popart/names.hpp>
#include <popart/op.hpp>
#include <popart/op/call.hpp>
#include <popart/op/dropout.hpp>
#include <popart/op/getrandomseed.hpp>
#include <popart/op/ipucopy.hpp>
#include <popart/op/loop.hpp>
#include <popart/op/modifyrandomseed.hpp>
#include <popart/op/randombase.hpp>
#include <popart/opidentifier.hpp>
#include <popart/replicatedstreammode.hpp>
#include <popart/tensor.hpp>
#include <popart/tensors.hpp>
#include <popart/topocons.hpp>
#include <popart/transforms/randomsetup.hpp>
#include <popart/util.hpp>
#include "popart/tensornames.hpp"
#include "popart/vendored/optional.hpp"
#include <chrono>
#include <iostream>
#include <sstream>
namespace popart {
TensorInfo RandomSetup::seedTensorInfo(DataType::UINT32, {2});
std::size_t RandomSetup::id() { return typeid(RandomSetup).hash_code(); }
bool RandomSetup::apply(Graph &graph) const {
auto &ir = graph.getIr();
if (RandomSetup::requiresRandomSeed(ir)) {
logging::debug("[RandomSetup] Started.");
// Determine what we are going to do.
auto cfg = determineConfig(ir);
// Log what we are going to do.
logConfig(ir, cfg);
// Do the actual transformation step-wise.
for (auto &graphId : cfg.graphApplyOrder) {
applyToGraph(ir.getGraph(graphId), cfg);
}
logging::debug("[RandomSetup] Done.");
return true;
} else {
logging::debug("[RandomSetup] Nothing to do.");
}
return false;
}
RandomSetup::Config RandomSetup::determineConfig(const Ir &ir) const {
Config cfg;
// Work out what attributes we need to set for new ops.
cfg.setVirtualGraphIds = determineSetVirtualGraphIds(ir);
cfg.setExecutionPhases = determineSetExecutionPhases(ir);
cfg.setPipelineStages = determineSetPipelineStages(ir);
// Get op strand mapping and random ops mapping.
auto res = determineStrandsMapAndRandomOpsMap(ir);
cfg.strandsMap = std::get<0>(res);
cfg.randomOpsMap = std::get<1>(res);
// Get TensorIds for random seeds.
auto baseSeedMaps = determineBaseSeedsMaps(ir, cfg.strandsMap);
cfg.inBaseSeedMap = std::get<0>(baseSeedMaps);
cfg.outBaseSeedMap = std::get<1>(baseSeedMaps);
// Determine where to insert inputs/outputs.
auto seedIndexMaps = determineSeedIndexMaps(ir);
cfg.firstSeedInIndexMap = std::get<0>(seedIndexMaps);
cfg.firstSeedOutIndexMap = std::get<1>(seedIndexMaps);
// Determine order of application.
cfg.graphApplyOrder = determineGraphApplyOrder(ir);
return cfg;
}
bool RandomSetup::determineSetVirtualGraphIds(const Ir &ir) const {
return ir.virtualGraphsEnabled();
}
bool RandomSetup::determineSetExecutionPhases(const Ir &ir) const {
return ir.getSessionOptions().executionPhaseSettings.phases > 1;
}
bool RandomSetup::determineSetPipelineStages(const Ir &ir) const {
auto &opts = ir.getSessionOptions();
auto ops = ir.getAllOps();
auto opPred = [](Op *op) { return op->hasPipelineStage(); };
return opts.enablePipelining && std::all_of(ops.begin(), ops.end(), opPred);
}
RandomSetup::StrandsMapAndRandomOpsMap
RandomSetup::determineStrandsMapAndRandomOpsMap(const Ir &ir) const {
auto graphs = ir.getAllGraphs();
GraphToStrands strandsMap;
GraphToOpToStrands randomOpsMap;
// Initially populate randomOpsMap with all ops that are derived from
// RandomBaseOp. Note that there are also 'subgraph ops' that will need to be
// added later, but that's done in the while loop below.
std::transform(graphs.begin(),
graphs.end(),
std::inserter(randomOpsMap, randomOpsMap.end()),
[&](const Graph *graph) -> GraphToOpToStrands::value_type {
OpToStrands randomOps = getInitStrandToOps(*graph);
return {graph->id, randomOps};
});
// Initially populate 'strandsMap' with those strands that have an
// op attached to them in 'randomOpsMap'.
std::transform(graphs.begin(),
graphs.end(),
std::inserter(strandsMap, strandsMap.end()),
[&](const Graph *graph) -> GraphToStrands::value_type {
// Get keys from randomOpsMap.
Strands strands;
for (auto opIt = randomOpsMap.at(graph->id).begin();
opIt != randomOpsMap.at(graph->id).end();
++opIt) {
for (const auto &strand : opIt->second) {
if (std::find(strands.begin(), strands.end(), strand) ==
strands.end()) {
strands.push_back(strand);
}
}
}
return {graph->id, strands};
});
// Do fixed point calculation to properly populate both maps (e.g.
// to work out which graphs need a seed). Note that we need a fixed point
// because seeds requirements cascade through the IR -- that is, even if a
// subgraph itself has no random ops it may still require a seed because it
// contains a CallOp to a child subgraph that requires a seed.
while (true) {
bool hasChanged = false;
for (auto &graph : graphs) {
// If any subgraph op exists to a subgraph that is random, then this
// subgraph also needs a random seed, because we need to pass it to
// the subgraph.
auto &graphStrands = strandsMap.at(graph->id);
auto &graphRandomOps = randomOpsMap.at(graph->id);
for (auto &x : graph->getOps()) {
Op *op = x.second.get();
for (const auto &calledGraph : op->getCalledGraphs()) {
auto &strandsInCalledGraph = strandsMap.at(calledGraph->id);
for (auto &calledStrand : strandsInCalledGraph) {
auto graphStrandsIt = std::find(
graphStrands.begin(), graphStrands.end(), calledStrand);
if (graphStrandsIt == graphStrands.end()) {
// Log it.
logging::trace("[RandomSetup] Determined {} requires random seed "
"for strand {} because of Op {}.",
graph->getGraphString(),
calledStrand,
op->str());
// A subgraph op calls a subgraph that needs a random seed for a
// strand and we haven't marked this strand as needed in this
// graph as yet. Record it now.
graphStrands.push_back(calledStrand);
// We haven't reached a fixed point yet.
hasChanged = true;
}
// The calledStrand should be a member of graphRandomOps[op].
auto &opStrands = graphRandomOps[op];
auto opStrandsIt =
std::find(opStrands.begin(), opStrands.end(), calledStrand);
if (opStrandsIt == opStrands.end()) {
opStrands.push_back(calledStrand);
// Log it.
logging::trace("[RandomSetup] Determined {} requires random seed "
"for strand {} because of called {} of Op {}.",
graph->getGraphString(),
calledStrand,
calledGraph->getGraphString(),
op->str());
// We haven't reached a fixed point yet.
hasChanged = true;
}
}
}
}
}
if (!hasChanged) {
// Fixpoint!
break;
}
}
return {strandsMap, randomOpsMap};
}
RandomSetup::OpToStrands
RandomSetup::getInitStrandToOps(const Graph &graph) const {
// Get an initial mapping from strands to a list of ops for a given graph,
// just populating with those ops derived from RandomBaseOp for now.
OpToStrands randomOps;
for (auto &x : graph.getOps()) {
Op *op = x.second.get();
if (auto randomOp = dynamic_cast<RandomBaseOp *>(op)) {
if (!randomOp->hasInput(randomOp->getSeedInIndex())) {
auto strand = getStrand(randomOp);
randomOps[randomOp].push_back(strand);
// Log it.
logging::trace("[RandomSetup] Determined {} requires random seed "
"for strand {} because of Op {}.",
graph.getGraphString(),
strand,
randomOp->str());
}
}
}
return randomOps;
}
RandomSetup::InAndOutBaseSeedMap
RandomSetup::determineBaseSeedsMaps(const Ir &ir,
const GraphToStrands &strandsMap) const {
GraphToStrandToTensorId inBaseSeedIds;
GraphToStrandToTensorId outBaseSeedIds;
for (const auto &entry : strandsMap) {
const auto &graphId = entry.first;
const auto &opStrands = entry.second;
const auto &graph = ir.getGraph(graphId);
if (graphId == ir.getMainGraph().id) {
// The main graph always uses the output of the GetRandomSeedOp, hence use
// [randomSeed___updated] for all strands.
for (auto &strand : opStrands) {
inBaseSeedIds[graphId][strand] =
GetRandomSeedOp::getUpdatedSeedTensorId();
}
// No out base seeds needed for main graph. Outputs are only used on
// subgraphs.
} else {
// Introduce new TensorIds specifically for this graph/strand of the form
// <graph_id>
for (auto &strand : opStrands) {
auto id = ModifyRandomSeedOp::getSeedInTensorId();
id = getTensorIdForStrand(id, strand);
inBaseSeedIds[graphId][strand] = addScope(graph, id + "_in");
outBaseSeedIds[graphId][strand] = addScope(graph, id + "_out");
}
}
}
return {inBaseSeedIds, outBaseSeedIds};
}
RandomSetup::FirstSeedInIndexMapAndFirstSeedOutIndexMap
RandomSetup::determineSeedIndexMaps(const Ir &ir) const {
GraphToInIndex inIndices;
GraphToOutIndex outIndices;
const int loopFirstInput = LoopOp::getLoopGraphFirstInputInIndex();
const int loopFirstOutput = LoopOp::getLoopGraphFirstOutputOutIndex();
for (const auto &graph : ir.getAllGraphs()) {
// Work out a suitable place to put the input index for a base seed input
// in a subgraph. Note that if subgraph is used as a loop body inputs are
// offset by the loop iteration counter and the loop conditional inputs.
// Additionally, any explicit input needs to have an associated output. We
// want the seed to be an explicit input because it needs to be updated in
// every loop iteration, so it should be added to the list of explicit
// inputs. Our way of making sure this happens safely is by adding it
// immediately after the loop condition input, if it exists. Note that
// a subgraph need not be used in a loop, so we also need to deal with a
// scenario where the number of inputs does not allow us to put the input
// after the loop condition input.
OutIndex loopBodyIn = loopFirstInput;
// Cap input index by the number of inputs.
loopBodyIn = std::min<InIndex>(loopBodyIn, graph->getInputIds().size());
inIndices[graph->id] = loopBodyIn;
// Work out a suitable place to put the base seed output. We need to make
// sure that in subgraphs that are used as loop bodies these outputs are
// loop carried with the base seed inputs. To do this, we need to correct
// for the offset caused by the loop iteration and loop condition inputs
// as well as the loop condition output. Bear in mind the subgraph may not
// be a loop body -- this code needs to work for any subgraph.
OutIndex loopBodyOut = loopBodyIn - loopFirstInput + loopFirstOutput;
// Cap output index by the number of output.
loopBodyOut = std::min<OutIndex>(loopBodyOut, graph->getOutputIds().size());
// Index can't be less than 0.
loopBodyOut = std::max<OutIndex>(loopBodyOut, 0);
outIndices[graph->id] = loopBodyOut;
}
return {inIndices, outIndices};
}
RandomSetup::GraphIds
RandomSetup::determineGraphApplyOrder(const Ir &ir) const {
const auto &graphs = ir.getAllGraphs();
// We need called subgraphs to have been transformed before we transform
// the ops that call them. To that end, we're restricted in the order in
// which we can transform graphs. We determine that order in this function.
GraphIds done;
GraphIds todo;
// Start with all graph ids in todo.
std::transform(graphs.begin(),
graphs.end(),
std::back_inserter(todo),
[](auto &graph) { return graph->id; });
// Checks if a graph is in done.
auto calledGraphInDone = [&](const Graph *calledGraph) {
auto doneIt = std::find(done.begin(), done.end(), calledGraph->id);
return doneIt != done.end();
};
// Check if all called graphs are in done.
using GetOpsEntry = std::pair<const OpId, std::unique_ptr<popart::Op>>;
auto opsCalledGraphsInDone = [&](const GetOpsEntry &entry) {
const auto &op = entry.second;
auto opCalledGraphs = op->getCalledGraphs();
return std::all_of(
opCalledGraphs.begin(), opCalledGraphs.end(), calledGraphInDone);
};
// While we still have graph ids in todo.
while (!todo.empty()) {
// Iterate over the todo list.
for (auto todoIt = todo.begin(); todoIt != todo.end(); /* not here */) {
const auto &graph = ir.getGraph(*todoIt);
bool allCalledGraphsDone = std::all_of(
graph.getOps().begin(), graph.getOps().end(), opsCalledGraphsInDone);
if (allCalledGraphsDone) {
// Graph can be applied now, iterator to point to next element.
done.push_back(*todoIt);
todoIt = todo.erase(todoIt);
} else {
// Move on to next graph.
++todoIt;
}
}
}
return done;
}
void RandomSetup::logConfig(const Ir &ir, const Config &cfg) const {
// This function just logs the 'cfg' object which defines all paramters
// of the transformation we are about to do.
// Log application order.
std::vector<std::string> graphStrs;
std::transform(cfg.graphApplyOrder.begin(),
cfg.graphApplyOrder.end(),
std::back_inserter(graphStrs),
[&](GraphId id) { return ir.getGraph(id).getGraphString(); });
logging::trace("[RandomSetup] Determined [{}] is a valid application order.",
logging::join(graphStrs.begin(), graphStrs.end(), ", "));
// Log each graph's params.
for (const auto &graphId : cfg.graphApplyOrder) {
auto &graph = ir.getGraph(graphId);
const Strands &strands = cfg.strandsMap.at(graphId);
if (!strands.empty()) {
// Create a string to log the strands for this graph.
auto graphStrandsStr =
logging::join(strands.begin(), strands.end(), ", ");
logging::trace("[RandomSetup] Determined a random seed is required for "
"strand(s) {} in {} because:",
graphStrandsStr,
graph.getGraphString());
for (auto entry : cfg.randomOpsMap.at(graphId)) {
auto op = entry.first;
auto &strands = entry.second;
auto opStrandsStr = logging::join(strands.begin(), strands.end(), ", ");
logging::trace("[RandomSetup] - op '{}' needs seed(s) for strand(s) "
"{}",
op->str(),
opStrandsStr);
}
} else {
logging::trace("[RandomSetup] {} does not require a random seed.",
graph.getGraphString());
}
}
}
void RandomSetup::applyToGraph(Graph &graph, const Config &cfg) const {
// Log what we are doing.
logging::debug("[RandomSetup] Started transforming {}.",
graph.getGraphString());
// Add base seeds for this graph as per the config.
addBaseSeeds(graph, cfg);
// Add seeds for operations in the graph.
auto opSeeds = addModifyRandomSeedOps(graph, cfg);
// Connect up seed tensors to all the ops in the graph.
for (const auto &entry : cfg.randomOpsMap.at(graph.id)) {
Op *op = entry.first;
connectOp(graph, cfg, opSeeds.at(op), op);
}
// Log what we are doing.
logging::debug("[RandomSetup] Done transforming {}.", graph.getGraphString());
}
void RandomSetup::addBaseSeeds(Graph &graph, const Config &cfg) const {
bool isMainGraph = (graph.getIr().getMainGraph().id == graph.id);
if (isMainGraph) {
// The GetRandomSeedOp adds these base seeds.
addGetRandomSeedOp(graph.getIr(), cfg);
} else {
// Add input tensors for base seeds.
for (const auto &strand : cfg.strandsMap.at(graph.id)) {
// Add graph input for strand.
auto inBaseSeedId = cfg.inBaseSeedMap.at(graph.id).at(strand);
auto inIndex = cfg.firstSeedInIndexMap.at(graph.id);
graph.addInput(inIndex, inBaseSeedId, seedTensorInfo, false);
logging::trace("[RandomSetup] Added {} to {} as graph input #{} for "
"strand {}",
inBaseSeedId,
graph.getGraphString(),
inIndex,
strand);
// Add graph output for strand.
auto outBaseSeedId = cfg.outBaseSeedMap.at(graph.id).at(strand);
auto outIndex = cfg.firstSeedOutIndexMap.at(graph.id);
graph.getTensors().addActGrad(outBaseSeedId, "seedOutput");
auto tensor = graph.getTensors().get(outBaseSeedId);
tensor->info = seedTensorInfo;
graph.markAsOutput(outIndex, outBaseSeedId, false);
logging::trace("[RandomSetup] Added {} to {} as graph output #{} for "
"strand {}",
outBaseSeedId,
graph.getGraphString(),
outIndex,
strand);
}
}
}
void RandomSetup::addGetRandomSeedOp(Ir &ir, const Config &cfg) const {
auto &graph = ir.getMainGraph();
// 1. Create [randomSeed___fromHost] tensor.
TensorId randomSeedFromHost = GetRandomSeedOp::getStreamedSeedTensorId();
graph.getTensors().addStream(randomSeedFromHost, seedTensorInfo);
Tensor &seedTensor = *graph.getTensors().get(randomSeedFromHost);
seedTensor.setReplicatedStreamMode(ReplicatedStreamMode::Replicate);
logging::debug("[RandomSetup] Added tensor {}.", randomSeedFromHost);
// 2. Create TensorId for [randomSeed___updated] (created later).
TensorId randomSeedUpdated = GetRandomSeedOp::getUpdatedSeedTensorId();
// 3. Create GetRandomSeedOp.
Op::Settings settings(graph, "");
auto getRandomSeedOp = std::make_unique<GetRandomSeedOp>(
Onnx::CustomOperators::GetRandomSeed, settings);
// Connect input.
getRandomSeedOp->connectInTensor(getRandomSeedOp->getSeedInIndex(),
randomSeedFromHost);
// Create and connect output.
getRandomSeedOp->createAndConnectOutTensor(
GetRandomSeedOp::getUpdatedSeedOutIndex(), randomSeedUpdated);
// Configure it.
if (cfg.setExecutionPhases) {
getRandomSeedOp->setExecutionPhase(0);
}
if (cfg.setVirtualGraphIds) {
getRandomSeedOp->setVirtualGraphId(0);
}
if (cfg.setPipelineStages) {
getRandomSeedOp->setPipelineStage(0);
}
// Call setup.
getRandomSeedOp->setup();
// Log it.
logging::debug("[RandomSetup] Created op {} in {}.",
getRandomSeedOp->str(),
graph.getGraphString());
// Add to graph.
graph.moveIntoGraph(std::move(getRandomSeedOp));
}
TensorId
RandomSetup::addModifyRandomSeedOp(Graph &graph,
const Config &cfg,
const Strand &strand,
uint32_t modifier,
nonstd::optional<TensorId> opSeedId,
const std::string &seedReasonStr) const {
TensorId inBaseSeedId = cfg.inBaseSeedMap.at(graph.id).at(strand);
auto constId = ModifyRandomSeedOp::getSeedModifierTensorId(modifier);
constId = getTensorIdForStrand(constId, strand);
constId = addScope(graph, constId);
// Insert a constant tensor modifier for this op.
std::vector<uint32_t> modifierData(1, {modifier});
TensorInfo modifierInfo(DataType::UINT32, {});
graph.getTensors().addConstInit(
constId, modifierInfo, reinterpret_cast<void *>(modifierData.data()));
auto &virtualGraphId = std::get<0>(strand);
auto &pipelineStage = std::get<1>(strand);
Op::Settings settings(graph, "");
auto modifyRandomSeedOp = std::make_unique<ModifyRandomSeedOp>(
Onnx::CustomOperators::ModifyRandomSeed, settings);
modifyRandomSeedOp->connectInTensor(modifyRandomSeedOp->getSeedInIndex(),
inBaseSeedId);
modifyRandomSeedOp->connectInTensor(
modifyRandomSeedOp->getSeedModifierInIndex(), constId);
if (!opSeedId) {
// If opSeedId is not set, we're creating a new tensor to hold the seed
// for the op.
TensorId outId = ModifyRandomSeedOp::getModifiedSeedTensorId(modifier);
outId = getTensorIdForStrand(outId, strand);
outId = addScope(graph, outId);
modifyRandomSeedOp->createAndConnectOutTensor(
ModifyRandomSeedOp::getModifiedSeedOutIndex(), outId);
} else {
// If opSeedId is set, we're using an existing graph output.
modifyRandomSeedOp->connectOutTensor(
ModifyRandomSeedOp::getModifiedSeedOutIndex(), *opSeedId);
}
modifyRandomSeedOp->setup();
// Configure it.
if (cfg.setExecutionPhases) {
modifyRandomSeedOp->setExecutionPhase(0);
}
if (cfg.setVirtualGraphIds) {
modifyRandomSeedOp->setVirtualGraphId(virtualGraphId);
}
if (cfg.setPipelineStages) {
modifyRandomSeedOp->setPipelineStage(pipelineStage);
}
logging::debug("[RandomSetup] Added op {} to {} in strand {} to provide "
"seeds for {}. ",
modifyRandomSeedOp->debugName(),
graph.getGraphString(),
strand,
seedReasonStr);
// Get output tensor id before we move the op and invalidate the pointer.
auto result = modifyRandomSeedOp->output->id(
ModifyRandomSeedOp::getModifiedSeedOutIndex());
graph.moveIntoGraph(std::move(modifyRandomSeedOp));
return result;
}
void RandomSetup::connectOp(Graph &graph,
const Config &cfg,
const StrandToTensorId &opSeeds,
Op *op) const {
// It would be nice to design this code in a way that did not involve
// dynamic casts. We deal with RandomBaseOps, CallOps, etc., separately.
if (auto randomOp = dynamic_cast<RandomBaseOp *>(op)) {
connectRandomBaseOp(graph, cfg, opSeeds, randomOp);
} else if (auto callOp = dynamic_cast<CallOp *>(op)) {
connectSubgraphOp(graph, cfg, opSeeds, callOp, 0, 0);
} else if (auto loopOp = dynamic_cast<LoopOp *>(op)) {
connectSubgraphOp(graph,
cfg,
opSeeds,
loopOp,
0,
LoopOp::getLoopGraphFirstOutputOutIndex());
} else {
throw internal_error("[RandomSetup] Random behaviour that requires "
"instrumentation of {} ops is currently not "
"supported",
op->opid);
}
}
void RandomSetup::connectRandomBaseOp(Graph &graph,
const Config &cfg,
const StrandToTensorId &opSeeds,
RandomBaseOp *op) const {
// A RandomBaseOp basically just needs it's seed tensor input connecting. We
// do that here. We also check that the opSeeds map contains a seed only
// for the strand that the random op is in.
const auto &opStrand = getStrand(op);
auto opSeedsIt = opSeeds.find(opStrand);
if (opSeeds.size() != 1 || opSeedsIt == opSeeds.end()) {
// Get strands into a vector so it's easier to add to error message.
std::vector<Strand> strands;
for (const auto &entry : opSeeds) {
strands.push_back(entry.first);
}
throw internal_error("[RandomSetup] Expected only a seed for {} for op "
"{} (got seeds for {})",
opStrand,
op->str(),
logging::join(strands.begin(), strands.end(), ", "));
}
logging::trace("[RandomSetup] Setting seed tensor to {} for {}.",
opSeedsIt->second,
op->str());
op->connectInTensor(op->getSeedInIndex(), opSeedsIt->second);
op->setup();
}
void RandomSetup::connectSubgraphOp(Graph &graph,
const Config &cfg,
const StrandToTensorId &opSeeds,
SubgraphOp *op,
int inputOffset,
int outputOffset) const {
// LoopOps are responsible for passing through seeds to the loop body so that
// seeds are available for ops/strands. We have previously added such seeds
// as inputs and now we need to connect the LoopOps with tensors in opSeeds
// in accordance to those subgraph inputs. We want the seed to be an explicit
// inputs that are updated in every loop iteration.
auto &calledGraph = op->getCalledGraph();
const auto &opStrands = cfg.randomOpsMap.at(graph.id).at(op);
// We have added inputs/outputs to subgraph. This may have messed up inputs
// and outputs that were already connected to the subgraph op. We need to
// move affected inputs/outputs to later indices before we connect up the
// input/output base seeds.
int moveAmount = opStrands.size();
// Move inputs.
int maxIn = op->input->maxIndex();
int firstInToMove = cfg.firstSeedInIndexMap.at(calledGraph.id) - inputOffset;
for (InIndex i = maxIn; i >= firstInToMove; --i) {
if (op->input->hasIndex(i)) {
Tensor *t = op->input->tensorMap().at(i);
op->disconnectInTensor(t);
op->connectInTensor(i + moveAmount, t->id);
}
}
// Move outputs.
int maxOut = op->output->maxIndex();
int firstOutToMove =
cfg.firstSeedOutIndexMap.at(calledGraph.id) - outputOffset;
for (InIndex i = maxOut; i >= firstOutToMove; --i) {
if (op->output->hasIndex(i)) {
Tensor *t = op->output->tensorMap().at(i);
op->disconnectOutTensor(t);
op->connectOutTensor(i + moveAmount, t->id);
}
}
for (const auto &strand : cfg.randomOpsMap.at(graph.id).at(op)) {
// Get the seed allocated to this strand/op.
auto opSeedsIt = opSeeds.find(strand);
if (opSeedsIt == opSeeds.end()) {
throw internal_error("[RandomSetup] Expected seed for strand {} to be "
"available (needed to transform op {}). ",
strand,
op->str());
}
// Work out the id of the graph input.
auto inBaseSeedId = cfg.inBaseSeedMap.at(calledGraph.id).at(strand);
if (!calledGraph.hasInputId(inBaseSeedId)) {
throw internal_error("[RandomSetup] Expected {} to have graph "
"input {} (needed to transform op {}). ",
calledGraph.getGraphString(),
inBaseSeedId,
op->str());
}
// Connect the tensor to the correct CallOp input.
InIndex index = calledGraph.getInputIndex(inBaseSeedId) - inputOffset;
op->connectInTensor(index, opSeedsIt->second);
// We need to set an output here to make a loop carried dependency. We
// invent a new tensor name for this, using the op->id value
// to ensure it's uniqueness. We don't actually use this tensor anywhere.
auto outBaseSeedId = cfg.outBaseSeedMap.at(calledGraph.id).at(strand);
if (!calledGraph.hasOutputId(outBaseSeedId)) {
throw internal_error("[RandomSetup] Expected {} to have graph "
"output {} (needed to transform op {}). ",
calledGraph.getGraphString(),
outBaseSeedId,
op->str());
}
OutIndex outIndex =
calledGraph.getOutputIndex(outBaseSeedId) - outputOffset;
TensorId outId = TensorId(reservedRandomSeedPrefix()) + "_loopcarry" +
std::to_string(op->id);
outId = getTensorIdForStrand(outId, strand);
outId = addScope(graph, outId);
op->createAndConnectOutTensor(outIndex, outId);
logging::trace("[RandomSetup] Passing seed tensor {} to {} in {} "
"via {}.",
opSeedsIt->second,
inBaseSeedId,
calledGraph.getGraphString(),
op->str());
}
op->setup();
}
RandomSetup::OpToStrandToTensorId
RandomSetup::addModifyRandomSeedOps(Graph &graph, const Config &cfg) const {
OpToStrandToTensorId opSeeds;
uint32_t modifier = 0u;
// Add a ModifyRandomSeedOp for every op that needs a random seed in the
// graph. Note that some ops may need a seed for more than one strand.
for (const auto &opsToStrandsEntry : cfg.randomOpsMap.at(graph.id)) {
auto op = opsToStrandsEntry.first;
const auto &strands = opsToStrandsEntry.second;
for (const auto &strand : strands) {
// Adding op seed for random op/strand.
auto str = op->str();
auto out = addModifyRandomSeedOp(
graph, cfg, strand, modifier++, nonstd::optional<TensorId>(), str);
// Remember this.
opSeeds[op][strand] = out;
}
}
// If this isn't the main graph, add a addModifyRandomSeedOp for each strand
// to populate the output base seed. This can be used by loops as loop
// carried dependencies.
if (graph.id != graph.getIr().getMainGraph().id) {
for (const auto &entry : cfg.outBaseSeedMap.at(graph.id)) {
const auto &strand = entry.first;
const auto &outBaseSeed = entry.second;
addModifyRandomSeedOp(graph,
cfg,
strand,
modifier++,
outBaseSeed,
"subgraph's base seed output (may be unused)");
}
}
return opSeeds;
}
bool RandomSetup::hasRandomOps(const Ir &ir) {
auto ops = ir.getAllOps();
return std::any_of(ops.begin(), ops.end(), [](const Op *op) {
return op->isConvertibleTo<RandomBaseOp>();
});
}
bool RandomSetup::requiresRandomSeed(const Ir &ir) {
return (RandomSetup::hasRandomOps(ir) ||
ir.getSessionOptions().enableStochasticRounding);
}
bool RandomSetup::hasRandomSeed(const Ir &ir) {
return ir.containsTensor(GetRandomSeedOp::getStreamedSeedTensorId());
}
TensorId RandomSetup::getStreamedSeedTensorId() {
return GetRandomSeedOp::getStreamedSeedTensorId();
}
RandomSetup::Strand RandomSetup::getStrand(const Op *op) {
Strand key(unusedVGraphId, unusedPipelineStage);
if (op->hasVirtualGraphId()) {
std::get<0>(key) = op->getVirtualGraphId();
}
if (op->hasPipelineStage()) {
std::get<1>(key) = op->getPipelineStage();
}
return key;
}
TensorId RandomSetup::getTensorIdForStrand(const TensorId &id,
const Strand &strand) {
auto &virtualGraphId = std::get<0>(strand);
auto &pipelineStage = std::get<1>(strand);
TensorId res = id;
if (virtualGraphId >= 0) {
res += "_vgid" + std::to_string(virtualGraphId);
}
if (pipelineStage >= 0) {
res += "_stage" + std::to_string(pipelineStage);
}
return res;
}
std::ostream &operator<<(std::ostream &out, const RandomSetup::Strand &strand) {
auto &virtualGraphId = std::get<0>(strand);
auto &pipelineStage = std::get<1>(strand);
out << "(vgid=";
if (virtualGraphId >= 0) {
out << virtualGraphId;
} else {
out << "N/A";
}
out << ", stage=";
if (pipelineStage >= 0) {
out << pipelineStage;
} else {
out << "N/A";
}
out << ")";
return out;
}
namespace {
// RandomSetup.
bool init = Transform::registerTransform(new RandomSetup());
} // namespace
} // namespace popart
| 35.500551 | 80 | 0.620951 | [
"object",
"vector",
"transform"
] |
dc9c426d138a781bfa21478915dc53fbe069428e | 4,078 | cpp | C++ | partners_api/maxim_api.cpp | AddisMap/omim | 3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b | [
"Apache-2.0"
] | null | null | null | partners_api/maxim_api.cpp | AddisMap/omim | 3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b | [
"Apache-2.0"
] | null | null | null | partners_api/maxim_api.cpp | AddisMap/omim | 3e7e4ed7b24f12a7d6cabf4d83b968523f150f1b | [
"Apache-2.0"
] | null | null | null | #include "partners_api/maxim_api.hpp"
#include "platform/http_client.hpp"
#include "platform/platform.hpp"
#include "geometry/latlon.hpp"
#include "base/logging.hpp"
#include "std/target_os.hpp"
#include <iomanip>
#include <limits>
#include <sstream>
#include "3party/jansson/myjansson.hpp"
#include "private.h"
namespace
{
double const kSecInMinute = 60.;
bool RunSimpleHttpRequest(std::string const & url, std::string & result)
{
platform::HttpClient request(url);
return request.RunHttpRequest(result);
}
} // namespace
namespace taxi
{
namespace maxim
{
std::string const kTaxiInfoUrl = "http://cabinet.taximaxim.ru/Services/Public.svc";
bool RawApi::GetTaxiInfo(ms::LatLon const & from, ms::LatLon const & to, std::string & result,
std::string const & baseUrl /* = kTaxiInfoUrl */)
{
std::ostringstream url;
url << std::fixed << std::setprecision(6) << baseUrl
<< "/CalculateByCoords?version=1.0&platform=WEB&RefOrgId="
<< MAXIM_CLIENT_ID << "&access-token=" << MAXIM_SERVER_TOKEN
<< "&startLatitude=" << from.lat << "&startLongitude=" << from.lon
<< "&endLatitude=" << to.lat << "&endLongitude=" << to.lon;
return RunSimpleHttpRequest(url.str(), result);
}
/// Requests list of available products from Maxim.
void Api::GetAvailableProducts(ms::LatLon const & from, ms::LatLon const & to,
ProductsCallback const & successFn,
ErrorProviderCallback const & errorFn)
{
ASSERT(successFn, ());
ASSERT(errorFn, ());
// TODO(a): Add ErrorCode::FarDistance and provide this error code.
if (!IsDistanceSupported(from, to))
{
errorFn(ErrorCode::NoProducts);
return;
}
auto const baseUrl = m_baseUrl;
GetPlatform().RunTask(Platform::Thread::Network, [from, to, baseUrl, successFn, errorFn]()
{
std::string result;
if (!RawApi::GetTaxiInfo(from, to, result, baseUrl))
{
errorFn(ErrorCode::RemoteError);
return;
}
std::vector<Product> products;
try
{
MakeFromJson(result, products);
}
catch (my::Json::Exception const & e)
{
LOG(LERROR, (e.what(), result));
products.clear();
}
if (products.empty())
errorFn(ErrorCode::NoProducts);
else
successFn(products);
});
}
/// Returns link which allows you to launch the Maxim app.
RideRequestLinks Api::GetRideRequestLinks(std::string const & productId, ms::LatLon const & from,
ms::LatLon const & to) const
{
std::ostringstream orderLink;
std::ostringstream installLink;
orderLink << "order?refOrgId=" << MAXIM_CLIENT_ID << "&startLatitude=" << from.lat
<< "&startLongitude=" << from.lon << "&endLatitude=" << to.lat
<< "&endLongitude=" << to.lon;
#if defined(OMIM_OS_IPHONE)
installLink << "https://itunes.apple.com/app/apple-store/id579985456?pt=119057982"
<< "&ct=maps_me&mt=8";
#elif defined(OMIM_OS_ANDROID)
installLink << "https://play.google.com/store/apps/details?id=com.taxsee.taxsee"
<< "&referrer=utm_source%3Dmaps_me";
#endif
return {"maximzakaz://" + orderLink.str(), installLink.str()};
}
void MakeFromJson(std::string const & src, std::vector<taxi::Product> & products)
{
products.clear();
my::Json root(src.c_str());
if (!json_is_object(root.get()))
return;
bool success = false;
FromJSONObject(root.get(), "Success", success);
if (!success)
return;
auto const price = json_object_get(root.get(), "Price");
if (price == nullptr || json_is_null(price))
return;
double p = 0.0;
FromJSON(price, p);
if (p == 0.0)
return;
taxi::Product product;
FromJSONObject(root.get(), "PriceString", product.m_price);
FromJSONObject(root.get(), "CurrencyCode", product.m_currency);
double time = 0.0;
FromJSONObject(root.get(), "FeedTime", time);
product.m_time = strings::to_string(static_cast<int64_t>(time * kSecInMinute));
products.push_back(move(product));
}
} // namespace maxim
} // namespace taxi
| 26.653595 | 97 | 0.648357 | [
"geometry",
"vector"
] |
dc9c767fe08e91eddfc2342f4d07a081d0d04c2d | 3,580 | hpp | C++ | qi/type/dynamicobject.hpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | qi/type/dynamicobject.hpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | qi/type/dynamicobject.hpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | #pragma once
/*
** Copyright (C) 2013 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_TYPE_DYNAMICOBJECT_HPP_
#define _QI_TYPE_DYNAMICOBJECT_HPP_
#include <qi/anyobject.hpp>
#include <qi/property.hpp>
#include <qi/ptruid.hpp>
#include <boost/optional.hpp>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
namespace qi
{
class DynamicObjectPrivate;
/** A Dynamic object is an object that handles all signal/method operation
* itself.
*
* Signal handling:
* The default implementation is creating a SignalBase for each MetaSignal in
* the MetaObject, and bounces metaPost(), connect() and disconnect() to it.
*
* Method handling:
* The default implementation holds a method list that the user must populate
* with setMethod()
*/
class QI_API DynamicObject {
public:
DynamicObject();
virtual ~DynamicObject();
/// You *must* call DynamicObject::setMetaObject() if you overload this method.
virtual void setMetaObject(const MetaObject& mo);
MetaObject &metaObject();
void setMethod(unsigned int id, AnyFunction callable, MetaCallType threadingModel = MetaCallType_Auto);
void setSignal(unsigned int id, SignalBase* signal);
void setProperty(unsigned int id, PropertyBase* property);
const AnyFunction& method(unsigned int id) const;
SignalBase* signal(unsigned int id) const;
PropertyBase* property(unsigned int) const;
boost::optional<PtrUid> ptrUid() const;
void setPtrUid(boost::optional<PtrUid> newUid);
virtual qi::Future<AnyReference> metaCall(AnyObject context, unsigned int method, const GenericFunctionParameters& params, MetaCallType callType = MetaCallType_Auto, Signature returnSignature=Signature());
virtual void metaPost(AnyObject context, unsigned int event, const GenericFunctionParameters& params);
/// Calls given functor when event is fired. Takes ownership of functor.
virtual qi::Future<SignalLink> metaConnect(unsigned int event, const SignalSubscriber& subscriber);
/// Disconnect an event link. Returns if disconnection was successful.
virtual qi::Future<void> metaDisconnect(SignalLink linkId);
virtual qi::Future<AnyValue> metaProperty(AnyObject context, unsigned int id);
virtual qi::Future<void> metaSetProperty(AnyObject context, unsigned int id, AnyValue val);
void setThreadingModel(ObjectThreadingModel model);
ObjectThreadingModel threadingModel() const;
// internal use, call once to update with Manageable methods and signals
void setManageable(Manageable* m);
// C4251
boost::shared_ptr<DynamicObjectPrivate> _p;
};
/// Make an AnyObject of DynamicObject kind from a DynamicObject
QI_API AnyObject makeDynamicAnyObject(DynamicObject *obj,
bool destroyObject = true,
const boost::optional<PtrUid>& ptrUid = {},
boost::function<void (GenericObject*)> onDelete = boost::function<void (GenericObject*)>());
QI_API AnyObject makeDynamicSharedAnyObjectImpl(DynamicObject* obj, boost::shared_ptr<Empty> other);
/** Make an AnyObject that shares its ref counter with \p other
* Note that \p obj will not be destroyed when the shared counter reaches 0.
*/
template<typename T>
inline AnyObject makeDynamicSharedAnyObject(DynamicObject *obj, boost::shared_ptr<T> other)
{
return makeDynamicSharedAnyObjectImpl(obj, boost::shared_ptr<Empty>(other, 0));
}
QI_API ObjectTypeInterface* getDynamicTypeInterface();
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#endif // _QITYPE_DYNAMICOBJECT_HPP_
| 35.098039 | 209 | 0.748045 | [
"object",
"model"
] |
dc9d1f52dbf99e99285ad180b96787f46eb0bbe4 | 33,371 | cc | C++ | PYTHIA8/pythia8243/src/LHEF3.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | PYTHIA8/pythia8243/src/LHEF3.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | PYTHIA8/pythia8243/src/LHEF3.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // LHEF3.cc is a part of the PYTHIA event generator.
// Copyright (C) 2019 Torbjorn Sjostrand.
// PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
// Please respect the MCnet Guidelines, see GUIDELINES for details.
// This file is written by Stefan Prestel.
// It contains the main class for LHEF 3.0 functionalities.
// Function definitions.
#include "Pythia8/LHEF3.h"
namespace Pythia8 {
//==========================================================================
// The XMLTag struct is used to represent all information within an XML tag.
// It contains the attributes as a map, any sub-tags as a vector of pointers
// to other XMLTag objects, and any other information as a single string.
//--------------------------------------------------------------------------
// Constants.
const XMLTag::pos_t XMLTag::end = string::npos;
//==========================================================================
// The LHAweights struct.
//--------------------------------------------------------------------------
// Construct from XML tag.
LHAweights::LHAweights(const XMLTag & tag) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
string v = it->second.c_str();
attributes[it->first] = v;
}
contents = tag.contents;
istringstream iss(tag.contents);
double w;
while ( iss >> w ) weights.push_back(w);
}
//--------------------------------------------------------------------------
// Print out.
void LHAweights::list(ostream & file) const {
file << "<weights";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << ">";
for ( int j = 0, M = weights.size(); j < M; ++j ) file << " " << weights[j];
file << "</weights>" << endl;
}
//==========================================================================
// The LHAscales struct: Collect different scales relevant for an event.
//--------------------------------------------------------------------------
// Construct from an XML-tag.
LHAscales::LHAscales(const XMLTag & tag, double defscale)
: muf(defscale), mur(defscale), mups(defscale), SCALUP(defscale) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
double v = atof(it->second.c_str());
if ( it->first == "muf" ) muf = v;
else if ( it->first == "mur" ) mur = v;
else if ( it->first == "mups" ) mups = v;
else attributes.insert(make_pair(it->first, v));
}
contents = tag.contents;
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAscales::list(ostream & file) const {
file << "<scales";
file << " muf=\"" << muf << "\"";
file << " mur=\"" << mur << "\"";
file << " mups=\"" << mups << "\"";
for ( map<string,double>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << ">" << contents;
file << "</scales>" << endl;
}
//==========================================================================
// The LHAgenerator struct: Collect generator information for an event file.
//--------------------------------------------------------------------------
// Construct from an XML-tag
LHAgenerator::LHAgenerator(const XMLTag & tag, string defname)
: name(defname), version(defname), contents(defname) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
if ( it->first == "name" ) name = it->second;
else if ( it->first == "version" ) version = it->second;
else attributes.insert(make_pair(it->first, it->second));
}
contents = tag.contents;
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAgenerator::list(ostream & file) const {
file << "<generator";
if ( name != "" ) file << " name=\"" << name << "\"";
if ( version != "" ) file << " version=\"" << version << "\"";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >";
file << contents;
file << "</generator>" << endl;
}
//==========================================================================
// The LHAwgt struct: Collect the wgt information.
//--------------------------------------------------------------------------
// Construct from an XML-tag
LHAwgt::LHAwgt(const XMLTag & tag, double defwgt)
: id(""), contents(defwgt) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
if ( it->first == "id" ) id = it->second;
else attributes.insert(make_pair(it->first, it->second));
}
contents = atof(tag.contents.c_str());
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAwgt::list(ostream & file) const {
file << "<wgt";
if ( id != "" ) file << " id=\"" << id << "\"";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >";
file << contents;
file << "</wgt>" << endl;
}
//==========================================================================
// The LHAweight struct: Collect the weight information.
//--------------------------------------------------------------------------
// Construct from an XML-tag.
LHAweight::LHAweight(const XMLTag & tag, string defname)
: id(defname), contents(defname) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
if ( it->first == "id" ) id = it->second;
else attributes.insert(make_pair(it->first, it->second));
}
contents = tag.contents;
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAweight::list(ostream & file) const {
file << "<weight";
if ( id != "" ) file << " id=\"" << id << "\"";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >";
file << contents;
file << "</weight>" << endl;
}
//==========================================================================
// The LHAweightgroup struct: The LHAweightgroup assigns a group-name to a set
// of LHAweight objects.
//--------------------------------------------------------------------------
// Construct a group of LHAweight objects from an XML tag and
// insert them in the given vector.
LHAweightgroup::LHAweightgroup(const XMLTag & tag) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
if ( it->first == "name" ) name = it->second;
else attributes.insert(make_pair(it->first,it->second));
}
if ( name=="" ) {
string key("type");
if( attributes.find(key) != attributes.end() ) {
name = attributes[key];
}
}
contents = tag.contents;
// Now add the weight's step by step.
string s;
vector<XMLTag*> tags = XMLTag::findXMLTags(tag.contents, &s);
for ( int i = 0, N = tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tags[i];
LHAweight wt(tagnow);
weights.insert(make_pair(wt.id, wt));
weightsKeys.push_back(wt.id);
}
for ( int i = 0, N = tag.tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tag.tags[i];
const LHAweight & wt(tagnow);
weights.insert(make_pair(wt.id, wt));
weightsKeys.push_back(wt.id);
}
for ( int i = 0, N = tags.size(); i < N; ++i ) if (tags[i]) delete tags[i];
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAweightgroup::list(ostream & file) const {
file << "<weightgroup";
if ( name != "" ) file << " name=\"" << name << "\"";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >\n";
for ( map<string,LHAweight>::const_iterator it = weights.begin();
it != weights.end(); ++it ) it->second.list(file);
file << "</weightgroup>" << endl;
}
//==========================================================================
// The LHArwgt struct: Assigns a group-name to a set of LHAwgt objects.
//--------------------------------------------------------------------------
// Construct a group of LHAwgt objects from an XML tag and
// insert them in the given vector.
LHArwgt::LHArwgt(const XMLTag & tag) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
string v = it->second.c_str();
attributes[it->first] = v;
}
contents = tag.contents;
// Now add the wgt's step by step.
string s;
vector<XMLTag*> tags = XMLTag::findXMLTags(tag.contents, &s);
for ( int i = 0, N = tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tags[i];
LHAwgt wt(tagnow);
wgts.insert(make_pair(wt.id, wt));
wgtsKeys.push_back(wt.id);
}
for ( int i = 0, N = tag.tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tag.tags[i];
LHAwgt wt(tagnow);
wgts.insert(make_pair(wt.id, wt));
wgtsKeys.push_back(wt.id);
}
for ( int i = 0, N = tags.size(); i < N; ++i ) if (tags[i]) delete tags[i];
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHArwgt::list(ostream & file) const {
file << "<rwgt";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >\n";
for ( map<string,LHAwgt>::const_iterator it = wgts.begin();
it != wgts.end(); ++it ) it->second.list(file);
file << "</rwgt>" << endl;
}
//==========================================================================
// The LHAinitrwgt assigns a group-name to a set of LHAweightgroup objects.
//--------------------------------------------------------------------------
// Construct a group of LHAweightgroup objects from an XML tag and
// insert them in the given vector.
LHAinitrwgt::LHAinitrwgt(const XMLTag & tag) {
for ( map<string,string>::const_iterator it = tag.attr.begin();
it != tag.attr.end(); ++it ) {
string v = it->second.c_str();
attributes[it->first] = v;
}
contents = tag.contents;
// Now add the wgt's step by step.
string s;
vector<XMLTag*> tags = XMLTag::findXMLTags(tag.contents, &s);
for ( int i = 0, N = tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tags[i];
if ( tagnow.name == "weightgroup" ) {
LHAweightgroup wgroup(tagnow);
string wgname = wgroup.name;
// if still no name, use integer as a key
if (wgname=="") {
stringstream iss;
iss << i;
wgname=iss.str();
}
weightgroups.insert(make_pair(wgname, wgroup));
weightgroupsKeys.push_back(wgname);
string ss;
vector<XMLTag*> tags2 = XMLTag::findXMLTags(tagnow.contents, &ss);
for ( int k = 0, M = tags2.size(); k < M; ++k ) {
const XMLTag & tagnow2 = *tags2[k];
if ( tagnow2.name == "weight" ) {
LHAweight wt(tagnow2);
string wtname = wt.id;
weights.insert(make_pair(wtname, wt));
weightsKeys.push_back(wtname);
}
}
for ( int j = 0, M = tags2.size(); j < M; ++j )
if (tags2[j]) delete tags2[j];
} else if ( tagnow.name == "weight" ) {
LHAweight wt(tagnow);
string wtname = wt.id;
weights.insert(make_pair(wtname, wt));
weightsKeys.push_back(wtname);
}
}
// Now add the wgt's step by step.
for ( int i = 0, N = tag.tags.size(); i < N; ++i ) {
const XMLTag & tagnow = *tag.tags[i];
if ( tagnow.name == "weightgroup" ) {
LHAweightgroup wgroup(tagnow);
string wgname = wgroup.name;
weightgroups.insert(make_pair(wgname, wgroup));
weightgroupsKeys.push_back(wgname);
string ss;
vector<XMLTag*> tags2 = XMLTag::findXMLTags(tagnow.contents, &ss);
for ( int k = 0, M = tags2.size(); k < M; ++k ) {
const XMLTag & tagnow2 = *tags2[k];
if ( tagnow2.name == "weight" ) {
LHAweight wt(tagnow2);
string wtname = wt.id;
weights.insert(make_pair(wtname, wt));
weightsKeys.push_back(wtname);
}
}
for ( int k = 0, M = tagnow.tags.size(); k < M; ++k ) {
const XMLTag & tagnow2 = *tagnow.tags[k];
if ( tagnow2.name == "weight" ) {
LHAweight wt(tagnow2);
string wtname = wt.id;
weights.insert(make_pair(wtname, wt));
weightsKeys.push_back(wtname);
}
}
for ( int j = 0, M = tags2.size(); j < M; ++j )
if (tags2[j]) delete tags2[j];
} else if ( tagnow.name == "weight" ) {
LHAweight wt(tagnow);
string wtname = wt.id;
weights.insert(make_pair(wtname, wt));
weightsKeys.push_back(wtname);
}
}
for ( int i = 0, N = tags.size(); i < N; ++i ) if (tags[i]) delete tags[i];
}
//--------------------------------------------------------------------------
// Print out the corresponding XML-tag.
void LHAinitrwgt::list(ostream & file) const {
file << "<initrwgt";
for ( map<string,string>::const_iterator it = attributes.begin();
it != attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << " >\n";
for ( map<string,LHAweightgroup>::const_iterator it = weightgroups.begin();
it != weightgroups.end(); ++it ) it->second.list(file);
for ( map<string,LHAweight>::const_iterator it = weights.begin();
it != weights.end(); ++it ) it->second.list(file);
file << "</initrwgt>" << endl;
}
//==========================================================================
// The HEPRUP class is a simple container for the Les Houches file init block.
void HEPRUP::clear() {
IDBMUP = make_pair(0,0);
EBMUP = make_pair(0,0);
PDFGUP = make_pair(0,0);
PDFSUP = make_pair(0,0);
IDWTUP = -1;
NPRUP = 0;
XSECUP.resize(0);
XERRUP.resize(0);
XMAXUP.resize(0);
LPRUP.resize(0);
initrwgt.clear();
generators.resize(0);
weightgroups.clear();
weights.clear();
}
//==========================================================================
// The HEPEUP class is a simple container corresponding to the Les Houches
// accord (<A HREF="http://arxiv.org/abs/hep-ph/0109068">hep-ph/0109068</A>)
// common block with the same name. The members are named in the same
// way as in the common block. However, fortran arrays are represented
// by vectors, except for the arrays of length two which are
// represented by pair objects.
//--------------------------------------------------------------------------
// Copy information from the given HEPEUP.
HEPEUP & HEPEUP::setEvent(const HEPEUP & x) {
NUP = x.NUP;
IDPRUP = x.IDPRUP;
XWGTUP = x.XWGTUP;
XPDWUP = x.XPDWUP;
SCALUP = x.SCALUP;
AQEDUP = x.AQEDUP;
AQCDUP = x.AQCDUP;
IDUP = x.IDUP;
ISTUP = x.ISTUP;
MOTHUP = x.MOTHUP;
ICOLUP = x.ICOLUP;
PUP = x.PUP;
VTIMUP = x.VTIMUP;
SPINUP = x.SPINUP;
heprup = x.heprup;
scalesSave = x.scalesSave;
weightsSave = x.weightsSave;
weights_detailed = x.weights_detailed;
weights_compressed = x.weights_compressed;
rwgtSave = x.rwgtSave;
attributes = x.attributes;
return *this;
}
//--------------------------------------------------------------------------
// Reset the HEPEUP object.
void HEPEUP::reset() {
NUP = 0;
weights_detailed.clear();
weights_compressed.clear();
weightsSave.clear();
rwgtSave.clear();
scalesSave.clear();
attributes.clear();
}
//--------------------------------------------------------------------------
// Assuming the NUP variable, corresponding to the number of
// particles in the current event, is correctly set, resize the
// relevant vectors accordingly.
void HEPEUP::resize() {
IDUP.resize(NUP);
ISTUP.resize(NUP);
MOTHUP.resize(NUP);
ICOLUP.resize(NUP);
PUP.resize(NUP, vector<double>(5));
VTIMUP.resize(NUP);
SPINUP.resize(NUP);
}
//==========================================================================
// The Reader class is initialized with a stream from which to read a
// version 1/2 Les Houches Accord event file. In the constructor of
// the Reader object the optional header information is read and then
// the mandatory init is read. After this the whole header block
// including the enclosing lines with tags are available in the public
// headerBlock member variable. Also the information from the init
// block is available in the heprup member variable and any additional
// comment lines are available in initComments. After each successful
// call to the readEvent() function the standard Les Houches Accord
// information about the event is available in the hepeup member
// variable and any additional comments in the eventComments
// variable. A typical reading sequence would look as follows:
//--------------------------------------------------------------------------
// Used internally in the constructors to read header and init blocks.
bool Reader::init() {
bool readingHeader = false;
bool readingInit = false;
// Make sure we are reading a LHEF file:
getLine();
if ( currentLine.find("<LesHouchesEvents" ) == string::npos )
return false;
version = 0;
if ( currentLine.find("version=\"1" ) != string::npos )
version = 1;
else if ( currentLine.find("version=\"2" ) != string::npos )
version = 2;
else if ( currentLine.find("version=\"3" ) != string::npos )
version = 3;
else
return false;
// Clear all members.
outsideBlock="";
headerBlock="";
headerComments="";
heprup.clear();
initComments="";
hepeup.clear();
eventComments="";
// Loop over all lines until we hit the </init> tag.
while ( getLine() && currentLine.find("</init>") == string::npos ) {
if ( currentLine.find("<header") != string::npos
&& currentLine.find("#") == string::npos) {
// We have hit the header block, so we should dump this and
// all following lines to headerBlock until we hit the end of
// it.
readingHeader = true;
headerBlock = currentLine + "\n";
}
else if ( ( currentLine.find("<init>") != string::npos
|| currentLine.find("<init ") != string::npos )
&& currentLine.find("#") == string::npos) {
// We have hit the init block, so we should expect to find the
// standard information in the following.
readingInit = true;
// The first line tells us how many lines to read next.
getLine();
istringstream iss(currentLine);
if ( !( iss >> heprup.IDBMUP.first >> heprup.IDBMUP.second
>> heprup.EBMUP.first >> heprup.EBMUP.second
>> heprup.PDFGUP.first >> heprup.PDFGUP.second
>> heprup.PDFSUP.first >> heprup.PDFSUP.second
>> heprup.IDWTUP >> heprup.NPRUP ) ) {
heprup.NPRUP = -42;
return false;
}
heprup.resize();
for ( int i = 0; i < heprup.NPRUP; ++i ) {
getLine();
istringstream isss(currentLine);
if ( !( isss >> heprup.XSECUP[i] >> heprup.XERRUP[i]
>> heprup.XMAXUP[i] >> heprup.LPRUP[i] ) ) {
heprup.NPRUP = -42;
return false;
}
}
}
else if ( currentLine.find("</header>") != string::npos
&& currentLine.find("#") == string::npos) {
// The end of the header block. Dump this line as well to the
// headerBlock and we're done.
readingHeader = false;
headerBlock += currentLine + "\n";
}
else if ( readingHeader ) {
// We are in the process of reading the header block. Dump the
// line to headerBlock.
headerBlock += currentLine + "\n";
headerComments += currentLine + "\n";
}
else if ( readingInit ) {
// Here we found a comment line. Dump it to initComments.
initComments += currentLine + "\n";
}
else {
// We found some other stuff outside the standard tags.
outsideBlock += currentLine + "\n";
}
}
if ( file == NULL ) heprup.NPRUP = -42;
// Scan the header block for XML tags
string leftovers;
vector<XMLTag*> tags1 = XMLTag::findXMLTags(headerComments, &leftovers);
if ( leftovers.find_first_not_of(" \t\n") == string::npos )
leftovers="";
for ( int i = 0, N = tags1.size(); i < N; ++i ) {
const XMLTag & tag = *tags1[i];
if ( tag.name == "initrwgt" ) {
LHAinitrwgt irwgt(tag);
heprup.initrwgt = irwgt;
for ( int j = 0, M = tag.tags.size(); j < M; ++j ) {
XMLTag & ctag = *tag.tags[j];
if ( ctag.name == "weightgroup" ) {
LHAweightgroup wgroup(ctag);
string wgname = wgroup.name;
heprup.weightgroups.insert(make_pair(wgname, wgroup));
string ss;
vector<XMLTag*> tags2 = XMLTag::findXMLTags(ctag.contents, &ss);
for ( int k = 0, O = tags2.size(); k < O; ++k ) {
const XMLTag & tagnow2 = *tags2[k];
if ( tagnow2.name == "weight" ) {
LHAweight wt(tagnow2);
string wtname = wt.id;
heprup.weights.insert(make_pair(wtname, wt));
}
}
for ( int k = 0, O = ctag.tags.size(); k < O; ++k ) {
const XMLTag & tagnow2 = *ctag.tags[k];
if ( tagnow2.name == "weight" ) {
LHAweight wt(tagnow2);
string wtname = wt.id;
heprup.weights.insert(make_pair(wtname, wt));
}
}
} else if ( ctag.name == "weight" ) {
string tname = ctag.attr["id"];
heprup.weights.insert(make_pair(tname, LHAweight(ctag)));
}
}
}
}
heprup.generators.clear();
// Scan the init block for XML tags
leftovers="";
vector<XMLTag*> tags2 = XMLTag::findXMLTags(initComments, &leftovers);
if ( leftovers.find_first_not_of(" \t\n") == string::npos )
leftovers="";
for ( int i = 0, N = tags2.size(); i < N; ++i ) {
const XMLTag & tag = *tags2[i];
if ( tag.name == "generator" ) {
heprup.generators.push_back(LHAgenerator(tag));
}
}
for ( int i = 0, N = tags1.size(); i < N; ++i )
if (tags1[i]) delete tags1[i];
for ( int i = 0, N = tags2.size(); i < N; ++i )
if (tags2[i]) delete tags2[i];
// Done
return true;
}
//--------------------------------------------------------------------------
// Read an event from the file and store it in the hepeup
// object. Optional comment lines are stored in the eventComments
// member variable. return true if the read was successful.
bool Reader::readEvent(HEPEUP * peup) {
HEPEUP & eup = (peup? *peup: hepeup);
eup.clear();
eup.heprup = &heprup;
weights_detailed_vec.clear();
// Check if the initialization was successful. Otherwise we will
// not read any events.
if ( heprup.NPRUP < 0 ) return false;
eventComments = "";
outsideBlock = "";
eup.NUP = 0;
// Keep reading lines until we hit the next event or the end of
// the event block. Save any inbetween lines. Exit if we didn't
// find an event.
while ( getLine() && currentLine.find("<event") == string::npos )
outsideBlock += currentLine + "\n";
// Get event attributes.
if (currentLine != "") {
string eventLine(currentLine);
eventLine += "</event>";
vector<XMLTag*> evtags = XMLTag::findXMLTags(eventLine);
XMLTag & evtag = *evtags[0];
for ( map<string,string>::const_iterator it = evtag.attr.begin();
it != evtag.attr.end(); ++it ) {
eup.attributes.insert(make_pair(it->first,it->second));
}
for ( int i = 0, N = evtags.size(); i < N; ++i )
if (evtags[i]) delete evtags[i];
}
if ( !getLine() ) return false;
// We found an event. The first line determines how many
// subsequent particle lines we have.
istringstream iss(currentLine);
if ( !( iss >> eup.NUP >> eup.IDPRUP >> eup.XWGTUP
>> eup.SCALUP >> eup.AQEDUP >> eup.AQCDUP ) )
return false;
eup.resize();
// Read all particle lines.
for ( int i = 0; i < eup.NUP; ++i ) {
if ( !getLine() ) return false;
istringstream isss(currentLine);
if ( !( isss >> eup.IDUP[i] >> eup.ISTUP[i]
>> eup.MOTHUP[i].first >> eup.MOTHUP[i].second
>> eup.ICOLUP[i].first >> eup.ICOLUP[i].second
>> eup.PUP[i][0] >> eup.PUP[i][1] >> eup.PUP[i][2]
>> eup.PUP[i][3] >> eup.PUP[i][4]
>> eup.VTIMUP[i] >> eup.SPINUP[i] ) )
return false;
}
// Now read any additional comments.
while ( getLine() && currentLine.find("</event>") == string::npos )
eventComments += currentLine + "\n";
if ( file == NULL ) return false;
eup.scalesSave = LHAscales(eup.SCALUP);
// Scan the init block for XML tags
string leftovers;
vector<XMLTag*> tags = XMLTag::findXMLTags(eventComments, &leftovers);
if ( leftovers.find_first_not_of(" \t\n") == string::npos )
leftovers="";
eventComments = "";
istringstream f(leftovers);
string l;
while (getline(f, l)) {
size_t p = l.find_first_not_of(" \t");
l.erase(0, p);
p = l.find_last_not_of(" \t");
if (string::npos != p) l.erase(p+1);
if (l.find_last_not_of("\n") != string::npos)
eventComments += l + "\n";
}
for ( int i = 0, N = tags.size(); i < N; ++i ) {
XMLTag & tag = *tags[i];
if ( tag.name == "weights" ) {
LHAweights wts(tag);
eup.weightsSave = wts;
for ( int k = 0, M = int(wts.weights.size()); k < M; ++k ) {
eup.weights_compressed.push_back(wts.weights[k]);
}
}
else if ( tag.name == "scales" ) {
eup.scalesSave = LHAscales(tag, eup.SCALUP);
}
else if ( tag.name == "rwgt" ) {
LHArwgt rwgt0(tag);
eup.rwgtSave = rwgt0;
string s;
vector<XMLTag*> tags2 = XMLTag::findXMLTags(rwgt0.contents, &s);
for ( int k = 0, M = tags2.size(); k < M; ++k ) {
const XMLTag & tagnow = *tags2[k];
if ( tagnow.name == "wgt" ) {
LHAwgt wt(tagnow);
eup.weights_detailed.insert(make_pair(wt.id, wt.contents));
weights_detailed_vec.push_back(wt.contents);
}
}
for ( int k = 0, M = tag.tags.size(); k < M; ++k ) {
const XMLTag & tagnow = *tag.tags[k];
if ( tagnow.name == "wgt" ) {
LHAwgt wt(tagnow);
eup.weights_detailed.insert(make_pair(wt.id, wt.contents));
weights_detailed_vec.push_back(wt.contents);
}
}
}
}
for ( int i = 0, N = tags.size(); i < N; ++i ) if (tags[i]) delete tags[i];
return true;
}
//==========================================================================
// The Writer class is initialized with a stream to which to write a
// version 3.0 Les Houches Accord event file.
//--------------------------------------------------------------------------
// Write out an optional header block followed by the standard init
// block information together with any comment lines.
void Writer::init() {
// Write out the standard XML tag for the event file.
if ( version == 1 )
file << "<LesHouchesEvents version=\"1.0\">" << endl;
else
file << "<LesHouchesEvents version=\"3.0\">" << endl;
file << setprecision(8);
// Print headercomments and header init information.
file << "<header>" << endl;
file << hashline(headerStream.str(),true) << std::flush;
if ( version != 1 ) heprup.initrwgt.list(file);
file << "</header>" << endl;
file << "<init>"<< endl
<< " " << setw(8) << heprup.IDBMUP.first
<< " " << setw(8) << heprup.IDBMUP.second
<< " " << setw(14) << heprup.EBMUP.first
<< " " << setw(14) << heprup.EBMUP.second
<< " " << setw(4) << heprup.PDFGUP.first
<< " " << setw(4) << heprup.PDFGUP.second
<< " " << setw(4) << heprup.PDFSUP.first
<< " " << setw(4) << heprup.PDFSUP.second
<< " " << setw(4) << heprup.IDWTUP
<< " " << setw(4) << heprup.NPRUP << endl;
heprup.resize();
for ( int i = 0; i < heprup.NPRUP; ++i )
file << " " << setw(14) << heprup.XSECUP[i]
<< " " << setw(14) << heprup.XERRUP[i]
<< " " << setw(14) << heprup.XMAXUP[i]
<< " " << setw(6) << heprup.LPRUP[i] << endl;
if ( version == 1 ) {
file << hashline(initStream.str(),true) << std::flush
<< "</init>" << endl;
initStream.str("");
return;
}
for ( int i = 0, N = heprup.generators.size(); i < N; ++i ) {
heprup.generators[i].list(file);
}
file << hashline(initStream.str(),true) << std::flush
<< "</init>" << endl;
initStream.str("");
}
//--------------------------------------------------------------------------
// Write out the event stored in hepeup, followed by optional
// comment lines.
bool Writer::writeEvent(HEPEUP * peup, int pDigits) {
HEPEUP & eup = (peup? *peup: hepeup);
file << "<event";
for ( map<string,string>::const_iterator it = eup.attributes.begin();
it != eup.attributes.end(); ++it )
file << " " << it->first << "=\"" << it->second << "\"";
file << ">" << std::flush << endl;
file << " " << setw(4) << eup.NUP
<< " " << setw(6) << eup.IDPRUP
<< " " << setw(14) << eup.XWGTUP
<< " " << setw(14) << eup.SCALUP
<< " " << setw(14) << eup.AQEDUP
<< " " << setw(14) << eup.AQCDUP << endl;
eup.resize();
for ( int i = 0; i < eup.NUP; ++i )
file << " " << setw(8) << eup.IDUP[i]
<< " " << setw(2) << eup.ISTUP[i]
<< " " << setw(4) << eup.MOTHUP[i].first
<< " " << setw(4) << eup.MOTHUP[i].second
<< " " << setw(4) << eup.ICOLUP[i].first
<< " " << setw(4) << eup.ICOLUP[i].second
<< " " << setw(pDigits) << eup.PUP[i][0]
<< " " << setw(pDigits) << eup.PUP[i][1]
<< " " << setw(pDigits) << eup.PUP[i][2]
<< " " << setw(pDigits) << eup.PUP[i][3]
<< " " << setw(pDigits) << eup.PUP[i][4]
<< " " << setw(1) << eup.VTIMUP[i]
<< " " << setw(1) << eup.SPINUP[i] << endl;
// Write event comments.
file << hashline(eventStream.str()) << std::flush;
eventStream.str("");
if ( version != 1 ) {
eup.rwgtSave.list(file);
eup.weightsSave.list(file);
eup.scalesSave.list(file);
}
file << "</event>" << endl;
if ( !file ) return false;
return true;
}
//--------------------------------------------------------------------------
// Write out an event as a string.
string Writer::getEventString(HEPEUP * peup) {
HEPEUP & eup = (peup? *peup: hepeup);
stringstream helper;
helper << "<event";
for ( map<string,string>::const_iterator it = eup.attributes.begin();
it != eup.attributes.end(); ++it )
helper << " " << it->first << "=\"" << it->second << "\"";
helper << ">" << std::flush << endl;
helper << " " << setw(4) << eup.NUP
<< " " << setw(6) << eup.IDPRUP
<< " " << setw(14) << eup.XWGTUP
<< " " << setw(14) << eup.SCALUP
<< " " << setw(14) << eup.AQEDUP
<< " " << setw(14) << eup.AQCDUP << endl;
eup.resize();
for ( int i = 0; i < eup.NUP; ++i ) {
helper << " " << setw(8) << eup.IDUP[i]
<< " " << setw(2) << eup.ISTUP[i]
<< " " << setw(4) << eup.MOTHUP[i].first
<< " " << setw(4) << eup.MOTHUP[i].second
<< " " << setw(6) << eup.ICOLUP[i].first
<< " " << setw(6) << eup.ICOLUP[i].second
<< fixed
<< setprecision(15)
<< " " << setw(22) << eup.PUP[i][0]
<< " " << setw(22) << eup.PUP[i][1]
<< " " << setw(22) << eup.PUP[i][2]
<< " " << setw(22) << eup.PUP[i][3]
<< " " << setw(22) << eup.PUP[i][4]
<< " " << setw(6) << eup.VTIMUP[i]
<< " " << setw(6) << eup.SPINUP[i] << endl;
}
// Write event comments.
helper << hashline(eventStream.str()) << std::flush;
eventStream.str("");
if ( version != 1 ) {
eup.rwgtSave.list(helper);
eup.weightsSave.list(helper);
eup.scalesSave.list(helper);
}
helper << "</event>" << endl;
string helperString = helper.str();
//event = helperString.c_str();
return helperString;
}
//--------------------------------------------------------------------------
// Make sure that each line in the string s starts with a
// #-character and that the string ends with a new-line.
string Writer::hashline(string s, bool comment) {
string ret;
istringstream is(s);
string ss;
while ( getline(is, ss) ) {
if ( comment )
ss = "# " + ss;
ret += ss + '\n';
}
return ret;
}
//==========================================================================
}
| 32.430515 | 78 | 0.517575 | [
"object",
"vector"
] |
dca31e3b3aa8a002cd480d81594f3421c6b06ceb | 2,123 | cpp | C++ | Src/Motor_Driver.cpp | Nuko-XCB/Sweep-Robot-Team36 | fb219b066d94e568365bbd72aad0cc49f5068da3 | [
"MIT"
] | null | null | null | Src/Motor_Driver.cpp | Nuko-XCB/Sweep-Robot-Team36 | fb219b066d94e568365bbd72aad0cc49f5068da3 | [
"MIT"
] | null | null | null | Src/Motor_Driver.cpp | Nuko-XCB/Sweep-Robot-Team36 | fb219b066d94e568365bbd72aad0cc49f5068da3 | [
"MIT"
] | null | null | null | #include <thread>
#include <opencv2/highgui/highgui_c.h>
#include "Display.h"
#include <chrono>
#include "Motor_Driver.h"
#include <arpa/inet.h>
#include <string>
using namespace std;
int Motor_Driver(float &positionX, float &positionY, float &RealAngle,float &targetAngle,vector<vector<int>> &list_target)
{
int srv_sd, cli_sd, ret;
if ((srv_sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(EXIT_FAILURE);
}
sockaddr_in svr_addr, cli_addr;
cli_addr.sin_family = AF_INET;
cli_addr.sin_port = htons(7403);
cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
svr_addr.sin_family = AF_INET;
svr_addr.sin_port = htons(7403);
svr_addr.sin_addr.s_addr = inet_addr("192.168.0.105");//my pc
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
int sock_fd2=socket(AF_INET, SOCK_DGRAM, 0);
std::cout << "start" << std::endl;
std::string send_data="";
char pc_buff[512];
while (1)
{
//MTX.lock();
//heading=RealAngle;
//MTX.unlock();
cv::waitKey(50);
while (1) //until turn to target
{
send_data="Heading:"+to_string(RealAngle)+" TargetAngle:"+to_string(targetAngle)+" PositionX:"+to_string(positi$
//cout<<send_data<<endl;
send_data.copy(pc_buff,send_data.size(),0);
sendto(sock_fd2, pc_buff,512, 0, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
cv::waitKey(50);
float angleDist = RealAngle - targetAngle;
if (angleDist > 180) angleDist = angleDist-360;
if (angleDist < -180) angleDist = 360 + angleDist;
cout<<" Motor_Driver-- heading "<<RealAngle<<" Target "<<targetAngle<<" DIST "<<angleDist<<endl;
if (angleDist > 4 || angleDist < -4)
{
if (angleDist < 0)
{
char SendBuf[15] ="right";
sendto(sock_fd, SendBuf,5, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr));
}
else
{
char SendBuf[15] = "left ";
sendto(sock_fd, SendBuf,5, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr));
}
}
else
break;
}
char SendBuf[15] = "front";
sendto(sock_fd, SendBuf,5, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr));
}
}
| 27.571429 | 122 | 0.646726 | [
"vector"
] |
dca6f0867a9000072f38b708a3e964484b403caa | 10,016 | cxx | C++ | PHOS/PHOSbase/AliPHOSPulseGenerator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | PHOS/PHOSbase/AliPHOSPulseGenerator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | PHOS/PHOSbase/AliPHOSPulseGenerator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
/* $Id$ */
// The class which simulates the pulse shape from the PHOS FEE shaper,
// make sampled amplitudes, digitize them.
// Use case:
// AliPHOSPulseGenerator *pulse = new AliPHOSPulseGenerator(energy,time);
// Int_t *adcHG = new Int_t[pulse->GetRawFormatTimeBins()];
// Int_t *adcLG= new Int_t[pulse->GetRawFormatTimeBins()];
// pulse->AddNoise(1.);
// pulse->MakeSamples();
// pulse->GetSamples(adcHG, adcHG) ;
// pulse->Print();
// pulse->Draw();
//
// Author: Yuri Kharlov, after Yves Schutz and Per Thomas Hille
// --- ROOT system ---
#include <TCanvas.h>
#include <TF1.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TMath.h>
#include <TRandom.h>
// --- AliRoot header files ---
#include "AliLog.h"
#include "AliPHOSPulseGenerator.h"
// --- Standard library ---
#include <cmath>
#include <iostream>
using std::cout;
using std::endl;
ClassImp(AliPHOSPulseGenerator)
Int_t AliPHOSPulseGenerator::fgOrder = 2 ; // order of the Gamma function
Double_t AliPHOSPulseGenerator::fgTimePeak = 2.1E-6 ; // tau=2.1 micro seconds
Double_t AliPHOSPulseGenerator::fgTimeTrigger = 100E-9 ; // one tick 100 ns
//-----------------------------------------------------------------------------
AliPHOSPulseGenerator::AliPHOSPulseGenerator(Double_t a, Double_t t0)
: TObject(), fAmplitude(a), fTZero(t0), fHG2LGratio(16.), fDataHG(0), fDataLG(0), fDigitize(kTRUE)
{
// Contruct a pulsegenrator object and initializes all necessary parameters
// @param a digit amplitude in GeV
// @param t0 time delay in nanoseconds of signal relative the first sample.
// This value should be between 0 and Ts, where Ts is the sample interval
fDataHG = new Double_t[fkTimeBins];
fDataLG = new Double_t[fkTimeBins];
Reset();
}
//-----------------------------------------------------------------------------
AliPHOSPulseGenerator::~AliPHOSPulseGenerator()
{
// Destructor: delete arrays of samples
delete [] fDataHG;
fDataHG=0;
delete [] fDataLG;
fDataLG=0;
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::Reset()
{
// Reset all sample amplitudes to 0
for (Int_t i=0; i<fkTimeBins; i++) {
fDataHG[i] = 0.;
fDataLG[i] = 0.;
}
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::AddBaseline(Double_t baselineLevel)
{
// Adds a baseline offset to the signal
// @param baselineLevel The basline level to add
for (Int_t i=0; i<fkTimeBins; i++) {
fDataHG[i] += baselineLevel;
fDataLG[i] += baselineLevel;
}
// Digitize floating point amplitudes to integers
if (fDigitize) Digitize();
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::AddNoise(Double_t sigma)
{
// Adds Gaussian uncorrelated to the sample array
// @param sigma the noise amplitude in entities of ADC levels
for (Int_t i=0; i<fkTimeBins; i++) {
fDataHG[i] = gRandom->Gaus(0., sigma) ;
fDataLG[i] = gRandom->Gaus(0., sigma) ;
}
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::AddNoise(Double_t * /* sigma */, Double_t /* cutoff */)
{
//Adds correlated Gaussian noise with cutof frequency "cutoff"
// @param sigma noise amplitude in entities of ADC levels
// @param -30DB cutoff frequency of the noise in entities of sampling frequency
AliError("not implemented yet");
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::AddPretriggerSamples(Int_t nPresamples)
{
// Adds pretrigger samples to the sample arrays and replace them
// with concatinated and truncated arrays
Double_t *tmpDataHG = new Double_t[fkTimeBins];
Double_t *tmpDataLG = new Double_t[fkTimeBins];
Int_t i;
for (i=0; i<fkTimeBins; i++) {
tmpDataHG[i] = fDataHG[i];
tmpDataLG[i] = fDataLG[i];
}
for (i=0; i<fkTimeBins; i++) {
if (i<nPresamples) {
fDataHG[i] = 0.;
fDataLG[i] = 0.;
}
else {
fDataHG[i] = tmpDataHG[i-nPresamples];
fDataLG[i] = tmpDataLG[i-nPresamples];
}
}
delete [] tmpDataHG;
delete [] tmpDataLG;
}
//-----------------------------------------------------------------------------
void AliPHOSPulseGenerator::Digitize()
{
// Emulates ADC: rounds up to nearest integer value all amplitudes
for (Int_t i=0; i<fkTimeBins; i++) {
fDataHG[i] = (Int_t)(fDataHG[i]);
fDataLG[i] = (Int_t)(fDataLG[i]);
}
}
//-----------------------------------------------------------------------------
Double_t AliPHOSPulseGenerator::RawResponseFunction(Double_t *x, Double_t *par)
{
// Shape of the electronics raw reponse:
// It is a semi-gaussian, 2nd order Gamma function of the general form
// v(t) = A *(t/tp)**n * exp(-n * t/tp-n) with
// tp : peaking time fgTimePeak
// n : order of the function
Double_t signal ;
Double_t xx = x[0] - ( fgTimeTrigger + par[1] ) ;
if (xx < 0 || xx > GetRawFormatTimeMax())
signal = 0. ;
else {
signal = par[0] * TMath::Power(xx/fgTimePeak, fgOrder) * TMath::Exp(-fgOrder*(xx/fgTimePeak-1.)) ; //normalized to par[2] at maximum
}
return signal ;
}
//__________________________________________________________________
Bool_t AliPHOSPulseGenerator::MakeSamples()
{
// for a start time fTZero and an amplitude fAmplitude given by digit,
// calculates the raw sampled response AliPHOSPulseGenerator::RawResponseFunction
const Int_t kRawSignalOverflow = 0x3FF ; // decimal 1023
Bool_t lowGain = kFALSE ;
TF1 signalF("signal", RawResponseFunction, 0, GetRawFormatTimeMax(), 4);
for (Int_t iTime = 0; iTime < GetRawFormatTimeBins(); iTime++) {
signalF.SetParameter(0, fAmplitude) ;
signalF.SetParameter(1, fTZero) ;
Double_t time = iTime * GetRawFormatTimeMax() / GetRawFormatTimeBins() ;
Double_t signal = signalF.Eval(time) ;
fDataHG[iTime] += signal;
if ( static_cast<Int_t>(fDataHG[iTime]+0.5) > kRawSignalOverflow ){ // larger than 10 bits
fDataHG[iTime] = kRawSignalOverflow ;
lowGain = kTRUE ;
}
Double_t aLGamp = fAmplitude/fHG2LGratio ;
signalF.SetParameter(0, aLGamp) ;
signal = signalF.Eval(time) ;
fDataLG[iTime] += signal;
if ( static_cast<Int_t>(fDataLG[iTime]+0.5) > kRawSignalOverflow) // larger than 10 bits
fDataLG[iTime] = kRawSignalOverflow ;
}
// Digitize floating point amplitudes to integers
if (fDigitize) Digitize();
return lowGain ;
}
//__________________________________________________________________
void AliPHOSPulseGenerator::GetSamples(Int_t *adcHG, Int_t *adcLG) const
{
// Return integer sample arrays adcHG and adcLG
for (Int_t iTime = 0; iTime < GetRawFormatTimeBins(); iTime++) {
adcHG[iTime] = static_cast<Int_t>(fDataHG[iTime]) ;
adcLG[iTime] = static_cast<Int_t>(fDataLG[iTime]) ;
}
}
//__________________________________________________________________
void AliPHOSPulseGenerator::Print(Option_t*) const
{
// Prints sampled amplitudes to stdout
Int_t i;
cout << "High gain: ";
for (i=0; i<fkTimeBins; i++)
cout << (Int_t)fDataHG[i] << " ";
cout << endl;
cout << "Low gain: ";
for (i=0; i<fkTimeBins; i++)
cout << (Int_t)fDataLG[i] << " ";
cout << endl;
}
//__________________________________________________________________
void AliPHOSPulseGenerator::Draw(Option_t* opt)
{
// Draw graphs with high and low gain samples
// Option_t* opt="all": draw both HG and LG in one canvas
// "HG" : draw HG only
// "LG" : draw LG only
Double_t *time = new Double_t[fkTimeBins];
for (Int_t iTime = 0; iTime < GetRawFormatTimeBins(); iTime++) {
time[iTime] = iTime * GetRawFormatTimeMax() / GetRawFormatTimeBins() ;
}
Int_t nPoints = fkTimeBins;
TGraph *graphHG = new TGraph(nPoints,time,fDataHG);
TGraph *graphLG = new TGraph(nPoints,time,fDataLG);
graphHG->SetMarkerStyle(20);
graphLG->SetMarkerStyle(20);
graphHG->SetMarkerSize(0.4);
graphLG->SetMarkerSize(0.4);
graphHG->SetTitle("High gain samples");
graphLG->SetTitle("Low gain samples");
TCanvas *c1 = new TCanvas("c1","Raw ALTRO samples",10,10,700,500);
c1->SetFillColor(0);
if (strstr(opt,"all")){
c1->Divide(2,1);
c1->cd(1);
gPad->SetLeftMargin(0.15);
}
if (strstr(opt,"LG") == 0){
graphHG->Draw("AP");
graphHG->GetHistogram()->SetTitleOffset(1.0,"Y");
graphHG->GetHistogram()->SetXTitle("time, sec");
graphHG->GetHistogram()->SetYTitle("Amplitude, ADC counts");
}
if (strstr(opt,"all")){
c1->cd(2);
gPad->SetLeftMargin(0.15);
}
if (strstr(opt,"HG") == 0){
graphLG->Draw("AP");
graphLG->GetHistogram()->SetTitleOffset(1.0,"Y");
graphLG->GetHistogram()->SetXTitle("time, sec");
graphLG->GetHistogram()->SetYTitle("Amplitude, ADC counts");
}
c1->Update();
}
| 33.952542 | 137 | 0.60613 | [
"object",
"shape"
] |
dcab09284fca75b8c42a7f75f4843bd7b0f61646 | 809 | cpp | C++ | Client/Source Files/ChatClient.cpp | SahibYar/Diffie-Hellman-key-exchange | 71ed1a94200ec8e3323cf2981f0b790bfa8a99bc | [
"Apache-2.0"
] | 4 | 2019-06-12T00:22:15.000Z | 2022-02-07T20:02:24.000Z | Client/Source Files/ChatClient.cpp | SahibYar/Diffie-Hellman-key-exchange | 71ed1a94200ec8e3323cf2981f0b790bfa8a99bc | [
"Apache-2.0"
] | null | null | null | Client/Source Files/ChatClient.cpp | SahibYar/Diffie-Hellman-key-exchange | 71ed1a94200ec8e3323cf2981f0b790bfa8a99bc | [
"Apache-2.0"
] | 1 | 2021-10-06T12:26:46.000Z | 2021-10-06T12:26:46.000Z | #include <iostream>
#include <thread>
#include "ClassClient.hpp"
using namespace std;
int main()
{
char ip[15]; //variable to store the ip address
u_short port;
thread recv;
cout << "Client" << endl;
cout << "Enter the ip address of the server: ";
cin >> ip;
cout << "Enter the port of the server: ";
cin >> port;
ClientNetworkInit cli(ip, port); //construct the ClientNetworkInit object
cli.ConnectServer(); //connect to the specified server
ClientNetworkComInit(ip, port); //setup to enter your id and the id of the user you want to chat with
recv = thread(ClientNetworkComRecv); //start the reciever on a separate thread
recv.detach();
ClientNetworkComSend(); //run the sender in the main thread
return 0;
}
| 24.515152 | 110 | 0.646477 | [
"object"
] |
dcacfd8bf27e1463cb1dd32503fc9a9df574ea39 | 7,520 | cpp | C++ | src/homework_4.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | 2 | 2020-07-10T10:37:06.000Z | 2020-07-10T11:14:22.000Z | src/homework_4.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | null | null | null | src/homework_4.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | null | null | null | #include "homework_4.h"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
using namespace std;
using namespace cv;
const char* canny_window_name = "homework 4 - canny edge detection";
const char* hough_window_name = "homework 4 - hough lines detection";
const char* result_window_name = "homework 4 - result";
struct HoughParams {
Mat detected_edges;
Mat orig_img;
double rho_resolution = 1.0;
double theta_resolution = 0.05;
int lines_threshold = 120;
int circle_acc_threshold = 30;
int circle_max_radius = 10;
};
struct CannyParams {
Mat src;
Mat detected_edges;
int low_threshold = 283;
int threshold_ratio = 3;
int kernel_size = 3;
HoughParams *hough_params;
};
struct Line {
Point a;
Point b;
};
/**
* Convert lines in polar coordinates which is returned by hough transform into pairs
* of points in x/y coordinates which delimit the lines.
* @param input_lines The vector of input lines, each line is a Vec2f containing rho and theta
* @param output_lines The output vector of lines, each line is a Line object containing a pair of Point.
*/
void polar_lines_to_cartesian(vector<Vec2f> &input_lines, vector<Line> &output_lines) {
for ( size_t i = 0; i < input_lines.size(); i++ ) {
float rho = input_lines[i][0], theta = input_lines[i][1];
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
Line line;
line.a.x = cvRound(x0 + 1000*(-b));
line.a.y = cvRound(y0 + 1000*(a));
line.b.x = cvRound(x0 - 1000*(-b));
line.b.y = cvRound(y0 - 1000*(a));
output_lines.push_back(line);
}
}
/**
* Finds the intersection of two lines, or returns false.
* The lines are defined by (o1, p1) and (o2, p2).
* The intersection point will be stored in Point2f &r
*/
bool lines_intersection(Point2f o1, Point2f p1, Point2f o2, Point2f p2,
Point2f &r) {
Point2f x = o2 - o1;
Point2f d1 = p1 - o1;
Point2f d2 = p2 - o2;
float cross = d1.x*d2.y - d1.y*d2.x;
if (abs(cross) < /*EPS*/1e-8)
return false;
double t1 = (x.x * d2.y - x.y * d2.x)/cross;
r = o1 + d1 * t1;
return true;
}
/**
* Draw a circle on given image
* @param img The image onto which the circle is to be drawn
* @param circle_to_draw The circle described as a Vec3f contaning center coordinates and circle radius.
*/
void draw_circle(Mat img, Vec3f circle_to_draw) {
Point center(cvRound(circle_to_draw[0]), cvRound(circle_to_draw[1]));
int radius = cvRound(circle_to_draw[2]);
circle( img, center, radius, Scalar(0,255,0), -1, 8, 0 );
}
/**
* Fill the lower triangle between two given intersecting lines and fill given circle, then show final result.
* @param img The source image
* @param line1 and line2 The pair of lines delimiting the triangle
* @param circle_to_draw The circle to draw described as a Vec3f contaning center coordinates and circle radius.
*/
void show_result(Mat img, Line line1, Line line2, Vec3f circle_to_draw) {
Point2f pt_intersection, pt1, pt2;
// find lower triangle vertices
if ( lines_intersection(line1.a, line1.b, line2.a, line2.b, pt_intersection) ) {
pt1 = line1.a.y > line1.b.y ? line1.a : line1.b;
pt2 = line2.a.y > line2.b.y ? line2.a : line2.b;
Point triangle[] = {pt1, pt2, pt_intersection};
const Point* polygons[] = {triangle};
int npt[] = { 3 };
// draw triangle
fillPoly(img, polygons, npt, 1, Scalar(0,0,255), LINE_8);
}
// draw circle
draw_circle(img, circle_to_draw);
// show result
imshow( result_window_name, img );
}
/**
* Callback function which runs hough transform to detect lines and circles in an image, then it finally
* show the final image coloring the space between two detected lines and a detected circle.
* @param params An HoughParams object contaning the source images, and parameters
*/
static void hough_transform(int, void *params) {
HoughParams *hough_params = static_cast<HoughParams*>(params);
// detect lines
vector<Vec2f> lines;
Mat detected_edges = hough_params->detected_edges;
HoughLines(detected_edges, lines, hough_params->rho_resolution,
hough_params->theta_resolution, hough_params->lines_threshold, 0, 0 );
// draw lines
vector<Line> lines_cartesian;
polar_lines_to_cartesian(lines, lines_cartesian);
Mat dst = hough_params->orig_img.clone();
for ( Line detected_line : lines_cartesian ) {
line( dst, detected_line.a, detected_line.b, Scalar(0,0,255), 2, LINE_AA);
}
// detect circles
vector<Vec3f> circles;
HoughCircles(detected_edges, circles, HOUGH_GRADIENT, 2, detected_edges.rows/4,
200, hough_params->circle_acc_threshold, 2, hough_params->circle_max_radius );
// draw circles
for (Vec3f circle : circles) {
draw_circle(dst, circle);
}
// show detected lines and circles
imshow( hough_window_name, dst );
// show final result
if (lines_cartesian.size() >= 2 && circles.size() > 0) {
show_result(hough_params->orig_img.clone(), lines_cartesian[0], lines_cartesian[1], circles[0]);
}
}
/**
* Callback function which runs canny edge detector on an image to detect edges and show the result.
* Then it finally calls the hough_transform callback on the detected edges to detect lines and circles.
* @param params An CannyParams object contaning the source images, and parameters
*/
static void canny_threshold(int, void *params) {
CannyParams *canny_params = static_cast<CannyParams*>(params);
Canny( canny_params->src, canny_params->detected_edges, canny_params->low_threshold,
canny_params->low_threshold * canny_params->threshold_ratio, canny_params->kernel_size );
// show result
imshow( canny_window_name, canny_params->detected_edges );
// run hough transform
canny_params->hough_params->detected_edges = canny_params->detected_edges;
hough_transform(0, canny_params->hough_params);
}
void main_homework_4() {
// loads an image
string path;
cout << "Type input image path (empty input loads 'data/lab4/input.png'): ";
getline(cin, path);
if (path.empty()) {
path = "data/lab4/input.png";
}
Mat input_img = imread(path);
namedWindow( canny_window_name );
namedWindow( hough_window_name );
Mat src_gray;
cvtColor( input_img, src_gray, COLOR_BGR2GRAY );
HoughParams hough_params;
hough_params.orig_img = input_img;
CannyParams canny_params;
canny_params.src = src_gray;
canny_params.hough_params = &hough_params;
const int max_low_threshold = 400;
const int max_hough_lines_threshold = 300;
const int max_hough_circle_threshold = 50;
createTrackbar( "Min canny threshold:", canny_window_name, &canny_params.low_threshold,
max_low_threshold, canny_threshold, &canny_params );
createTrackbar( "hough lines threshold:", hough_window_name, &hough_params.lines_threshold,
max_hough_lines_threshold, hough_transform, &hough_params );
createTrackbar( "hough circle threshold:", hough_window_name, &hough_params.circle_acc_threshold,
max_hough_circle_threshold, hough_transform, &hough_params );
canny_threshold(0, &canny_params);
hough_transform(0, &hough_params);
waitKey(0);
} | 34.3379 | 112 | 0.682048 | [
"object",
"vector",
"transform"
] |
dcadf8a950b292e8c7a5d4d660eac75d3830548d | 1,023 | hpp | C++ | src/blackhole/attribute/scope.hpp | bioothod/blackhole | 2bd242e6027f20019e60b600f50a9e25127db640 | [
"MIT"
] | 1 | 2015-01-12T05:23:28.000Z | 2015-01-12T05:23:28.000Z | src/blackhole/attribute/scope.hpp | bioothod/blackhole | 2bd242e6027f20019e60b600f50a9e25127db640 | [
"MIT"
] | null | null | null | src/blackhole/attribute/scope.hpp | bioothod/blackhole | 2bd242e6027f20019e60b600f50a9e25127db640 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include "blackhole/detail/config/platform/deprecated.hpp"
#include "blackhole/detail/config/underlying.hpp"
namespace blackhole {
namespace attribute {
//! @deprecated: It's very likely, that attribute scope will be dropped soon.
enum class scope_t : std::uint8_t {
local = 1 << 0, /* user-defined event attributes */
event = 1 << 1, /* not user-defined event attributes, like timestamp or message */
global = 1 << 2, /* logger object attributes */
thread = 1 << 3, /* thread attributes */
universe = 1 << 4 /* singleton attributes for entire application */
};
typedef aux::underlying_type<scope_t>::type scope_underlying_type;
static const scope_t DEFAULT_SCOPE = scope_t::local;
} // namespace attribute
namespace log {
namespace attribute {
typedef blackhole::attribute::scope_t scope
BLACKHOLE_DEPRECATED("Use `attribute::scope_t` instead.");
} // namespace attribute
} // namespace log
} // namespace blackhole
| 26.230769 | 94 | 0.691105 | [
"object"
] |
dcaf39eeec790b705d9565f364bd376c68b80d74 | 19,780 | cpp | C++ | software/arduino/ArdiChefController/WebServerSTPlus.cpp | tgit23/ArdiChef | e0ffbe1d17271175f32c144875b8da1ac7ce558d | [
"MIT"
] | 1 | 2016-02-13T06:57:11.000Z | 2016-02-13T06:57:11.000Z | software/arduino/ArdiChefController/WebServerSTPlus.cpp | tgit23/ArdiChef | e0ffbe1d17271175f32c144875b8da1ac7ce558d | [
"MIT"
] | 5 | 2015-04-24T17:01:02.000Z | 2016-02-13T23:29:10.000Z | software/arduino/ArdiChefController/WebServerSTPlus.cpp | tgit23/ArdiChef | e0ffbe1d17271175f32c144875b8da1ac7ce558d | [
"MIT"
] | null | null | null | #include "WebServerSTPlus.h"
const char legalChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890/.-_~";
/***********************************************************************************//**
* @brief WebServerSTPlus() Initializer
* Once the WebServer is initialezed network communications are active
* @param[in] mac - The mac address of the WebServer; must be unique on network
* @param[in] ip - The ip address for the WebServer if DHCP is not used
* @param[in] gateway - Set the networks gateway
* @param[in] subnet - Set the networks subnet mask
* @param[in] UseDHCP - Attempt to connect using DHCP (IP Address will be dynamic)
* @param[in] Port - The network port number to use (HTML is always 80)
* @notes
* Requires Arduino Ethernet Library - include <Ethernet.h>
*
* <B>Example:</B>@code{.cpp}
* WebServerSTPlus *webserver;
* webserver = new WebServerSTPlus(mac,ip,gateway,subnet,false,80); @endcode
**************************************************************************************/
WebServerSTPlus::WebServerSTPlus(byte mac[], IPAddress ip, IPAddress gateway, IPAddress subnet, bool UseDHCP, int Port) {
server = new EthernetServer(Port); // Create EthernetServer object
digitalWrite(W5100_CSPIN,HIGH); // disable w5100 SPI while starting SD
DB1((F("Starting SD..")));
if(!SD.begin(SD_CSPIN)) DB1L((F("failed"))); else DB1L((F("ok")));
//---------- Start Ethernet Connection --------------------------------
if(UseDHCP){
if (Ethernet.begin(mac) == 0) {
DB1L(("Failed to configure Ethernet using DHCP"));
UseDHCP = false; } //Default to Static Settings
}
if(!UseDHCP) Ethernet.begin(mac, ip, gateway, gateway, subnet);
DB1(("Server IP address: ")); // Print local IP address
for (byte b = 0; b < 4; b++) {
DB1((Ethernet.localIP()[b], DEC)); DB1(("."));
} DB1L(());
delay(2000);
server->begin();
unsigned long thisTime = millis();
for(int i=0;i<MAX_SOCK_NUM;i++) { connectTime[i] = thisTime; }
DB1L((F("Ready")));
}
/***********************************************************************************//**
* @brief doloop()
* Trigger function - needs to be called inside the main sketch loop()
**************************************************************************************/
void WebServerSTPlus::doloop(char *nc_code) {
EthernetClient client = server->available();
if(client) {
boolean currentLineIsBlank = true;
boolean currentLineIsGet = true;
int tCount = 0;
char tBuf[256];
int r,t;
char *pch;
char ext[5] = "";
char methodBuffer[8];
char requestBuffer[238];
char pageBuffer[48];
char paramBuffer[238];
char protocolBuffer[9];
char fileName[32];
char fileType[4];
int clientCount = 0;
int loopCount = 0; // this controls the timeout
requestNumber++;
DB1((F("\r\nClient request #"))); DB1((requestNumber)); DB1((F(": ")));
while (client.connected()) {
while(client.available()) {
// if packet, reset loopCount // loopCount = 0;
char c = client.read();
if(currentLineIsGet && tCount < 255)
{
tBuf[tCount] = c;
tCount++;
tBuf[tCount] = 0;
}
if (c == '\n' && currentLineIsBlank) {
DB1L((tBuf));
while(client.available()) client.read();
int scanCount = sscanf(tBuf,"%7s %237s %8s",methodBuffer,requestBuffer,protocolBuffer);
if(scanCount != 3) { DB1L((F("bad request"))); sendBadRequest(client); return; }
// Process ?nc= (numeric control) tags
pch = strtok(requestBuffer,"?");
if(pch != NULL) {
//strncpy(fileName,pch,31);
//strncpy(tBuf,pch,255);
strcpy(fileName,pch);
strcpy(tBuf,pch);
pch = strtok(NULL,"?");
if(pch != NULL) {
// Process URL parameters
strcpy(paramBuffer,pch);
// Numeric Control (nc=)
if( strncmp(pch,"nc=",3) == 0 ) {
strcpy(nc_code,pch+3);
DB1((F("param nc_code: ")));DB1L((nc_code));
// File Write (fw=)
} else if ( strncmp(pch,"fw=",3) == 0 ) {
//strcpy(paramBuffer,pch+3);
urldecode(paramBuffer,pch+3);
sdWrite(fileName,paramBuffer,WRITE);
// File Append (fa=)
} else if ( strncmp(pch,"fa=",3) == 0 ) {
//strcpy(paramBuffer,pch+3);
urldecode(paramBuffer,pch+3);
sdWrite(fileName,paramBuffer,APPEND);
// Undefined
} else {
DB1((F("undefined param: ")));DB1L((paramBuffer));
}
client.stop();
return;
} else {
paramBuffer[0] = 0;
}
}
strtoupper(requestBuffer);
strtoupper(tBuf);
DB1((F("method = "))); DB1L((methodBuffer));
if(strcmp(methodBuffer,"GET") != 0 && strcmp(methodBuffer,"HEAD") != 0) {
sendBadRequest(client);
return;
}
for(int x = 0; x < strlen(requestBuffer); x++) {
if(strchr(legalChars,requestBuffer[x]) == NULL) {
DB1L((F("bad character")));
sendBadRequest(client);
return;
}
}
DB1((F("params = "))); DB1L((paramBuffer));
DB1((F("protocol = "))); DB1L((protocolBuffer));
// if dynamic page name (this code looks in-complete
if(strcmp(requestBuffer,"/MYTEST.PHP") == 0) {
DB1L((F("dynamic page")));
}
else {
//----------- PARSE ----------------------
// Home page
if(strcmp(fileName,"/") == 0) { strcpy(fileName,"/INDEX.HTM"); }
//vvv[ File Name (Modify for SFN-8.3) ]vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
DB1((F("SD file = "))); DB1L((fileName));
pch = strrchr(fileName,'.'); //ptr to extension
if (pch!=NULL) {
int extlen = strlen(pch); //record original extension length
memcpy(ext,pch,4);pch[0]='\0'; //ext=4-digit copy, truncate name
strcpy(fileType,ext+1); //Copy file type
strtoupper(fileType); //All-caps for matching
if(extlen>4) strcat(fileName,"~1"); //Truncate files with long ext
}
pch = strrchr(fileName,'/'); //ptr to filename
if (pch!=NULL) {
if (strlen(pch)>9) {
pch[7]='~';pch[8]='1';pch[9]='\0'; //Truncate fileName to 8-digits
}
}
strcat(fileName,ext); //Concate extension
DB1((F("SD Mod file(FSN-8.3) = "))); DB1L((fileName));
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Check FileName
if(strlen(fileName) > 30) {
DB1L((F("filename too long")));
sendBadRequest(client);
return;
}
else if(strlen(fileType) > 3 || strlen(fileType) < 1) {
DB1((F("fileType '")));DB1((fileType));
DB1((F("' is wrong size of")));DB1((strlen(fileType)));
DB1L((F("file type invalid size")));
sendBadRequest(client);
return;
}
else {
DB1L((F("filename format ok")));
if(SD.exists(fileName)) {
// SRAM check
DB1((F("SRAM = ")));
DB1L((freeRam()));
DB1((F("file found..")));
File myFile = SD.open(fileName);
if(!myFile) {
DB1L((F("open error")));
sendFileNotFound(client);
return;
}
else DB1((F("opened..")));
strcpy_P(tBuf,PSTR("HTTP/1.0 200 OK\r\nContent-Type: "));
// send Content-Type
if(strcmp(fileType,"HTM") == 0) strcat_P(tBuf,PSTR("text/html"));
else if(strcmp(fileType,"PHP") == 0) strcat_P(tBuf,PSTR("text/html"));
else if(strcmp(fileType,"TXT") == 0) strcat_P(tBuf,PSTR("text/plain"));
else if(strcmp(fileType,"CSS") == 0) strcat_P(tBuf,PSTR("text/css"));
else if(strcmp(fileType,"GIF") == 0) strcat_P(tBuf,PSTR("image/gif"));
else if(strcmp(fileType,"JPG") == 0) strcat_P(tBuf,PSTR("image/jpeg"));
else if(strcmp(fileType,"JS") == 0) strcat_P(tBuf,PSTR("application/javascript"));
else if(strcmp(fileType,"ICO") == 0) strcat_P(tBuf,PSTR("image/x-icon"));
else if(strcmp(fileType,"PNG") == 0) strcat_P(tBuf,PSTR("image/png"));
else if(strcmp(fileType,"PDF") == 0) strcat_P(tBuf,PSTR("application/pdf"));
else if(strcmp(fileType,"ZIP") == 0) strcat_P(tBuf,PSTR("application/zip"));
else strcat_P(tBuf,PSTR("text/plain"));
strcat_P(tBuf,PSTR("\r\nConnection: close\r\n\r\n"));
client.write(tBuf);
if(strcmp(methodBuffer,"GET") == 0) {
DB1((F("send..")));
while(myFile.available()) {
clientCount = myFile.read(tBuf,64);
client.write((byte*)tBuf,clientCount);
}
}
myFile.close();
DB1L((F("closed")));
client.stop();
DB1L((F("disconnected")));
return;
}
else {
DB1L((F("File not found")));
sendFileNotFound(client);
root = SD.open("/");
printDirectory(root, 3);
return;
}
}
}
pch = strtok(paramBuffer,"&");
while(pch != NULL) {
if(strncmp(pch,"t=",2) == 0) {
t = atoi(pch+2);
DB1(("t=")); DB1L((t,DEC));
}
if(strncmp(pch,"r=",2) == 0) {
r = atoi(pch+2);
DB1(("r=")); DB1L((r,DEC));
}
pch = strtok(NULL,"& ");
}
DB1L((F("Sending response")));
strcpy_P(tBuf,PSTR("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"));
client.write(tBuf);
if(strcmp(methodBuffer,"GET") == 0) {
strcpy_P(tBuf,PSTR("<html><head><script type=\"text/javascript\">"));
client.write(tBuf);
strcpy_P(tBuf,PSTR("function show_alert() {alert(\"This is an alert\");}"));
client.write(tBuf);
strcpy_P(tBuf,PSTR("</script></head>"));
client.write(tBuf);
strcpy_P(tBuf,PSTR("<body><H1>TEST</H1><form method=GET onSubmit=\"show_alert()\">"));
client.write(tBuf);
strcpy_P(tBuf,PSTR("T: <input type=text name=t><br>"));
client.write(tBuf);
strcpy_P(tBuf,PSTR("R: <input type=text name=r><br><input type=submit></form></body></html>"));
client.write(tBuf);
}
client.stop();
}
else if (c == '\n') {
currentLineIsBlank = true;
currentLineIsGet = false;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
loopCount++;
if(loopCount > 1000) { // if 1000ms has passed since last packet
client.stop(); // close connection
DB1L(("\r\nTimeout"));
}
// delay 1ms for timeout timing
delay(1);
}
DB1L((F("disconnected")));
}
}
//----------------------- UTILITY ----------------------------------------
/***********************************************************************************//**
* @brief strtoupper(text)
* Change all characters to upper-case
**************************************************************************************/
void WebServerSTPlus::strtoupper(char* aBuf) {
for(int x = 0; x<strlen(aBuf);x++) {
aBuf[x] = toupper(aBuf[x]);
}
}
/***********************************************************************************//**
* @brief urldecode(return, request-text)
* Decode %xx URL encodes back into their original characters
**************************************************************************************/
void WebServerSTPlus::urldecode(char *dst, const char *src) {
char a, b;
while (*src) {
// If %dd found
if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) {
if (a >= 'a') { a -= 'a'-'A'; }
if (a >= 'A') { a -= ('A' - 10);} else { a -= '0';}
if (b >= 'a') { b -= 'a'-'A';}
if (b >= 'A') { b -= ('A' - 10);} else { b -= '0';}
*dst++ = 16*a+b;
src+=3;
} else { *dst++ = *src++; }
}
*dst++ = '\0';
}
/***********************************************************************************//**
* @brief freeRam()
* @return Returns the amount of free RAM memory on the Arduino
**************************************************************************************/
int WebServerSTPlus::freeRam() {
extern int __heap_start,*__brkval;
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int) __brkval);
}
/***********************************************************************************//**
* @brief checkSockStatus()
*
**************************************************************************************/
void WebServerSTPlus::checkSockStatus()
{
unsigned long thisTime = millis();
for (int i = 0; i < MAX_SOCK_NUM; i++) {
uint8_t s = W5100.readSnSR(i);
if((s == 0x17) || (s == 0x1C)) {
if(thisTime - connectTime[i] > 30000UL) {
DB1((F("\r\nSocket frozen: ")));
DB1L((i));
close(i);
}
}
else connectTime[i] = thisTime;
socketStat[i] = W5100.readSnSR(i);
}
}
/***********************************************************************************//**
* @brief ShowSockStatus()
*
**************************************************************************************/
void WebServerSTPlus::ShowSockStatus()
{
for (int i = 0; i < MAX_SOCK_NUM; i++) {
DB1((F("Socket#")));
DB1((i));
uint8_t s = W5100.readSnSR(i);
socketStat[i] = s;
DB1((F(":0x")));
DB1((s,16));
DB1((F(" ")));
DB1((W5100.readSnPORT(i)));
DB1((F(" D:")));
uint8_t dip[4];
W5100.readSnDIPR(i, dip);
for (int j=0; j<4; j++) {
DB1((dip[j],10));
if (j<3) DB1(("."));
}
DB1((F("(")));
DB1((W5100.readSnDPORT(i)));
DB1L((F(")")));
}
}
//----------------------- STATUS MESSAGES --------------------------------
/***********************************************************************************//**
* @brief sendBadRequest(client)
* send a "BAD REQUEST" html page
**************************************************************************************/
void WebServerSTPlus::sendBadRequest(EthernetClient thisClient) {
char tBuf[64];
strcpy_P(tBuf,PSTR("HTTP/1.0 400 Bad Request\r\n"));
thisClient.write(tBuf);
strcpy_P(tBuf,PSTR("Content-Type: text/html\r\nConnection: close\r\n\r\n"));
thisClient.write(tBuf);
strcpy_P(tBuf,PSTR("<html><body><H1>BAD REQUEST</H1></body></html>"));
thisClient.write(tBuf);
thisClient.stop();
DB1L((F("disconnected")));
}
/***********************************************************************************//**
* @brief sendBadRequest(client)
* send a "FILE NOT FOUND" html page
**************************************************************************************/
void WebServerSTPlus::sendFileNotFound(EthernetClient thisClient) {
char tBuf[64];
strcpy_P(tBuf,PSTR("HTTP/1.0 404 File Not Found\r\n"));
thisClient.write(tBuf);
strcpy_P(tBuf,PSTR("Content-Type: text/html\r\nConnection: close\r\n\r\n"));
thisClient.write(tBuf);
strcpy_P(tBuf,PSTR("<html><body><H1>FILE NOT FOUND</H1></body></html>"));
thisClient.write(tBuf);
thisClient.stop();
DB1L((F("disconnected")));
}
//----------------------------- SD Utility ------------------------------------------------------------
/***********************************************************************************//**
* @brief printDirectory(dir,numTabs)
* List the files in the 'dir' path of the SD-card on the Serial Monitor
**************************************************************************************/
void WebServerSTPlus::printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}
/***********************************************************************************//**
* @brief sdWrite(fileName,text,type)
* @param fileName The full path and fileName to write to on the SD-Card
* @param text The text to be written
* @param WriteType 'WRITE' or 'APPEND'
* @notes
* 'fileName' will be automatically parsed to the 8.3-SFN standard
**************************************************************************************/
void WebServerSTPlus::sdWrite(char* fileName, char* text, sdWriteType WriteType) {
DB1((F("WebServerSTPlus::sdWrite( '")));DB1((fileName));DB1((F("','")));DB1((text));DB1L((F("')")));
char *pch;
char ext[5] = "";
char fileType[4];
//vvv[ File Name (Modify for SFN-8.3) ]vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
DB1((F("SD file = "))); DB1L((fileName));
pch = strrchr(fileName,'.'); //ptr to extension
if (pch!=NULL) {
int extlen = strlen(pch); //record original extension length
memcpy(ext,pch,4);pch[0]='\0'; //ext=4-digit copy, truncate name
strcpy(fileType,ext+1); //Copy file type
strtoupper(fileType); //All-caps for matching
if(extlen>4) strcat(fileName,"~1"); //Truncate files with long ext
}
pch = strrchr(fileName,'/'); //ptr to filename
if (pch!=NULL) {
if (strlen(pch)>9) {
pch[7]='~';pch[8]='1';pch[9]='\0'; //Truncate fileName to 8-digits
}
}
strcat(fileName,ext); //Concate extension
DB1((F("SD Mod file(FSN-8.3) = "))); DB1L((fileName));
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if( WriteType==WRITE ) {
DB1((F("WRITE ")));
File myFile = SD.open(fileName,O_CREAT | O_TRUNC | O_WRITE);
myFile.write(text,strlen(text));
myFile.close();
DB1L((F("complete...")));
} else if( WriteType==APPEND ) {
DB1((F("APPEND ")));
if(!SD.exists(fileName)) { DB1L((F("file not found..."))); return; }
DB1((F("file found..")));
File myFile = SD.open(fileName,O_WRITE | O_APPEND);
myFile.write(text,strlen(text));
myFile.close();
DB1L((F("complete...")));
}
}
| 36.697588 | 121 | 0.449444 | [
"object"
] |
dcb1b46475a3852ae919c462154f1b3efda236d2 | 2,315 | cpp | C++ | Chapter10/list.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 480 | 2017-06-29T14:58:34.000Z | 2022-03-29T03:22:49.000Z | Chapter10/list.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 10 | 2017-09-06T10:33:38.000Z | 2021-05-31T11:54:23.000Z | Chapter10/list.cpp | raakasf/Cpp17-STL-Cookbook | bf889164c515094d37f18023af48fe86fcbb1824 | [
"MIT"
] | 133 | 2017-07-04T01:55:22.000Z | 2022-03-20T12:44:54.000Z | #include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <experimental/filesystem>
using namespace std;
using namespace experimental::filesystem;
static tuple<path, file_status, size_t> file_info(const directory_entry &entry)
{
const auto fs (status(entry));
return {entry.path(),
fs,
is_regular_file(fs) ? file_size(entry.path()) : 0u};
}
static char type_char(file_status fs)
{
if (is_directory(fs)) { return 'd'; }
else if (is_symlink(fs)) { return 'l'; }
else if (is_character_file(fs)) { return 'c'; }
else if (is_block_file(fs)) { return 'b'; }
else if (is_fifo(fs)) { return 'p'; }
else if (is_socket(fs)) { return 's'; }
else if (is_other(fs)) { return 'o'; }
else if (is_regular_file(fs)) { return 'f'; }
return '?';
}
static string rwx(perms p)
{
auto check ([p](perms bit, char c) { return (p & bit) == perms::none ? '-' : c; });
return {check(perms::owner_read, 'r'),
check(perms::owner_write, 'w'),
check(perms::owner_exec, 'x'),
check(perms::group_read, 'r'),
check(perms::group_write, 'w'),
check(perms::group_exec, 'x'),
check(perms::others_read, 'r'),
check(perms::others_write, 'w'),
check(perms::others_exec, 'x')};
}
static string size_string(size_t size)
{
stringstream ss;
if (size >= 1000000000) { ss << (size / 1000000000) << 'G'; }
else if (size >= 1000000) { ss << (size / 1000000) << 'M'; }
else if (size >= 1000) { ss << (size / 1000) << 'K'; }
else { ss << size << 'B'; }
return ss.str();
}
int main(int argc, char *argv[])
{
path dir {argc > 1 ? argv[1] : "."};
if (!exists(dir)) {
cout << "Path " << dir << " does not exist.\n";
return 1;
}
vector<tuple<path, file_status, size_t>> items;
transform(directory_iterator{dir}, {}, back_inserter(items), file_info);
for (const auto &[path, status, size]: items) {
cout << type_char(status) << rwx(status.permissions()) << " "
<< setw(4) << right << size_string(size) << " "
<< path.filename().c_str() << '\n';
}
}
| 29.303797 | 87 | 0.540821 | [
"vector",
"transform"
] |
dcbd7ccfa6075670db62ce44fc96ebc1ec5a58ed | 173,339 | cc | C++ | alljoyn/alljoyn_core/router/android/WFDTransport.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 37 | 2015-01-18T21:27:23.000Z | 2018-01-12T00:33:43.000Z | alljoyn/alljoyn_core/router/android/WFDTransport.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 14 | 2015-02-24T11:44:01.000Z | 2020-07-20T18:48:44.000Z | alljoyn/alljoyn_core/router/android/WFDTransport.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 29 | 2015-01-23T16:40:52.000Z | 2019-10-21T12:22:30.000Z | /**
* @file
* WFDTransport is a specialization of class Transport for daemons talking over
* Wi-Fi Direct links and doing Wi_Fi Direct pre-association service discovery.
*/
/******************************************************************************
* Copyright (c) 2012, 2014, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <qcc/platform.h>
#include <qcc/IPAddress.h>
#include <qcc/Socket.h>
#include <qcc/SocketStream.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>
#include <qcc/IfConfig.h>
#include <alljoyn/BusAttachment.h>
#include <alljoyn/TransportMask.h>
#include <alljoyn/Session.h>
#include "BusInternal.h"
#include "ConfigDB.h"
#include "RemoteEndpoint.h"
#include "Router.h"
#include "ns/IpNameService.h"
#include "WFDTransport.h"
#define QCC_MODULE "WFD"
using namespace std;
using namespace qcc;
const uint32_t WFD_LINK_TIMEOUT_PROBE_ATTEMPTS = 1;
const uint32_t WFD_LINK_TIMEOUT_PROBE_RESPONSE_DELAY = 10;
const uint32_t WFD_LINK_TIMEOUT_MIN_LINK_TIMEOUT = 40;
namespace ajn {
class _WFDEndpoint;
/**
* Name of transport used in transport specs.
*/
const char* WFDTransport::TransportName = "wfd";
/*
* An endpoint class to handle the details of authenticating a connection in a
* way that avoids denial of service attacks.
*/
class _WFDEndpoint : public _RemoteEndpoint {
public:
/**
* There are three threads that can be running around in this data
* structure. An auth thread is run before the endpoint is started in order
* to handle the security stuff that must be taken care of before messages
* can start passing. This enum reflects the states of the authentication
* process and the state can be found in m_authState. Once authentication
* is complete, the auth thread must go away, but it must also be joined,
* which is indicated by the AUTH_DONE state. The other threads are the
* endpoint RX and TX threads, which are dealt with by the EndpointState.
*/
enum AuthState {
AUTH_ILLEGAL = 0,
AUTH_INITIALIZED, /**< This endpoint structure has been allocated but no auth thread has been run */
AUTH_AUTHENTICATING, /**< We have spun up an authentication thread and it has begun running our user function */
AUTH_FAILED, /**< The authentication has failed and the authentication thread is exiting immidiately */
AUTH_SUCCEEDED, /**< The auth process (Establish) has succeeded and the connection is ready to be started */
AUTH_DONE, /**< The auth thread has been successfully shut down and joined */
};
/**
* There are three threads that can be running around in this data
* structure. Two threads, and RX thread and a TX thread are used to pump
* messages through an endpoint. These threads cannot be run until the
* authentication process has completed. This enum reflects the states of
* the endpoint RX and TX threads and can be found in m_epState. The auth
* thread is dealt with by the AuthState enum above. These threads must be
* joined when they exit, which is indicated by the EP_DONE state.
*/
enum EndpointState {
EP_ILLEGAL = 0,
EP_INITIALIZED, /**< This endpoint structure has been allocated but not used */
EP_FAILED, /**< Starting the RX and TX threads has failed and this endpoint is not usable */
EP_STARTED, /**< The RX and TX threads have been started (they work as a unit) */
EP_STOPPING, /**< The RX and TX threads are stopping (have run ThreadExit) but have not been joined */
EP_DONE /**< The RX and TX threads have been shut down and joined */
};
/**
* Connections can either be created as a result of a Connect() or an Accept().
* If a connection happens as a result of a connect it is the active side of
* a connection. If a connection happens because of an Accpet() it is the
* passive side of a connection. This is important because of reference
* counting of bus-to-bus endpoints.
*/
enum SideState {
SIDE_ILLEGAL = 0,
SIDE_INITIALIZED, /**< This endpoint structure has been allocated but don't know if active or passive yet */
SIDE_ACTIVE, /**< This endpoint is the active side of a connection */
SIDE_PASSIVE /**< This endpoint is the passive side of a connection */
};
_WFDEndpoint(WFDTransport* transport,
BusAttachment& bus,
bool incoming,
const qcc::String connectSpec,
qcc::SocketFd sock,
const qcc::IPAddress& ipAddr,
uint16_t port,
qcc::String guid)
: _RemoteEndpoint(bus, incoming, connectSpec, &m_stream, "wfd"),
m_transport(transport),
m_sideState(SIDE_INITIALIZED),
m_authState(AUTH_INITIALIZED),
m_epState(EP_INITIALIZED),
m_tStart(qcc::Timespec(0)),
m_authThread(this),
m_stream(sock),
m_ipAddr(ipAddr),
m_port(port),
m_guid(guid),
m_wasSuddenDisconnect(!incoming) { }
virtual ~_WFDEndpoint() { }
void SetStartTime(qcc::Timespec tStart) { m_tStart = tStart; }
qcc::Timespec GetStartTime(void) { return m_tStart; }
QStatus Authenticate(void);
void AuthStop(void);
void AuthJoin(void);
const qcc::IPAddress& GetIPAddress() { return m_ipAddr; }
uint16_t GetPort() { return m_port; }
qcc::String GetGuid() { return m_guid; }
SideState GetSideState(void) { return m_sideState; }
void SetActive(void)
{
m_sideState = SIDE_ACTIVE;
}
void SetPassive(void)
{
m_sideState = SIDE_PASSIVE;
}
AuthState GetAuthState(void) { return m_authState; }
void SetAuthDone(void)
{
m_authState = AUTH_DONE;
}
void SetAuthenticating(void)
{
m_authState = AUTH_AUTHENTICATING;
}
EndpointState GetEpState(void) { return m_epState; }
void SetEpFailed(void)
{
m_epState = EP_FAILED;
}
void SetEpStarted(void)
{
m_epState = EP_STARTED;
}
void SetEpStopping(void)
{
assert(m_epState == EP_STARTED);
m_epState = EP_STOPPING;
}
void SetEpDone(void)
{
assert(m_epState == EP_FAILED || m_epState == EP_STOPPING);
m_epState = EP_DONE;
}
bool IsSuddenDisconnect() { return m_wasSuddenDisconnect; }
void SetSuddenDisconnect(bool val) { m_wasSuddenDisconnect = val; }
QStatus SetLinkTimeout(uint32_t& linkTimeout)
{
QStatus status = ER_OK;
if (linkTimeout > 0) {
uint32_t to = max(linkTimeout, WFD_LINK_TIMEOUT_MIN_LINK_TIMEOUT);
to -= WFD_LINK_TIMEOUT_PROBE_RESPONSE_DELAY * WFD_LINK_TIMEOUT_PROBE_ATTEMPTS;
status = _RemoteEndpoint::SetLinkTimeout(to, WFD_LINK_TIMEOUT_PROBE_RESPONSE_DELAY, WFD_LINK_TIMEOUT_PROBE_ATTEMPTS);
if ((status == ER_OK) && (to > 0)) {
linkTimeout = to + WFD_LINK_TIMEOUT_PROBE_RESPONSE_DELAY * WFD_LINK_TIMEOUT_PROBE_ATTEMPTS;
}
} else {
_RemoteEndpoint::SetLinkTimeout(0, 0, 0);
}
return status;
}
/*
* Return true if the auth thread is STARTED, RUNNING or STOPPING. A true
* response means the authentication thread is in a state that indicates
* a possibility it might touch the endpoint data structure. This means
* don't delete the endpoint if this method returns true. This method
* indicates nothing about endpoint rx and tx thread state.
*/
bool IsAuthThreadRunning(void)
{
return m_authThread.IsRunning();
}
private:
class AuthThread : public qcc::Thread {
public:
AuthThread(_WFDEndpoint* conn) : Thread("auth"), ep(conn) { }
private:
virtual qcc::ThreadReturn STDCALL Run(void* arg);
_WFDEndpoint* ep;
};
WFDTransport* m_transport; /**< The server holding the connection */
volatile SideState m_sideState; /**< Is this an active or passive connection */
volatile AuthState m_authState; /**< The state of the endpoint authentication process */
volatile EndpointState m_epState; /**< The state of the endpoint authentication process */
qcc::Timespec m_tStart; /**< Timestamp indicating when the authentication process started */
AuthThread m_authThread; /**< Thread used to do blocking calls during startup */
qcc::SocketStream m_stream; /**< Stream used by authentication code */
qcc::IPAddress m_ipAddr; /**< Remote IP address. */
uint16_t m_port; /**< Remote port. */
qcc::String m_guid; /**< The GUID of the remote daemon corresponding to this endpoint */
bool m_wasSuddenDisconnect; /**< If true, assumption is that any disconnect is unexpected due to lower level error */
};
QStatus _WFDEndpoint::Authenticate(void)
{
QCC_DbgTrace(("WFDEndpoint::Authenticate()"));
/*
* Start the authentication thread.
*/
QStatus status = m_authThread.Start(this);
if (status != ER_OK) {
m_authState = AUTH_FAILED;
}
return status;
}
void _WFDEndpoint::AuthStop(void)
{
QCC_DbgTrace(("WFDEndpoint::AuthStop()"));
/*
* Ask the auth thread to stop executing. The only ways out of the thread
* run function will set the state to either AUTH_SUCCEEDED or AUTH_FAILED.
* There is a very small chance that we will send a stop to the thread after
* it has successfully authenticated, but we expect that this will result in
* an AUTH_FAILED state for the vast majority of cases. In this case, we
* notice that the thread failed the next time through the main server run
* loop, join the thread via AuthJoin below and delete the endpoint. Note
* that this is a lazy cleanup of the endpoint.
*/
m_authThread.Stop();
}
void _WFDEndpoint::AuthJoin(void)
{
QCC_DbgTrace(("WFDEndpoint::AuthJoin()"));
/*
* Join the auth thread to stop executing. All threads must be joined in
* order to communicate their return status. The auth thread is no exception.
* This is done in a lazy fashion from the main server accept loop, where we
* cleanup every time through the loop.
*/
m_authThread.Join();
}
void* _WFDEndpoint::AuthThread::Run(void* arg)
{
QCC_DbgTrace(("WFDEndpoint::AuthThread::Run()"));
ep->m_authState = AUTH_AUTHENTICATING;
/*
* We're running an authentication process here and we are cooperating with
* the main server thread. This thread is running in an object that is
* allocated on the heap, and the server is managing these objects so we
* need to coordinate getting all of this cleaned up.
*
* There is a state variable that only we write. The server thread only
* reads this variable, so there are no data sharing issues. If there is an
* authentication failure, this thread sets that state variable to
* AUTH_FAILED and then exits. The server holds a list of currently
* authenticating connections and will look for AUTH_FAILED connections when
* it runs its Accept loop. If it finds one, it will AuthJoin() this
* thread. Since we set AUTH_FAILED immediately before exiting, there will
* be no problem having the server block waiting for the Join() to complete.
* We fail authentication here and let the server clean up after us, lazily.
*
* If we succeed in the authentication process, we set the state variable
* to AUTH_SUCEEDED and then call back into the server telling it that we are
* up and running. It needs to take us off of the list of authenticating
* connections and put us on the list of running connections. This thread
* will quickly go away and will be replaced by the RX and TX threads of
* the running RemoteEndpoint.
*
* If we are running an authentication process, we are probably ultimately
* blocked on a socket. We expect that if the server is asked to shut
* down, it will run through its list of authenticating connections and
* AuthStop() each one. That will cause a thread Stop() which should unblock
* all of the reads and return an error which will eventually pop out here
* with an authentication failure.
*
* Finally, if the server decides we've spent too much time here and we are
* actually a denial of service attack, it can close us down by doing an
* AuthStop() on the authenticating endpoint. This will do a thread Stop()
* on the auth thread of the endpoint which will pop out of here as an
* authentication failure as well. The only ways out of this method must be
* with state = AUTH_FAILED or state = AUTH_SUCCEEDED.
*/
uint8_t byte;
size_t nbytes;
/*
* Eat the first byte of the stream. This is required to be zero by the
* DBus protocol. It is used in the Unix socket implementation to carry
* out-of-band capabilities, but is discarded here. We do this here since
* it involves a read that can block.
*/
QStatus status = ep->m_stream.PullBytes(&byte, 1, nbytes);
if ((status != ER_OK) || (nbytes != 1) || (byte != 0)) {
ep->m_stream.Close();
QCC_LogError(status, ("Failed to read first byte from stream"));
/*
* Management of the resources used by the authentication thread is done
* in one place, by the server Accept loop. The authentication thread
* writes its state into the connection and the server Accept loop reads
* this state. As soon as we set this state to AUTH_FAILED, we are
* telling the Accept loop that we are done with the conn data
* structure. That thread is then free to do anything it wants with the
* connection, including deleting it, so we are not allowed to touch
* conn after setting this state.
*
* In addition to releasing responsibility for the conn data structure,
* when we set the state to AUTH_SUCCEEDED we are telling the server
* accept loop that we are exiting now and so it can Join() on us (the
* authentication thread) without being worried about blocking since the
* next thing we do is exit.
*/
ep->m_authState = AUTH_FAILED;
return (void*)ER_FAIL;
}
/* Initialize the features for this endpoint */
ep->GetFeatures().isBusToBus = false;
ep->GetFeatures().isBusToBus = false;
ep->GetFeatures().handlePassing = false;
qcc::String authName;
qcc::String redirection;
/* Run the actual connection authentication code. */
QCC_DbgTrace(("WFDEndpoint::AuthThread::Run(): Establish()"));
status = ep->Establish("ANONYMOUS", authName, redirection);
if (status != ER_OK) {
ep->m_stream.Close();
QCC_LogError(status, ("Failed to establish WFD endpoint"));
/*
* Management of the resources used by the authentication thread is done
* in one place, by the server Accept loop. The authentication thread
* writes its state into the connection and the server Accept loop reads
* this state. As soon as we set this state to AUTH_FAILED, we are
* telling the Accept loop that we are done with the conn data
* structure. That thread is then free to do anything it wants with the
* connection, including deleting it, so we are not allowed to touch
* conn after setting this state.
*
* In addition to releasing responsibility for the conn data structure,
* when we set the state to AUTH_SUCCEEDED we are telling the server
* accept loop that we are exiting now and so it can Join() on us (the
* authentication thread) without being worried about blocking since the
* next thing we do is exit.
*/
ep->m_authState = AUTH_FAILED;
return (void*)status;
}
/*
* Tell the transport that the authentication has succeeded and that it can
* now bring the connection up.
*/
QCC_DbgTrace(("WFDEndpoint::AuthThread::Run(): Authenticated()"));
WFDEndpoint wfdEp = WFDEndpoint::wrap(ep);
ep->m_transport->Authenticated(wfdEp);
QCC_DbgTrace(("WFDEndpoint::AuthThread::Run(): Returning"));
/*
* We are now done with the authentication process. We have succeeded doing
* the authentication and we may or may not have succeeded in starting the
* endpoint TX and RX threads depending on what happened down in
* Authenticated(). What concerns us here is that we are done with this
* thread (the authentication thread) and we are about to exit. Before
* exiting, we must tell server accept loop that we are done with this data
* structure. As soon as we set this state to AUTH_SUCCEEDED that thread is
* then free to do anything it wants with the connection, including deleting
* it, so we are not allowed to touch conn after setting this state.
*
* In addition to releasing responsibility for the conn data structure, when
* we set the state to AUTH_SUCCEEDED we are telling the server accept loop
* that we are exiting now and so it can Join() the authentication thread
* without being worried about blocking since the next thing we do is exit.
*/
ep->m_authState = AUTH_SUCCEEDED;
return (void*)status;
}
WFDTransport::WFDTransport(BusAttachment& bus)
: Thread("WFDTransport"), m_bus(bus), m_stopping(false), m_listener(0),
m_isAdvertising(false), m_isDiscovering(false), m_isListening(false), m_isNsEnabled(false),
m_listenPort(0), m_p2pNsAcquired(false), m_p2pCmAcquired(false), m_ipNsAcquired(false)
{
QCC_DbgTrace(("WFDTransport::WFDTransport()"));
/*
* We know we are daemon code, so we'd better be running with a daemon
* router. This is assumed elsewhere.
*/
assert(m_bus.GetInternal().GetRouter().IsDaemon());
}
WFDTransport::~WFDTransport()
{
QCC_DbgTrace(("WFDTransport::~WFDTransport()"));
Stop();
Join();
}
void WFDTransport::Authenticated(WFDEndpoint& conn)
{
QCC_DbgTrace(("WFDTransport::Authenticated()"));
/*
* If the transport is stopping, dont start the Tx and RxThreads.
*/
if (m_stopping == true) {
return;
}
/*
* If Authenticated() is being called, it is as a result of the
* authentication thread telling us that it has succeeded. What we need to
* do here is to try and Start() the endpoint which will spin up its TX and
* RX threads and register the endpoint with the daemon router. As soon as
* we call Start(), we are transferring responsibility for error reporting
* through endpoint ThreadExit() function. This will percolate out our
* EndpointExit function. It will expect to find <conn> on the endpoint
* list so we move it from the authList to the endpointList before calling
* Start.
*/
m_endpointListLock.Lock(MUTEX_CONTEXT);
set<WFDEndpoint>::iterator i = find(m_authList.begin(), m_authList.end(), conn);
assert(i != m_authList.end() && "WFDTransport::Authenticated(): Conn not on m_authList");
/*
* Note here that we have not yet marked the authState as AUTH_SUCCEEDED so
* this is a point in time where the authState can be AUTH_AUTHENTICATING
* and the endpoint can be on the endpointList and not the authList.
*/
m_authList.erase(i);
m_endpointList.insert(conn);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
conn->SetListener(this);
QStatus status = conn->Start();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Authenticated(): Failed to start WFD endpoint"));
/*
* We were unable to start up the endpoint for some reason. As soon as
* we set this state to EP_FAILED, we are telling the server accept loop
* that we tried to start the connection but it failed. This connection
* is now useless and is a candidate for cleanup. This will be
* prevented until authState changes from AUTH_AUTHENTICATING to
* AUTH_SUCCEEDED. This may be a little confusing, but the
* authentication process has really succeeded but the endpoint start
* has failed. The combination of status in this case will be
* AUTH_SUCCEEDED and EP_FAILED. Once this state is detected by the
* server accept loop it is then free to do anything it wants with the
* connection, including deleting it.
*/
conn->SetEpFailed();
} else {
/*
* We were able to successfully start up the endpoint. As soon as we
* set this state to EP_STARTED, we are telling the server accept loop
* that there are TX and RX threads wandering around in this endpoint.
*/
conn->SetEpStarted();
}
}
QStatus WFDTransport::Start()
{
QCC_DbgTrace(("WFDTransport::Start()"));
/*
* We rely on the status of the server accept thead as the primary
* gatekeeper.
*
* A true response from IsRunning tells us that the server accept thread is
* STARTED, RUNNING or STOPPING.
*
* When a thread is created it is in state INITIAL. When an actual tread is
* spun up as a result of Start(), it becomes STARTED. Just before the
* user's Run method is called, the thread becomes RUNNING. If the Run
* method exits, the thread becomes STOPPING. When the thread is Join()ed
* it becomes DEAD.
*
* IsRunning means that someone has called Thread::Start() and the process
* has progressed enough that the thread has begun to execute. If we get
* multiple Start() calls calls on multiple threads, this test may fail to
* detect multiple starts in a failsafe way and we may end up with multiple
* server accept threads running. We assume that since Start() requests
* come in from our containing transport list it will not allow concurrent
* start requests.
*/
if (IsRunning()) {
QCC_LogError(ER_BUS_BUS_ALREADY_STARTED, ("WFDTransport::Start(): Already started"));
return ER_BUS_BUS_ALREADY_STARTED;
}
m_stopping = false;
/*
* Get the guid from the bus attachment which will act as the globally unique
* ID of the daemon.
*/
qcc::String guidStr = m_bus.GetInternal().GetGlobalGUID().ToString();
/*
* We're a WFD transport in the AllJoyn sense, so we are going to have to
* use the P2P name service and P2P connection manager to get our Wi-Fi
* requests done for us. This means we are going to have to Acquire() and
* Release() the corresponding singletons.
*
* Start() will legally be called exactly once, but Stop() and Join() may be
* called multiple times. Since we are essentially reference counting the
* name service and connection manager singletons with calls to Acquire and
* Release, we need to make sure that we Release exactly as many times as we
* Acquire. We just use a flag to mark whether or not we have done each
* operation exactly one time.
*/
m_p2pNsAcquired = false;
m_p2pCmAcquired = false;
m_ipNsAcquired = false;
/*
* Start the server accept loop through the thread base class. This will
* close or open the IsRunning() gate we use to control access to our
* public API.
*/
return Thread::Start();
}
QStatus WFDTransport::Stop(void)
{
QCC_DbgTrace(("WFDTransport::Stop()"));
/*
* It is legal to call Stop() more than once, so it must be possible to
* call Stop() on a stopped transport.
*/
m_stopping = true;
/*
* Tell the P2P name service to stop calling us back if it's there (we may
* get called more than once in the chain of destruction) so the pointer
* to the name service is not required to be valid -- i.e., it may be NULL
* from a previous call.
*/
if (m_p2pNsAcquired) {
P2PNameService::Instance().SetCallback(TRANSPORT_WFD, NULL);
}
/*
* Tell the P2P connection manager to stop calling us back as well over its
* state-changed callback.
*/
if (m_p2pCmAcquired) {
P2PConMan::Instance().SetStateCallback(NULL);
P2PConMan::Instance().SetNameCallback(NULL);
}
/*
* Tell the server accept loop thread to shut down through the thead
* base class.
*/
QStatus status = Thread::Stop();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Stop(): Failed to Stop() server thread"));
return status;
}
m_endpointListLock.Lock(MUTEX_CONTEXT);
/*
* Ask any authenticating ACTIVE endpoints to shut down and return to the
* caller. By its presence on the m_activeEndpointsThreadList, we know that
* an external (from the point of this module) thread is authenticating and
* is probably blocked waiting for the other side to respond. We can't call
* Stop() to stop that thread from running, we have to Alert() it to make it
* pop out of its blocking calls.
*/
for (set<Thread*>::iterator i = m_activeEndpointsThreadList.begin(); i != m_activeEndpointsThreadList.end(); ++i) {
(*i)->Alert();
}
/*
* Ask any authenticating endpoints to shut down and exit their threads. By its
* presence on the m_authList, we know that the endpoint is authenticating and
* the authentication thread has responsibility for dealing with the endpoint
* data structure. We call Stop() to stop that thread from running. The
* endpoint Rx and Tx threads will not be running yet.
*/
for (set<WFDEndpoint>::iterator i = m_authList.begin(); i != m_authList.end(); ++i) {
WFDEndpoint ep = *i;
ep->AuthStop();
}
/*
* Ask any running endpoints to shut down and exit their threads. By its
* presence on the m_endpointList, we know that authentication is compete and
* the Rx and Tx threads have responsibility for dealing with the endpoint
* data structure. We call Stop() to stop those threads from running. Since
* the connnection is on the m_endpointList, we know that the authentication
* thread has handed off responsibility.
*/
for (set<WFDEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) {
WFDEndpoint ep = *i;
ep->Stop();
}
m_endpointListLock.Unlock(MUTEX_CONTEXT);
return ER_OK;
}
QStatus WFDTransport::Join(void)
{
QCC_DbgTrace(("WFDTransport::Join()"));
/*
* It is legal to call Join() more than once, so it must be possible to
* call Join() on a joined transport and also on a joined name service.
*/
QStatus status = Thread::Join();
if (status != ER_OK) {
return status;
}
/*
* We expect that all of our calls to Start(), Stop() and Join() are
* orchestrated through the transport list and will ultimately come from
* only one thread. The place that we are setting these flags is in the
* main accept loop thread, but we just joined that thread immediately
* above, so it cannot be running now. So we're not concerned about
* multithreading and we just look at our acquired flags and set them
* without "protection."
*/
if (m_p2pNsAcquired) {
P2PNameService::Instance().Release();
m_p2pNsAcquired = false;
}
if (m_p2pCmAcquired) {
P2PConMan::Instance().Release();
m_p2pCmAcquired = false;
}
if (m_ipNsAcquired) {
IpNameService::Instance().Release();
m_ipNsAcquired = false;
}
/*
* A required call to Stop() that needs to happen before this Join will ask
* all of the endpoints to stop; and will also cause any authenticating
* endpoints to stop. We still need to wait here until all of the threads
* running in those endpoints actually stop running.
*
* Since Stop() is a request to stop, and this is what has ultimately been
* done to both authentication threads and Rx and Tx threads, it is possible
* that a thread is actually running after the call to Stop(). If that
* thead happens to be an authenticating endpoint, it is possible that an
* authentication actually completes after Stop() is called. This will move
* a connection from the m_authList to the m_endpointList, so we need to
* make sure we wait for all of the connections on the m_authList to go away
* before we look for the connections on the m_endpointlist.
*/
m_endpointListLock.Lock(MUTEX_CONTEXT);
/*
* Any authenticating endpoints have been asked to shut down and exit their
* authentication threads in a previously required Stop(). We need to
* Join() all of these auth threads here.
*/
set<WFDEndpoint>::iterator it = m_authList.begin();
while (it != m_authList.end()) {
WFDEndpoint ep = *it;
m_authList.erase(it);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
ep->AuthJoin();
m_endpointListLock.Lock(MUTEX_CONTEXT);
it = m_authList.upper_bound(ep);
}
/*
* Any running endpoints have been asked it their threads in a previously
* required Stop(). We need to Join() all of thesse threads here. This
* Join() will wait on the endpoint rx and tx threads to exit as opposed to
* the joining of the auth thread we did above.
*/
it = m_endpointList.begin();
while (it != m_endpointList.end()) {
WFDEndpoint ep = *it;
m_endpointList.erase(it);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
ep->Join();
m_endpointListLock.Lock(MUTEX_CONTEXT);
it = m_endpointList.upper_bound(ep);
}
m_endpointListLock.Unlock(MUTEX_CONTEXT);
m_stopping = false;
return ER_OK;
}
QStatus WFDTransport::GetListenAddresses(const SessionOpts& opts, std::vector<qcc::String>& busAddrs) const
{
QCC_DbgTrace(("WFDTransport::GetListenAddresses()"));
/*
* We are given a session options structure that defines the kind of
* transports that are being sought. WFD provides reliable traffic as
* understood by the session options, so we only return someting if
* the traffic type is TRAFFIC_MESSAGES or TRAFFIC_RAW_RELIABLE. It's
* not an error if we don't match, we just don't have anything to offer.
*/
if (opts.traffic != SessionOpts::TRAFFIC_MESSAGES && opts.traffic != SessionOpts::TRAFFIC_RAW_RELIABLE) {
QCC_DbgPrintf(("WFDTransport::GetListenAddresses(): traffic mismatch"));
return ER_OK;
}
/*
* The other session option that we need to filter on is the transport
* bitfield. There is a single bit in a TransportMask that corresponds
* to a transport in the AllJoyn sense. We are TRANSPORT_WFD.
*/
if (!(opts.transports & TRANSPORT_WFD)) {
QCC_DbgPrintf(("WFDTransport::GetListenAddresses(): transport mismatch"));
return ER_OK;
}
/*
* The abstract goal of a GetListenAddresses() call is to generate a list of
* interfaces that could possibly be used by a remote daemon to connect to
* this instance of our WFD transport. The interfaces are returned in the
* form of bus addresses and are shipped back to the remote side to be used
* in a WFDTransport::Connect() there. Since a connect spec for a WFD
* transport is just a guid=xxx, the only meaningful thing we could possibly
* return is our daemon's guid.
*/
qcc::String busAddr = qcc::String(GetTransportName()) + qcc::String(":guid=") + m_bus.GetInternal().GetGlobalGUID().ToString();
busAddrs.push_back(busAddr);
return ER_OK;
}
void WFDTransport::EndpointExit(RemoteEndpoint& ep)
{
QCC_DbgTrace(("WFDTransport::EndpointExit()"));
/*
* This is a callback driven from the remote endpoint thread exit function.
* Our WFDEndpoint inherits from class RemoteEndpoint and so when
* either of the threads (transmit or receive) of one of our endpoints exits
* for some reason, we get called back here. We only get called if either
* the tx or rx thread exits, which implies that they have been run. It
* turns out that in the case of an endpoint receiving a connection, it
* means that authentication has succeeded. In the case of an endpoint
* doing the connect, the EndpointExit may have resulted from an
* authentication error since authentication is done in the context of the
* Connect()ing thread and may be reported through EndpointExit.
*/
WFDEndpoint tep = WFDEndpoint::cast(ep);
/*
* The endpoint can exit if it was asked to by us in response to a
* Disconnect() from higher level code, or if it got an error from the
* underlying transport. We need to notify upper level code if the
* disconnect is due to an event from the transport.
*/
if (m_listener && tep->IsSuddenDisconnect()) {
m_listener->BusConnectionLost(tep->GetConnectSpec());
}
/*
* If this is an active connection, what has happened is that the reference
* count on the underlying RemoteEndpoint has been decremented to zero and
* the Stop() function of the endpoint has been called. This means that
* we are done with the endpoint and it should be cleaned up. Marking
* the connection as active prevented the passive side cleanup, so we need
* to deal with cleanup now.
*/
tep->SetPassive();
/*
* Mark the endpoint as no longer running. Since we are called from
* the RemoteEndpoint ThreadExit routine, we know it has stopped both
* the RX and TX threads and we can Join them in a timely manner.
*/
tep->SetEpStopping();
/*
* Wake up the server accept loop so that it deals with our passing immediately.
*/
Alert();
}
void WFDTransport::ManageEndpoints(Timespec tTimeout)
{
QCC_DbgTrace(("WFDTransport::ManageEndpoints()"));
m_endpointListLock.Lock(MUTEX_CONTEXT);
/*
* This is the one place where we deal with the management (deletion) of
* endpoints. This is the place where we have to decide what to do when
* the last of the endpoints we are managing is destroyed.
*
* In the case of a client application, when a Connect() is performed, we
* arrange with the P2P Helper Service to bring up a Wi-Fi Direct STA
* connection to the service device. You might think that when the last
* endpoint is freed, you would see a corresponding Disconnect() but you
* would be mistaken. Disconnect() is defined for transports, but it turns
* out that it is never called. When the daemon is done with a link to an
* external entity, it simply tears down the endpoint. Therefore, we need
* to detect when to tear down the underlying Wi-Fi Direct connection here.
*
* In Connect() we need to be careful to only force the actual link
* establishment for the first connection attempt to a remote device since
* we can have more than one layer four-based (TCP) endpoint running a TCP
* connection over a layer two-based (MAC) Wi-Fi Direct link. Here we need
* to be careful to only tear down the actual link when the last endpoint
* goes away.
*
* So, we need to make sure that the link is kept up 1) before any endpoints
* are actually created; 2) while endpoints exist; and then take down the
* link when the last of the endpoints have exited and been cleaned up.
*
* Another way of saying this is that we only send a ReleaseLink to the
* P2P Helper Service if there are no endpoints left and we've cleaned up
* at least one here in ManageEndpoints.
*
* If we are representing a service application, we enter a ready state when
* we advertise the service and when a remote application/daemon connects,
* we enter the connected state on reception of an OnLinkEstablished().
*
* We can actually be running both as a client and a service if we are
* hosting a pure peer-to-peer application. In this case, if all of the
* endpoints are torn down, we have to be careful to re-enter the ready
* state appropriate to a service and not the idle state appropriate to a
* client.
*/
bool endpointCleaned = false;
/*
* Run through the list of connections on the authList and cleanup
* any that are no longer running or are taking too long to authenticate
* (we assume a denial of service attack in this case).
*/
set<WFDEndpoint>::iterator i = m_authList.begin();
while (i != m_authList.end()) {
WFDEndpoint ep = *i;
_WFDEndpoint::AuthState authState = ep->GetAuthState();
if (authState == _WFDEndpoint::AUTH_FAILED) {
/*
* The endpoint has failed authentication and the auth thread is
* gone or is going away. Since it has failed there is no way this
* endpoint is going to be started so we can get rid of it as soon
* as we Join() the (failed) authentication thread.
*/
QCC_DbgPrintf(("WFDTransport::ManageEndpoints(): Scavenging failed authenticator"));
m_authList.erase(i);
endpointCleaned = true;
m_endpointListLock.Unlock(MUTEX_CONTEXT);
ep->AuthJoin();
m_endpointListLock.Lock(MUTEX_CONTEXT);
i = m_authList.upper_bound(ep);
continue;
}
Timespec tNow;
GetTimeNow(&tNow);
if (ep->GetStartTime() + tTimeout < tNow) {
/*
* This endpoint is taking too long to authenticate. Stop the
* authentication process. The auth thread is still running, so we
* can't just delete the connection, we need to let it stop in its
* own time. What that thread will do is to set AUTH_FAILED and
* exit. We will then clean it up the next time through this loop.
* In the hope that the thread can exit and we can catch its exit
* here and now, we take our thread off the OS ready list (Sleep)
* and let the other thread run before looping back.
*/
QCC_DbgPrintf(("WFDTransport::ManageEndpoints(): Scavenging slow authenticator"));
ep->AuthStop();
qcc::Sleep(1);
}
++i;
}
/*
* We've handled the authList, so now run through the list of connections on
* the endpointList and cleanup any that are no longer running or Join()
* authentication threads that have successfully completed.
*/
i = m_endpointList.begin();
while (i != m_endpointList.end()) {
WFDEndpoint ep = *i;
/*
* We are only managing passive connections here, or active connections
* that are done and are explicitly ready to be cleaned up.
*/
_WFDEndpoint::SideState sideState = ep->GetSideState();
if (sideState == _WFDEndpoint::SIDE_ACTIVE) {
++i;
continue;
}
_WFDEndpoint::AuthState authState = ep->GetAuthState();
_WFDEndpoint::EndpointState endpointState = ep->GetEpState();
if (authState == _WFDEndpoint::AUTH_SUCCEEDED) {
/*
* The endpoint has succeeded authentication and the auth thread is
* gone or is going away. Take this opportunity to join the auth
* thread. Since the auth thread promised not to touch the state
* after setting AUTH_SUCCEEEDED, we can safely change the state
* here since we now own the conn. We do this through a method call
* to enable this single special case where we are allowed to set
* the state.
*/
QCC_DbgPrintf(("WFDTransport::ManageEndpoints(): Scavenging failed authenticator"));
m_endpointListLock.Unlock(MUTEX_CONTEXT);
ep->AuthJoin();
ep->SetAuthDone();
m_endpointListLock.Lock(MUTEX_CONTEXT);
i = m_endpointList.upper_bound(ep);
continue;
}
/*
* There are two possibilities for the disposition of the RX and
* TX threads. First, they were never successfully started. In
* this case, the epState will be EP_FAILED. If we find this, we
* can just remove the useless endpoint from the list and delete
* it. Since the threads were never started, they must not be
* joined.
*/
if (endpointState == _WFDEndpoint::EP_FAILED) {
m_endpointList.erase(i);
endpointCleaned = true;
m_endpointListLock.Unlock(MUTEX_CONTEXT);
m_endpointListLock.Lock(MUTEX_CONTEXT);
i = m_endpointList.upper_bound(ep);
continue;
}
/*
* The second possibility for the disposition of the RX and
* TX threads is that they were successfully started but
* have been stopped for some reason, either because of a
* Disconnect() or a network error. In this case, the
* epState will be EP_STOPPING, which was set in the
* EndpointExit function. If we find this, we need to Join
* the endpoint threads, remove the endpoint from the
* endpoint list and delete it. Note that we are calling
* the endpoint Join() to join the TX and RX threads and not
* the endpoint AuthJoin() to join the auth thread.
*/
if (endpointState == _WFDEndpoint::EP_STOPPING) {
m_endpointList.erase(i);
endpointCleaned = true;
m_endpointListLock.Unlock(MUTEX_CONTEXT);
ep->Join();
m_endpointListLock.Lock(MUTEX_CONTEXT);
i = m_endpointList.upper_bound(ep);
continue;
}
++i;
}
/*
* As mentioned in the lengthy comment above, if we've cleaned up an
* endpoint and there are no more left (in the list of currently active
* endpoints and the list of currently authenticating endpoitns), then we
* need to release any resources we may have reserved as a result of the
* now unneeded (possibly already released) Wi-Fi Direct link.
*
* If we think were only a client (using the link in STA mode), we just go
* idle by calling DestroyTemporaryNetwork().
*
* However, if we think we are a service (if we are advertising) we need to
* free the Wi-Fi Group resource by calling DestroyTemporaryNetwork() but we
* also need to make sure to enter the ready state by calling
* CreateTemporaryNetwork() in order to be ready to accept new connections
* from possible clients in the future.
*
* Note that the m_isAdvertising test below is not a failsafe test for
* advertisement, since AdvertiseName() and CancelAdvertiseName() calls may
* be percolating through the main thread, but if we get it wrong here, when
* those percolating calls are actually executed, they will get it right.
*
* To further complicate things, we will also get an OnLinkLost() signal
* down in the P2PConMan when the last wireless link of our Wi-Fi interface
* is dropped. This happens if the single STA connection drops or if the
* last STA disconnects from the interface if in GO mode. The important
* thing to realize is that at this level we are dealing with endpoint
* (TCP/IP -- layers three and four) connections being lost not Wi-Fi
* (layers one and two) connections being lost, so if the link remains up
* we need to cause it to be torn down. If the link dropping has caused
* the endpoint exits, these events can happen in unfortunate sequences.
*
* The bottom line is that our last endpoint has exited so we need to
* release our resources and get back into the appropriate state. This may
* be the ready state if we are advertising a service or the idle state if
* we are not.
*
* This situation is full of possible race conditions since the low level
* (layer two) link lost messages are being routed out to the Android
* Application Framework and back over an AllJoyn service, but the high
* level (layer four) connection lost messages are routed up from the kernel
* through TCP directly here. This means that the ordering of the events
* EndpointExit() and OnLinkLost() is not deterministic at all.
*/
if (endpointCleaned && m_endpointList.empty() && m_authList.empty()) {
QCC_DbgPrintf(("WFDTransport::ManageEndpoints(): DestroyTemporaryNetwork()"));
QStatus status = P2PConMan::Instance().DestroyTemporaryNetwork();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::ManageEndpoints(): Unable to destroy temporary network"));
}
if (m_isAdvertising) {
qcc::String localDevice("");
QStatus status = P2PConMan::Instance().CreateTemporaryNetwork(localDevice, P2PConMan::DEVICE_SHOULD_BE_GO);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::ManageEndpoints(): Unable to recreate temporary network (SHOULD_BE_GO)"));
}
}
}
m_endpointListLock.Unlock(MUTEX_CONTEXT);
}
void* WFDTransport::Run(void* arg)
{
QCC_DbgTrace(("WFDTransport::Run()"));
/*
* We need to find the defaults for our connection limits. These limits
* can be specified in the configuration database with corresponding limits
* used for DBus. If any of those are present, we use them, otherwise we
* provide some hopefully reasonable defaults.
*/
ConfigDB* config = ConfigDB::GetConfigDB();
/*
* tTimeout is the maximum amount of time we allow incoming connections to
* mess about while they should be authenticating. If they take longer
* than this time, we feel free to disconnect them as deniers of service.
*/
Timespec tTimeout = config->GetLimit("auth_timeout", ALLJOYN_AUTH_TIMEOUT_DEFAULT);
/*
* maxAuth is the maximum number of incoming connections that can be in
* the process of authenticating. If starting to authenticate a new
* connection would mean exceeding this number, we drop the new connection.
*/
uint32_t maxAuth = config->GetLimit("max_incomplete_connections", ALLJOYN_MAX_INCOMPLETE_CONNECTIONS_WFD_DEFAULT);
/*
* maxConn is the maximum number of active connections possible over the
* WFD transport. If starting to process a new connection would mean
* exceeding this number, we drop the new connection.
*/
uint32_t maxConn = config->GetLimit("max_completed_connections", ALLJOYN_MAX_COMPLETED_CONNECTIONS_WFD_DEFAULT);
QStatus status = ER_OK;
while (!IsStopping()) {
/*
* Each time through the loop we create a set of events to wait on.
* We need to wait on the stop event and all of the SocketFds of the
* addresses and ports we are listening on. If the list changes, the
* code that does the change Alert()s this thread and we wake up and
* re-evaluate the list of SocketFds.
*/
m_listenFdsLock.Lock(MUTEX_CONTEXT);
vector<Event*> checkEvents, signaledEvents;
checkEvents.push_back(&stopEvent);
for (list<pair<qcc::String, SocketFd> >::const_iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) {
checkEvents.push_back(new Event(i->second, Event::IO_READ));
}
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
/*
* We have our list of events, so now wait for something to happen
* on that list (or get alerted).
*/
signaledEvents.clear();
status = Event::Wait(checkEvents, signaledEvents);
if (ER_OK != status) {
QCC_LogError(status, ("Event::Wait failed"));
break;
}
/*
* We're back from our Wait() so one of three things has happened. Our
* thread has been asked to Stop(), our thread has been Alert()ed, or
* one of the socketFds we are listening on for connecte events has
* becomed signalled.
*
* If we have been asked to Stop(), or our thread has been Alert()ed,
* the stopEvent will be on the list of signalled events. The
* difference can be found by a call to IsStopping() which is found
* above. An alert means that a request to start or stop listening
* on a given address and port has been queued up for us.
*/
for (vector<Event*>::iterator i = signaledEvents.begin(); i != signaledEvents.end(); ++i) {
/*
* In order to rationalize management of resources, we manage the
* various lists in one place on one thread. This thread is a
* convenient victim, so we do it here.
*/
ManageEndpoints(tTimeout);
/*
* Reset an existing Alert() or Stop(). If it's an alert, we
* will deal with looking for the incoming listen requests at
* the bottom of the server loop. If it's a stop we will
* exit the next time through the top of the server loop.
*/
if (*i == &stopEvent) {
stopEvent.ResetEvent();
continue;
}
/*
* Since the current event is not the stop event, it must reflect at
* least one of the SocketFds we are waiting on for incoming
* connections. Go ahead and Accept() the new connection on the
* current SocketFd.
*/
IPAddress remoteAddr;
uint16_t remotePort;
SocketFd newSock;
while (true) {
status = Accept((*i)->GetFD(), remoteAddr, remotePort, newSock);
if (status != ER_OK) {
break;
}
QCC_DbgPrintf(("WFDTransport::Run(): Accepting connection newSock=%d", newSock));
QCC_DbgPrintf(("WFDTransport::Run(): maxAuth == %d", maxAuth));
QCC_DbgPrintf(("WFDTransport::Run(): maxConn == %d", maxConn));
QCC_DbgPrintf(("WFDTransport::Run(): mAuthList.size() == %d", m_authList.size()));
QCC_DbgPrintf(("WFDTransport::Run(): mEndpointList.size() == %d", m_endpointList.size()));
assert(m_authList.size() + m_endpointList.size() <= maxConn);
/*
* Do we have a slot available for a new connection? If so, use
* it.
*/
m_endpointListLock.Lock(MUTEX_CONTEXT);
if ((m_authList.size() < maxAuth) && (m_authList.size() + m_endpointList.size() < maxConn)) {
static const bool truthiness = true;
WFDEndpoint conn(this, m_bus, truthiness, "", newSock, remoteAddr, remotePort,
m_bus.GetInternal().GetGlobalGUID().ToString());
conn->SetPassive();
Timespec tNow;
GetTimeNow(&tNow);
conn->SetStartTime(tNow);
/*
* By putting the connection on the m_authList, we are
* transferring responsibility for the connection to the
* Authentication thread. Therefore, we must check that the
* thread actually started running to ensure the handoff
* worked. If it didn't we need to deal with the connection
* here. Since there are no threads running we can just
* pitch the connection.
*/
std::pair<std::set<WFDEndpoint>::iterator, bool> ins = m_authList.insert(conn);
status = conn->Authenticate();
if (status != ER_OK) {
m_authList.erase(ins.first);
conn->Invalidate();
}
m_endpointListLock.Unlock(MUTEX_CONTEXT);
} else {
m_endpointListLock.Unlock(MUTEX_CONTEXT);
qcc::Shutdown(newSock);
qcc::Close(newSock);
status = ER_AUTH_FAIL;
QCC_LogError(status, ("WFDTransport::Run(): No slot for new connection"));
}
}
/*
* Accept returns ER_WOULDBLOCK when all of the incoming connections have been handled
*/
if (ER_WOULDBLOCK == status) {
status = ER_OK;
}
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Run(): Error accepting new connection. Ignoring..."));
}
}
/*
* We're going to loop back and create a new list of checkEvents that
* reflect the current state, so we need to delete the checkEvents we
* created on this iteration.
*/
for (vector<Event*>::iterator i = checkEvents.begin(); i != checkEvents.end(); ++i) {
if (*i != &stopEvent) {
delete *i;
}
}
/*
* If we're not stopping, we always check for queued requests to start
* and stop listening on address and port combinations (listen specs).
* We need to change the state of the sockets in one place (here) to
* ensure that we don't ever end up with Events that contain references
* to closed Sockets; and this is the one place were we can be assured
* we don't have those Events live.
*
* When we loop back to the top of the server accept loop, we will
* re-evaluate the list of listenFds and create new Events based on the
* current state of the list (after we remove or add anything here).
*
* We also take this opportunity to run the state machine that deals
* with whether or not to enable WFD listeners and the name service
* UDP listeners.
*/
RunListenMachine();
}
/*
* If we're stopping, it is our responsibility to clean up the list of FDs
* we are listening to. Since we've gotten a Stop() and are exiting the
* server loop, and FDs are added in the server loop, this is the place to
* get rid of them. We don't have to take the list lock since a Stop()
* request to the WFDTransport is required to lock out any new
* requests that may possibly touch the listen FDs list.
*/
m_listenFdsLock.Lock(MUTEX_CONTEXT);
for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) {
qcc::Shutdown(i->second);
qcc::Close(i->second);
}
m_listenFds.clear();
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
QCC_DbgPrintf(("WFDTransport::Run is exiting status=%s", QCC_StatusText(status)));
return (void*) status;
}
/*
* The purpose of this code is really to ensure that we don't have any listeners
* active on Android systems if we have no ongoing advertisements. This is to
* satisfy a requirement driven from the Android Compatibility Test Suite (CTS)
* which fails systems that have processes listening for WFD connections when
* the test is run.
*
* Listeners and advertisements are interrelated. In order to Advertise a
* service, the name service must have an endpoint to include in its
* advertisements; and there must be at least one listener running and ready to
* receive connections before telling the name service to advertise.
*
* Discovery requests do not require listeners be present per se before being
* forwarded to the name service. A discovery request will ulitmately lead to a
* bus-to-bus connection once a remote daemon has been discovered; but the local
* side will always start the connection. Sessions throw a bit of a monkey
* wrench in the works, though. Since a JoinSession request is sent to the
* (already connected) remote daemon and it decides what to do, we don't want to
* arbitrarily constrain the remote daemon by disallowing it to try and connect
* back to the local daemon. For this reason, we do require listeners to be
* present before discovery starts.
*
* So the goal is to not have active listeners in the system unless there are
* outstanding advertisements or discovery requests, but we cannot have
* outstanding advertisements or discovery requests until there are active
* listeners. Some care is obviously required here to accomplish this
* seemingly inconsistent behavior.
*
* We call the state of no outstanding advertisements and not outstanding
* discovery requests "Name Service Quiescent". In this case, the name service
* must be disabled so that it doesn't interact with the network and cause a CTS
* failure. As soon as a either a discovery request or an advertisement request
* is started, we need to enable the name service to recieve and send network
* packets, which will cause the daemon process to begin listening on the name
* service well-known UDP port.
*
* Before an advertisement or a discovery request can acutally be sent over the
* wire, we must start a listener which will receive connection requests, and
* we must provide the name service with endpoint information that it can include
* in its advertisement. So, from the name service and network perspective,
* listens must preceed advertisements.
*
* In order to accomplish the CTS requirements, however, advertisements must
* preceed listens. It turns out that this is how the high-level system wants
* to work. Essentually, the system calls StartListen at the beginning of time
* (when the daemon is first brought up) and it calls StopListen at the end of
* time (when the daemon is going down). Advertisements and discovery requests
* come and go in between as clients and services come up and go down.
*
* To deal with this time-inversion, we save a list of all listen requests, a
* list of all advertisement requests and a list of all discovery requests. At
* the beginning of time we get one or more StartListen calls and save the
* listen specs, but do not actually do the socket operations to start the
* corresponding socket-level listens. When the first advertisement or
* discovery request comes in from the higher-level code, we first start all of
* the saved listens and then enable the name service and ask it to start
* advertising or discovering as appropriate. Further advertisements and
* discovery requests are also saved, but the calls to the name service are
* passed through when it is not quiescent.
*
* We keep track of the disable advertisement and discovery calls as well. Each
* time an advertisement or discover operation is disabled, we remove the
* corresponding entry in the associated list. As soon as all advertisements
* and discovery operations are disabled, we disable the name service and remove
* our WFD listeners, and therefore remove all listeners from the system. Since
* we have a saved a list of listeners, they can be restarted if another
* advertisement or discovery request comes in.
*
* We need to do all of this in one place (here) to make it easy to keep the
* state of the transport (us) and the name service consistent. We are
* basically a state machine handling the following transitions:
*
* START_LISTEN_INSTANCE: An instance of a StartListen() has happened so we
* need to add the associated listen spec to our list of listeners and be
* ready for a subsequent advertisement. We expect these to happen at the
* beginning of time; but there is nothing preventing a StartListen after we
* start advertising. In this case we need to execute the start listen.
*
* STOP_LISTEN_INSTANCE: An instance of a StopListen() has happened so we need
* to remove the listen spec from our list of listeners. We expect these to
* happen at the end of time; but there is nothing preventing a StopListen
* at any other time. In this case we need to execute the stop listen and
* remove the specified listener immediately
*
* ENABLE_ADVERTISEMENT_INSTANCE: An instance of an EnableAdvertisement() has
* happened. If there are no other ongoing advertisements, we need to
* enable the stored listeners, pass the endpoint information down to the
* name servcie, enable the name service communication with the outside
* world if it is disabled and finally pass the advertisement down to the
* name service. If there are other ongoing advertisements we just pass
* down the new advertisement. It is an AllJoyn system programming error to
* start advertising before starting at least one listen.
*
* DISABLE_ADVERTISEMENT_INSTANCE: An instance of a DisableAdvertisement()
* call has happened. We always want to pass the corresponding Cancel down
* to the name service. If we decide that this is the last of our ongoing
* advertisements, we need to continue and disable the name service from
* talking to the outside world. For completeness, we remove endpoint
* information from the name service. Finally, we shut down our WFD
* transport listeners.
*
* ENABLE_DISCOVERY_INSTANCE: An instance of an EnableDiscovery() has
* happened. This is a fundamentally different request than an enable
* advertisement. We don't need any listeners to be present in order to do
* discovery, but the name service must be enabled so it can send and
* receive WHO-HAS packets. If the name service communications are
* disabled, we need to enable them. In any case we pass the request down
* to the name service.
*
* DISABLE_DISCOVERY_INSTANCE: An instance of a DisableDiscovery() call has
* happened. There is no corresponding disable call in the name service,
* but we do have to decide if we want to disable the name service to keep
* it from listening. We do so if this is the last discovery instance and
* there are no other advertisements.
*
* There are four member variables that reflect the state of the transport
* and name service with respect to this code:
*
* m_isListening: The list of listeners is reflected by currently listening
* sockets. We have network infrastructure in place to receive inbound
* connection requests.
*
* m_isNsEnabled: The name service is up and running and listening on its
* sockets for incoming requests.
*
* m_isAdvertising: The list of advertisements is reflected by current
* advertisements in the name service. if we are m_isAdvertising then
* m_isNsEnabled must be true.
*
* m_isDiscovering: The list of discovery requests has been sent to the name
* service. if we are m_isDiscovering then m_isNsEnabled must be true.
*/
void WFDTransport::RunListenMachine(void)
{
QCC_DbgTrace(("WFDTransport::RunListenMachine()"));
while (m_listenRequests.empty() == false) {
QCC_DbgPrintf(("WFDTransport::RunListenMachine(): Do request."));
/*
* Pull a request to do a listen request off of the queue of requests.
* These requests relate to starting and stopping discovery and
* advertisements; and also whether or not to listen for inbound
* connections.
*/
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
ListenRequest listenRequest = m_listenRequests.front();
m_listenRequests.pop();
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Do some consistency checks to make sure we're not confused about what
* is going on.
*
* First, if we are not listening, then we had better not think we're
* advertising or discovering. If we are not listening, then the name
* service must not be enabled and sending or responding to external
* daemons.
*/
if (m_isListening == false) {
assert(m_isAdvertising == false);
assert(m_isDiscovering == false);
assert(m_isNsEnabled == false);
}
/*
* If we think the name service is enabled, it had better think it is
* enabled. It must be enabled either because we are advertising or we
* are discovering. If we are advertising or discovering, then there
* must be listeners waiting for connections as a result of those
* advertisements or discovery requests. If there are listeners, then
* there must be a non-zero listenPort.
*/
if (m_isNsEnabled) {
assert(m_isAdvertising || m_isDiscovering);
assert(m_isListening);
assert(m_listenPort);
}
/*
* If we think we are advertising, we'd better have an entry in the
* advertisements list to make us advertise, and there must be listeners
* waiting for inbound connections as a result of those advertisements.
* If we are advertising the name service had better be enabled.
*/
if (m_isAdvertising) {
assert(!m_advertising.empty());
assert(m_isListening);
assert(m_listenPort);
assert(m_isNsEnabled);
}
/*
* If we are discovering, we'd better have an entry in the discovering
* list to make us discover, and there must be listeners waiting for
* inbound connections as a result of session operations driven by those
* discoveries. If we are discovering the name service had better be
* enabled.
*/
if (m_isDiscovering) {
assert(!m_discovering.empty());
assert(m_isListening);
assert(m_listenPort);
assert(m_isNsEnabled);
}
/*
* We're a WFD transport in the AllJoyn sense, so we also have to use
* Wi-Fi pre-association service discovery. This means we are going to
* have to use the P2P (layer two) name service, and if we find a
* service, we are going to have to use the P2P connection manager.
* Since we have an advertisement/discovery call that drove us here we
* know that the DBus interface they require must be ready. This is a
* convenient time to Acquire those singletons, since they must just
* be ready before either a discovery or advertisement operation is
* actually attempted. Since we drive that process from immediately
* below, we're good.
*/
switch (listenRequest.m_requestOp) {
case ENABLE_ADVERTISEMENT_INSTANCE:
case DISABLE_ADVERTISEMENT_INSTANCE:
case ENABLE_DISCOVERY_INSTANCE:
case DISABLE_DISCOVERY_INSTANCE:
if (m_p2pNsAcquired == false) {
P2PNameService::Instance().Acquire(&m_bus, m_bus.GetInternal().GetGlobalGUID().ToString());
P2PNameService::Instance().SetCallback(TRANSPORT_WFD, new CallbackImpl<WFDTransport, void, const qcc::String&, qcc::String&, uint8_t> (this, &WFDTransport::P2PNameServiceCallback));
m_p2pNsAcquired = true;
}
if (m_p2pCmAcquired == false) {
P2PConMan::Instance().Acquire(&m_bus, m_bus.GetInternal().GetGlobalGUID().ToString());
P2PConMan::Instance().SetStateCallback(new CallbackImpl<WFDTransport, void, P2PConMan::LinkState, const qcc::String&> (this, &WFDTransport::P2PConManStateCallback));
P2PConMan::Instance().SetNameCallback(new CallbackImpl<WFDTransport, void, const qcc::String&, const qcc::String&, std::vector<qcc::String>&, uint8_t>(this, &WFDTransport::P2PConManNameCallback));
m_p2pCmAcquired = true;
}
if (m_ipNsAcquired == false) {
IpNameService::Instance().Acquire(m_bus.GetInternal().GetGlobalGUID().ToString());
m_ipNsAcquired = true;
}
break;
default:
break;
}
/*
* Now that are sure we have a consistent view of the world, let's do
* what needs to be done.
*/
switch (listenRequest.m_requestOp) {
case START_LISTEN_INSTANCE:
StartListenInstance(listenRequest);
break;
case STOP_LISTEN_INSTANCE:
StopListenInstance(listenRequest);
break;
case ENABLE_ADVERTISEMENT_INSTANCE:
EnableAdvertisementInstance(listenRequest);
break;
case DISABLE_ADVERTISEMENT_INSTANCE:
DisableAdvertisementInstance(listenRequest);
break;
case ENABLE_DISCOVERY_INSTANCE:
EnableDiscoveryInstance(listenRequest);
break;
case DISABLE_DISCOVERY_INSTANCE:
DisableDiscoveryInstance(listenRequest);
break;
}
}
}
void WFDTransport::StartListenInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::StartListenInstance()"));
/*
* We have a new StartListen request, so save the listen spec so we
* can restart the listen if we stop advertising.
*/
NewListenOp(START_LISTEN, listenRequest.m_requestParam);
/*
* If we're running on Windows, we always start listening immediately
* since Windows uses WFD as the client to daemon communication link.
*
* On other operating systems (i.e. Posix) we use unix domain sockets and so
* we can delay listening to passify the Android Compatibility Test Suite.
* We do this unless we have any outstanding advertisements or discovery
* operations in which case we start up the listens immediately.
*/
if (m_isAdvertising || m_isDiscovering) {
DoStartListen(listenRequest.m_requestParam);
}
}
void WFDTransport::StopListenInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::StopListenInstance()"));
/*
* We have a new StopListen request, so we need to remove this
* particular listen spec from our lists so it will not be
* restarted.
*/
bool empty = NewListenOp(STOP_LISTEN, listenRequest.m_requestParam);
/*
* If we have just removed the last listener, we have a problem if
* we have active advertisements. This is because we will be
* advertising soon to be non-existent endpoints. The question is,
* what do we want to do about it. We could just ignore it since
* since clients receiving advertisements may just try to connect to
* a non-existent endpoint and fail. It does seem better to log an
* error and then cancel any outstanding advertisements since they
* are soon to be meaningless.
*/
if (empty && m_isAdvertising) {
QCC_LogError(ER_FAIL, ("WFDTransport::StopListenInstance(): No listeners with outstanding advertisements."));
for (list<qcc::String>::iterator i = m_advertising.begin(); i != m_advertising.end(); ++i) {
if (m_p2pNsAcquired) {
P2PNameService::Instance().CancelAdvertiseName(TRANSPORT_WFD, *i);
}
if (m_ipNsAcquired) {
IpNameService::Instance().CancelAdvertiseName(TRANSPORT_WFD, *i, TRANSPORT_WFD);
}
}
}
/*
* Execute the code that will actually tear down the specified
* listening endpoint. Note that we always stop listening
* immediately since that is Good (TM) from a power and CTS point of
* view. We only delay starting to listen.
*/
DoStopListen(listenRequest.m_requestParam);
}
void WFDTransport::EnableAdvertisementInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::EnableAdvertisementInstance()"));
/*
* We have a new advertisement request to deal with. The first
* order of business is to save the well-known name away for
* use later.
*/
bool isFirst;
NewAdvertiseOp(ENABLE_ADVERTISEMENT, listenRequest.m_requestParam, isFirst);
/*
* If it turned out that is the first advertisement on our list, we need to
* prepare before actually doing the advertisement.
*/
if (isFirst) {
/*
* If we don't have any listeners up and running, we need to get them
* up. If this is a Windows box, the listeners will start running
* immediately and will never go down, so they may already be running.
*/
if (!m_isListening) {
for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) {
DoStartListen(*i);
assert(m_listenPort);
m_isListening = true;
}
}
/*
* We can only enable the requested advertisement if there is something
* listening inbound connections on. Therefore, we should only enable
* the name service if there is a listener. This catches the case where
* there was no StartListen() done before the first advertisement.
*/
if (m_isListening) {
if (!m_isNsEnabled) {
/*
* We have to enable the P2P name service to get pre-association
* service discovery working, and we have to enable the IP name
* service to allow clients to discover our address and port
* information.
*/
P2PNameService::Instance().Enable(TRANSPORT_WFD);
std::map<qcc::String, uint16_t> listenPortMap;
listenPortMap["*"] = m_listenPort;
IpNameService::Instance().Enable(TRANSPORT_WFD, listenPortMap, 0, std::map<qcc::String, uint16_t>(), 0, true, false, false, false);
m_isNsEnabled = true;
}
} else {
QCC_LogError(ER_FAIL, ("WFDTransport::EnableAdvertisementInstance(): Advertise with no WFD listeners"));
return;
}
}
/*
* We think we're ready to send the advertisement. Are we really?
*/
assert(m_isListening);
assert(m_listenPort);
assert(m_isNsEnabled);
/*
* We're going to need the P2P name service and connection manager to make
* this happen, and we're going to need the IP name service to respond when
* the other side looks for an IP address and port, so they'd better be
* started and ready to go.
*/
assert(P2PNameService::Instance().Started() && "WFDTransport::EnableAdvertisementInstance(): P2PNameService not started");
assert(P2PConMan::Instance().Started() && "WFDTransport::EnableAdvertisementInstance(): P2PNameService not started");
assert(IpNameService::Instance().Started() && "WFDTransport::EnableAdvertisementInstance(): IpNameService not started");
/*
* If we're going to advertise a name, we must tell the underlying P2P
* system that we want to be a group owner (GO). The model we use is
* that services become GO and clients become station nodes (STA).
*
* There is no management of the underlying device in Android, and that
* is where we are going to be running. Basically, the last caller in
* gets to write over any previous callers.
*
* This means that if we have an existing client (STA) connection to another
* device, and the user decides to advertise a service, we will summarily
* kill the STA connection and prepare the device for incoming connections
* to the service as a GO.
*
* This means that if we are advertising/hosting a service and a client
* decides to connect to another device, we will summarily kill the GO
* connection and try to connect to the STA.
*
* To try and keep the user experience simple and understandable, we only
* allow one service to advertise over WFD at a time and we only allow one
* client to connect over WFD at a time.
*
* So, every time we advertise, we just take out anything else that may
* be there.
*/
qcc::String localDevice("");
QStatus status = P2PConMan::Instance().CreateTemporaryNetwork(localDevice, P2PConMan::DEVICE_SHOULD_BE_GO);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::EnableAdvertisementInstance(): Unable to create a GO side network"));
return;
}
/*
* We need to advertise the name over the IP name service because that is
* how the other side is going to determine addressing information for the
* ultimately desired TCP/UDP connection.
*
* When we start advertising here, there will be no temporary network
* actually created and therefore there is no network to send advertisements
* out over. We can't do anything with respect to opening an interface in
* the name service since we won't know the interface name until the link is
* actually established. We are just enabling the advertisements here.
*
* When a client eventually connects to the group, the connection manager
* will get an OnLinkEstablished signal from the P2P Helper service. This
* signal provides the interface name, and the signal is plumbed back to us
* via the callback from the P2PConMan. We do the call to open the name
* service interface in our callback handler. When this happens, the
* responses to FindAdvertiseName (who-has) requests will be answered and
* our advertisements will begin percolating out to the other (client) side.
*/
status = IpNameService::Instance().AdvertiseName(TRANSPORT_WFD, listenRequest.m_requestParam, false, TRANSPORT_WFD);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::EnableAdvertisementInstance(): Failed to advertise \"%s\"", listenRequest.m_requestParam.c_str()));
return;
}
/*
* We need to advertise the name over the P2P name service because that is
* the reason for being of this transport -- Wi-Fi Direct pre-association
* service discovery.
*/
status = P2PNameService::Instance().AdvertiseName(TRANSPORT_WFD, listenRequest.m_requestParam);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::EnableAdvertisementInstance(): Failed to advertise \"%s\"", listenRequest.m_requestParam.c_str()));
return;
}
QCC_DbgPrintf(("WFDTransport::EnableAdvertisementInstance(): Done"));
m_isAdvertising = true;
}
void WFDTransport::DisableAdvertisementInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::DisableAdvertisementInstance()"));
/*
* We have a new disable advertisement request to deal with. The first
* order of business is to remove the well-known name from our saved list.
*/
bool isFirst;
bool isEmpty = NewAdvertiseOp(DISABLE_ADVERTISEMENT, listenRequest.m_requestParam, isFirst);
QStatus status = IpNameService::Instance().CancelAdvertiseName(TRANSPORT_WFD, listenRequest.m_requestParam, TRANSPORT_WFD);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::DisableAdvertisementInstance(): Failed to IP Cancel \"%s\"", listenRequest.m_requestParam.c_str()));
}
status = P2PNameService::Instance().CancelAdvertiseName(TRANSPORT_WFD, listenRequest.m_requestParam);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::DisableAdvertisementInstance(): Failed to P2P Cancel \"%s\"", listenRequest.m_requestParam.c_str()));
}
/*
* If it turns out that this was the last advertisement on our list, we need
* to think about disabling our listeners and turning off the name service.
* We only to this if there are no discovery instances in progress.
*/
if (isEmpty && !m_isDiscovering) {
/*
* Since the cancel advertised name has been sent, we can disable the
* P2P name service. Telling the IP name service we don't have any
* enabled ports tells it to disable.
*/
P2PNameService::Instance().Disable(TRANSPORT_WFD);
std::map<qcc::String, uint16_t> listenPortMap;
listenPortMap["*"] = m_listenPort;
IpNameService::Instance().Enable(TRANSPORT_WFD, listenPortMap, 0, std::map<qcc::String, uint16_t>(), 0, false, false, false, false);
m_isNsEnabled = false;
/*
* If we had the name service running, we must have had listeners
* waiting for connections due to the name service. We need to stop
* them all now.
*/
for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) {
DoStopListen(*i);
}
m_isListening = false;
m_listenPort = 0;
QStatus status = P2PConMan::Instance().DestroyTemporaryNetwork();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::DisableAdvertisementInstance(): Unable to destroy GO side network"));
}
}
if (isEmpty) {
m_isAdvertising = false;
}
}
void WFDTransport::EnableDiscoveryInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::EnableDiscoveryInstance()"));
/*
* We have a new discovery request to deal with. The first
* order of business is to save the well-known name away for
* use later.
*/
bool isFirst;
NewDiscoveryOp(ENABLE_DISCOVERY, listenRequest.m_requestParam, isFirst);
/*
* If it turned out that is the first discovery request on our list, we need
* to prepare before actually doing the discovery.
*/
if (isFirst) {
/*
* If we don't have any listeners up and running, we need to get them
* up. If this is a Windows box, the listeners will start running
* immediately and will never go down, so they may already be running.
*/
if (!m_isListening) {
for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) {
DoStartListen(*i);
assert(m_listenPort);
m_isListening = true;
}
}
/*
* We can only enable the requested advertisement if there is something
* listening inbound connections on. Therefore, we should only enable
* the name service if there is a listener. This catches the case where
* there was no StartListen() done before the first discover.
*/
if (m_isListening) {
if (!m_isNsEnabled) {
P2PNameService::Instance().Enable(TRANSPORT_WFD);
m_isNsEnabled = true;
}
} else {
QCC_LogError(ER_FAIL, ("WFDTransport::EnableDiscoveryInstance(): Discover with no WFD listeners"));
return;
}
}
/*
* We think we're ready to send the FindAdvertisedName. Are we really?
*/
assert(m_isListening);
assert(m_listenPort);
assert(m_isNsEnabled);
assert(P2PNameService::Instance().Started() && "WFDTransport::EnableDiscoveryInstance(): P2PNameService not started");
qcc::String starred = listenRequest.m_requestParam;
// starred.append('*');
QStatus status = P2PNameService::Instance().FindAdvertisedName(TRANSPORT_WFD, starred);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::EnableDiscoveryInstance(): Failed to begin discovery on \"%s\"", starred.c_str()));
}
m_isDiscovering = true;
}
void WFDTransport::DisableDiscoveryInstance(ListenRequest& listenRequest)
{
QCC_DbgTrace(("WFDTransport::DisableDiscoveryInstance()"));
/*
* We have a new disable discovery request to deal with. The first
* order of business is to remove the well-known name from our saved list.
*/
bool isFirst;
bool isEmpty = NewDiscoveryOp(DISABLE_DISCOVERY, listenRequest.m_requestParam, isFirst);
qcc::String starred = listenRequest.m_requestParam;
// starred.append('*');
QStatus status = P2PNameService::Instance().CancelFindAdvertisedName(TRANSPORT_WFD, starred);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::DisableDiscoveryInstance(): Failed to end discovery on \"%s\"", starred.c_str()));
}
/*
* If it turns out that this was the last discovery operation on our list,
* we need to think about disabling our listeners and turning off the name
* service. We only to this if there are no advertisements in progress.
*/
if (isEmpty && !m_isAdvertising) {
/*
* We disable the P2P name service explicitly. Telling the IP name
* service that we have no enabled ports tells it to disable.
*/
P2PNameService::Instance().Disable(TRANSPORT_WFD);
std::map<qcc::String, uint16_t> listenPortMap;
listenPortMap["*"] = m_listenPort;
IpNameService::Instance().Enable(TRANSPORT_WFD, listenPortMap, 0, std::map<qcc::String, uint16_t>(), 0, false, false, false, false);
m_isNsEnabled = false;
/*
* If we had the name service running, we must have had listeners
* waiting for connections due to the name service. We need to stop
* them all now.
*/
for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) {
DoStopListen(*i);
}
m_isListening = false;
m_listenPort = 0;
}
if (isEmpty) {
m_isDiscovering = false;
}
}
/*
* The default address for use in listen specs. INADDR_ANY means to listen
* for WFD connections on any interfaces that are currently up or any that may
* come up in the future.
*/
static const char* ADDR4_DEFAULT = "0.0.0.0";
/*
* The default port for use in listen specs. This port is used by the WFD
* listener to listen for incoming connection requests. This is the default
* port for a "reliable" IPv4 listener since being able to deal with IPv4
* connection requests is required as part of the definition of the WFD
* transport.
*
* All other mechanisms (unreliable IPv4, reliable IPv6, unreliable IPv6)
* rely on the presence of an u4port, r6port, and u6port respectively to
* enable those mechanisms if possible.
*/
static const uint16_t PORT_DEFAULT = 9956;
QStatus WFDTransport::NormalizeListenSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap) const
{
QCC_DbgTrace(("WFDTransport::NormalizeListenSpec()"));
qcc::String family;
/*
* We don't make any calls that require us to be in any particular state
* with respect to threading so we don't bother to call IsRunning() here.
*
* Take the string in inSpec, which must start with "wfd:" and parse it,
* looking for comma-separated "key=value" pairs and initialize the
* argMap with those pairs.
*
* There are lots of legal possibilities for an IP-based transport, but
* all we are going to recognize is the "reliable IPv4 mechanism" and
* so we will summarily pitch everything else.
*
* We expect to end up with a normalized outSpec that looks something
* like:
*
* "wfd:r4addr=0.0.0.0,r4port=9955"
*
* That's all. We still allow "addr=0.0.0.0,port=9955,family=ipv4" but
* since the only thing that was ever allowed was really reliable IPv4, we
* treat addr as synonomous with r4addr, port as synonomous with r4port and
* ignore family. The old stuff is normalized to the above.
*
* In the future we may want to revisit this and use position/order of keys
* to imply more information. For example:
*
* "wfd:addr=0.0.0.0,port=9955,family=ipv4,reliable=true,
* addr=0.0.0.0,port=9956,family=ipv4,reliable=false;"
*
* might translate into:
*
* "wfd:r4addr=0.0.0.0,r4port=9955,u4addr=0.0.0.0,u4port=9956;"
*
* Note the new significance of position.
*/
QStatus status = ParseArguments(GetTransportName(), inSpec, argMap);
if (status != ER_OK) {
return status;
}
map<qcc::String, qcc::String>::iterator iter;
/*
* We just ignore the family since ipv4 was the only possibld working choice.
*/
iter = argMap.find("family");
if (iter != argMap.end()) {
argMap.erase(iter);
}
/*
* Transports, by definition, may support reliable Ipv4, unreliable IPv4,
* reliable IPv6 and unreliable IPv6 mechanisms to move bits. In this
* incarnation, the WFD transport will only support reliable IPv4; so we
* log errors and ignore any requests for other mechanisms.
*/
iter = argMap.find("u4addr");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"u4addr\" is not supported."));
argMap.erase(iter);
}
iter = argMap.find("u4port");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"u4port\" is not supported."));
argMap.erase(iter);
}
iter = argMap.find("r6addr");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"r6addr\" is not supported."));
argMap.erase(iter);
}
iter = argMap.find("r6port");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"r6port\" is not supported."));
argMap.erase(iter);
}
iter = argMap.find("u6addr");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"u6addr\" is not supported."));
argMap.erase(iter);
}
iter = argMap.find("u6port");
if (iter != argMap.end()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The mechanism implied by \"u6port\" is not supported."));
argMap.erase(iter);
}
/*
* Now, begin normalizing what we want to see in a listen spec.
*
* All listen specs must start with the name of the transport followed by
* a colon.
*/
outSpec = GetTransportName() + qcc::String(":");
/*
* The WFD transport must absolutely support the IPv4 "reliable" mechanism
* (WFD). We therefore must provide an r4addr either from explicit keys or
* generated from the defaults.
*/
iter = argMap.find("r4addr");
if (iter == argMap.end()) {
/*
* We have no value associated with an "r4addr" key. Do we have an
* "addr" which would be synonymous? If so, save it as an r4addr,
* erase it and point back to the new r4addr.
*/
iter = argMap.find("addr");
if (iter != argMap.end()) {
argMap["r4addr"] = iter->second;
argMap.erase(iter);
}
iter = argMap.find("r4addr");
}
/*
* Now, deal with the r4addr, possibly replaced by addr.
*/
if (iter != argMap.end()) {
/*
* We have a value associated with the "r4addr" key. Run it through a
* conversion function to make sure it's a valid value and to get into
* in a standard representation.
*/
IPAddress addr;
status = addr.SetAddress(iter->second, false);
if (status == ER_OK) {
/*
* The r4addr had better be an IPv4 address, otherwise we bail.
*/
if (!addr.IsIPv4()) {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The r4addr \"%s\" is not a legal IPv4 address.",
iter->second.c_str()));
return ER_BUS_BAD_TRANSPORT_ARGS;
}
iter->second = addr.ToString();
outSpec.append("r4addr=" + addr.ToString());
} else {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The r4addr \"%s\" is not a legal IPv4 address.",
iter->second.c_str()));
return ER_BUS_BAD_TRANSPORT_ARGS;
}
} else {
/*
* We have no value associated with an "r4addr" key. Use the default
* IPv4 listen address for the outspec and create a new key for the
* map.
*/
outSpec.append("r4addr=" + qcc::String(ADDR4_DEFAULT));
argMap["r4addr"] = ADDR4_DEFAULT;
}
/*
* The WFD transport must absolutely support the IPv4 "reliable" mechanism
* (WFD). We therefore must provide an r4port either from explicit keys or
* generated from the defaults.
*/
iter = argMap.find("r4port");
if (iter == argMap.end()) {
/*
* We have no value associated with an "r4port" key. Do we have a
* "port" which would be synonymous? If so, save it as an r4port,
* erase it and point back to the new r4port.
*/
iter = argMap.find("port");
if (iter != argMap.end()) {
argMap["r4port"] = iter->second;
argMap.erase(iter);
}
iter = argMap.find("r4port");
}
/*
* Now, deal with the r4port, possibly replaced by port.
*/
if (iter != argMap.end()) {
/*
* We have a value associated with the "r4port" key. Run it through a
* conversion function to make sure it's a valid value. We put it into
* a 32 bit int to make sure it will actually fit into a 16-bit port
* number.
*/
uint32_t port = StringToU32(iter->second);
if (port <= 0xffff) {
outSpec.append(",r4port=" + iter->second);
} else {
QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS,
("WFDTransport::NormalizeListenSpec(): The key \"r4port\" has a bad value \"%s\".", iter->second.c_str()));
return ER_BUS_BAD_TRANSPORT_ARGS;
}
} else {
/*
* We have no value associated with an "r4port" key. Use the default
* IPv4 listen port for the outspec and create a new key for the map.
*/
qcc::String portString = U32ToString(PORT_DEFAULT);
outSpec += ",r4port=" + portString;
argMap["r4port"] = portString;
}
return ER_OK;
}
QStatus WFDTransport::NormalizeTransportSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap) const
{
QCC_DbgTrace(("WFDTransport::NormalizeTransportSpec()"));
/*
* Wi-Fi Direct pre-association service discovery events are fundamentally
* layer two events that happen before networks are formed. Since there
* is no network, there is no DHCP or DHCP equivalent, so there cannot
* be an IP address passed in as part of a connect/transport spec. In
* order to identify a remote daemon to connect to, we use the daemon's
* GUID. If we find anything else, we have run across a "spec" that
* is not resulting from a Wi-Fi Direct service discovery event. We
* reject anything but one of ours.
*
* It might not look like we're doing much, but we are ensuring a consistent
* internal format WRT white space, etc.
*/
QStatus status = ParseArguments(GetTransportName(), inSpec, argMap);
if (status != ER_OK) {
return status;
}
map<qcc::String, qcc::String>::iterator iter = argMap.find("guid");
if (iter != argMap.end()) {
QCC_DbgPrintf(("WFDTransport::NormalizeTransportSpec(): Found guid"));
qcc::String guidString = iter->second;
argMap.clear();
argMap["guid"] = guidString;
outSpec = qcc::String(GetTransportName()) + qcc::String(":guid=") + guidString;
return ER_OK;
}
return ER_BUS_BAD_TRANSPORT_ARGS;
}
QStatus WFDTransport::Connect(const char* connectSpec, const SessionOpts& opts, BusEndpoint& newep)
{
QCC_DbgTrace(("WFDTransport::Connect(): %s", connectSpec));
QStatus status;
bool isConnected = false;
/*
* Clear the new endpoint pointer so we don't have to do it over and over
* again in case of the various errors.
*/
if (newep->IsValid()) {
newep->Invalidate();
}
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::Connect(): Not running or stopping; exiting"));
return ER_BUS_TRANSPORT_NOT_STARTED;
}
/*
* If we pass the IsRunning() gate above, we must have a server accept
* thread spinning up or shutting down but not yet joined. Since the name
* service is started before the server accept thread is spun up, and
* deleted after it is joined, we must have a started name service or someone
* isn't playing by the rules; so an assert is appropriate here.
*/
assert(P2PNameService::Instance().Started() && "WFDTransport::Connect(): P2PNameService not started");
/*
* There are two possibilities for the form of the connect spec we have just
* normalized. The first is that it contains a key of "guid" (the connect
* spec looks something like "wfd:guid=2b1188267ee74bc9a910b69435779523")
* and the second is that it contains IP addressing information as
* exemplified by the keys "r4addr" and "r4port" (the connect spec would
* look something like "wfd:r4addr=192.168.1.100,r4port=9956")
*
* If the "guid" key is present it indicates that the underlying discovery
* event happened over Wi-Fi P2P pre-association service discovery. Since
* this is a fundamentally layer two process, there is no IP addressing
* information present before this method is called. The connection between
* the GUID and the layer two (MAC) device address is kept in the P2P name
* service and is available to us.
*
* If we found a guid, then we need to actually go and discover the IP
* address info using our layer three name service, AKA the IP name service.
* We expect that there will always be a precipitating layer two (P2P)
* discovery event that drives a JoinSession() which, in turn, causes the
* WFDTransport::Connect() that brings us here. This first event will tell
* us to bring up an initial Wi-Fi connection. After that initial
* connection is brought up, the IP name service is always run over the
* resulting link and we may therefore see layer three discovery events.
*
* If the "r4addr", "u4addr", "r6addr", or "u6addr" keys are present in the
* connect spec it indicates that the JoinSession() driving this Connect()
* happened due to a layer three (IP) discovery event. In this case, we
* do not have to bring up an initial connection and we can proceed directly
* to the actual connect part of the method.
*
* We have two methods to parse the different kinds of connect specs. The
* NormalizeTransportSpec() method determines whether the connect spec
* contains a GUID and if it does, puts it into a standard form and returns
* ER_OK.
*
* The variable preAssociationEvent tells us what kind of discovery event
* caused the Connect() we are running: either a Wi-Fi Direct pre-
* association service discovery event (true) or an IP name service event
* (false).
*/
bool preAssociationEvent = false;
qcc::String guid;
qcc::String device;
qcc::String normSpec;
map<qcc::String, qcc::String> argMap;
status = NormalizeTransportSpec(connectSpec, normSpec, argMap);
if (status == ER_OK) {
QCC_DbgPrintf(("WFDTransport::Connect(): Found GUID. Normalized connect spec is \"%s\"", normSpec.c_str()));
/*
* Since we found a GUID in the connect spec, we know we have no layer
* three addressing information, so we are going to have to discover it
* before we can do an actual TCP connect to the destination daemon. We
* may also need an actual physical network to move the bits over.
* Neither of these things may exist yet.
*/
preAssociationEvent = true;
map<qcc::String, qcc::String>::iterator iter = argMap.find("guid");
assert(iter != argMap.end() && "WFDTransport::Connect(): Transport spec must provide \"guid\"");
guid = iter->second;
/*
* Since we are doing a Connect() we must want to take on the role of a
* P2P STA. A STA can only be connected to one P2P group at a time. A
* P2P group has an owner, which we assume to be a remote AllJoyn daemon
* hosting the service, the advertisement for which got us here in the
* first place. When we got the advertisement, we mapped the discovered
* GUID to the MAC address of the device that did the advertisement.
*
* The first thing we need to do in this process is to find the MAC
* address of the device to which we want to be talking. There is no
* guarantee that this device has not been lost during the time it took
* for the application to get around to asking us to connect, so we
* return an error if we can no longer find it.
*/
status = P2PNameService::Instance().GetDeviceForGuid(guid, device);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Device corresponding to GUID \"%s\" is gone", guid.c_str()));
return status;
}
/*
* Unfortunately, this is all fiendishly complicated, so it will be
* worth your time to read this long comment before you shoot yourself
* in the foot by making an "obviously correct" change.
*
* The major restriction when using the Wi-Fi Direct transport is that a
* device can be a GO (advertise a service) or a STA (connect to a
* service) it cannot be both. There is a fundamental impedance
* mismatch between this requirement of the underlying implementation
* and the AllJoyn requirement that pure peer-to-peer applications be
* supported. A pure peer-to-peer application is one that is equipotent
* with other peers and therefore has both a client (STA) and a service
* (GO) "personality." In order to make the WFD Transport as useful as
* possible, we want to maximize the conditions under which we can do
* something despite this fundamental mismatch.
*
* Unfortunately, sorting out what happens and what we need to do means
* understanding the system down to the lowest levels. Note that none
* of this will happen in the client-server (AKA hybrid peer-to-peer)
* case which is why I like that so much, but such are the vicissitudes
* of anthromorphic behavior. The end result is something that is very
* constrained and not very abstract, but we are ordered to come up with
* something that will work at least a little in the pure peer-to-peer
* case.
*
* So, we want to appear to higher levels as if we are both client/STA
* and service/GO even though this is impossible. As you might expect,
* this gets a little dicey.
*
* Starting with a pair for simplicity, what happens if we have two pure
* peer-to-peer apps starting up. Typically, both applications will
* first start up and advertise their service personalities. By
* advertising, they are saying that they want to be services which
* implies group owner (GO). We will do a CreateTemporaryNetwork() and
* enter the CONN_READY state which means we are a service ready to
* accept inbound TCP connections and want to be the GO in a Wi-Fi
* Direct group. This advetisement and readiness to accept connections
* will happen on both applications.
*
* Eventually one or both of the apps will receive an advertisement and
* try to connect to the other. By attempting a connection, an app is
* announcing its intention to become a client. In order to support the
* peer-to-peer scenario, we need to allow this; but we can only allow
* this if the service side is not currently connected, or the
* contemplated connection attempt will destroy the existing group in
* favor of a new STA connection to a different GO. Consider the case
* where the local P2P device is currently not connected and imagine
* what happens when we try to connect to a remote device. First, since
* we are taking on the role of a client/STA, our advertisements will be
* immediately silenced by the Android Framework/P2P Helper since a STA
* cannot accept inbound connections and therefore advertising a service
* over P2P makes no sense. We are also a service, however, and we want
* the remote side to be able to discover us and connect to us even
* though we are a P2P STA.
*
* If the daemon to which we are connecting (the remote daemon from this
* perspective) is still in the CONN_READY server state (it has not
* discovered us yet) it will accept the connection and become the GO.
* It will be allowed to continue advertising since it is still a
* service/GO. We will become the STA and our P2P advertisements will
* be silenced, however, since we have a Wi-Fi link to the daemon the IP
* name service can run irrespective of whether or not the underlying
* Wi-Fi device is STA or GO and so the remote client personality can
* discover our local service personality over IP multicast instead of
* P2P, which is now forbidden.
*
* Because of the magic of distributed systems, there may be a P2P
* advertisement making its way through the remote client even though
* our P2P. So, the remote daemon client personality can discover our
* local service either due to an outstanding pre-association service
* discovery event or through the IP name service once the link is
* actually established. If the discovery is through the IP name
* service, the connection will include IP addressing information and we
* will bypass the whole P2P system, so we don't have to worry about
* that right here, right now.
*
* If, however, the discovery event on the remote side was though P2P, a
* Connect() will be made on that remote side with a GUID which maps to
* the device/MAC address our local P2P device -- it will try to connect
* to us. However, since the remote daemon is a group owner, it doesn't know the
* MAC address of every device connected to it and so it actually already
* be connected to the specified remote device implied by the GUID even
* though it doesn't know it. We have to special case this event and
* try to let the IP name service resolve the GUID since we don't want to
* fail if we can possibly succeed. This actually corresponds to case three
* below (connected && !ourGroupOwner).
*
* A degenerate case happens when the connections overlap, i.e., both
* devices in the pair discover and try to connect at the same time. In
* this case, both sides will turn into clients from an AllJoyn
* perspective and try to form a Wi-Fi P2P group. Both sides will
* select the GO intent of zero (want to be a client) and so Wi-Fi P2P
* will go to the GO negotiation tie-breaker process. One of the
* "clients" will be selected as the GO and so network authentication
* will be performed on a randomly chosedn device. In this case, one of
* the client personalities is actually selected to be a GO and it is
* not notified of this fact. Even though one of the devices has been
* chosen to be GO by the underlying system, both have tried to
* Connect() and so both devices will have chosen to be a client. This
* means that both discovery and advertisement will be disabled on both
* devices. The devices will become an "island of discovery" which can
* never be expanded except in a further degeneracy.
*
* When a third device enters into the mix, what happens depends on
* how the first two devices actually ended up connecting. If both of
* the original pair ended up doing a Connect() their advertisements
* were silenced. If the thrid devices enters proximity after that
* time, it will not discover either of the previous two devices and
* the new device will never see the original devices.
*
* If the first two devices connected in such a way that one of them
* remained the service/GO (this requires that the second connect
* happened driven by an IP name service discovery event) The service/GO
* will still be advertising and the third device may discover the
* advertising service of the original pair over P2P. However, neither
* of the original pair will be able to see the third device.
*
* If the third device sees the advertisement for the remaining
* service/GO it may connect. Once connected, the IP name service will
* run and discover the remaining service, and as above, the two client
* personalities of the original pair will discover the service
* personality of the third device. Thus there is a temporary
* non-reflexive advertisement sitution that is only resolved when the
* third device connects. There may be transient advertisements
* floating around from the device that became the STA in the
* relationship between the two original devices. If the third device
* receives one of those and tries to connect to the STA it will fail.
* The interesting fact here is that since the service on the device was
* discovered, it will not be re-discovered by the client since a
* subsequent discovery event over the IP name service will be masked
* since it will look to the daemon as if it is the same service over
* the same transport (the WFD transport). In this case, the
* non-reflexive advertisement situation may remain indefinitely or
* until the third device cancels its find advertised name and restarts
* it.
*
* So, the following code may seem unusually complex for what it seems
* to be doing. What it is actually doing is trying to make a square
* peg fit in a round hole, so beware of making changes without thinking
* them through. It may cost you a toe or two.
*/
bool connected = P2PConMan::Instance().IsConnected();
bool ourGroupOwner = P2PConMan::Instance().IsConnected(device);
QCC_DbgPrintf(("WFDTransport::Connect(): Device \"%s\" corresponds to GUID \"%s\"", device.c_str(), guid.c_str()));
/*
* case 1: !connected && !ourGroupOwner: completely disconnected.
* case 2: !connected && ourGroupOwner: disconnected but connected to the desired group owner is impossible
* case 3: connected && !ourGroupOwner: already connected but to a different group owner
* case 4: connected && ourGroupOwner: already connected to the desired group owner
*/
if (!connected && ourGroupOwner) {
/*
* First, handle case two, disconnected but connected to the desired
* group owner is impossible. This is impossible, so we assert that
* it did not happen.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Connection case two"));
assert(false && "WFDTransport::Connect(): Impossible condition.");
} else if (connected && !ourGroupOwner) {
/*
* Handle case three, already connected but to a different group
* owner.
*
* There is an interesting degenerate case that we need to deal with
* in the pure peer-to-peer case -- that is, if we are both a client
* and a service and a remote daemon is both a client and a service.
* If we have advertised a service and some remote application's
* client personality has connected to us, we will be in the
* connected state but the device to which we are connected is the
* null string. This is because we are the GO and are not connected
* to a remote device (MAC) address. If we also have a client
* personality, we may have received a P2P pre-association service
* discovery notification prior to the remote daemon being silenced
* (see the long comment in case one below for details). If this
* happens, we may actually have a connection to the advertising
* daemon, we just don't know it. We don't want to arbitrarily fail
* the Connect() in this case, we want to try to see if we can
* resolve the GUID using the IP name service in case we can
* actually reach the daemon.
*
* So, as part of case three, we look to see if we are connected to
* a remote device with a null-string MAC address. If we are, we
* are a service attempting a connection to a remote GUID we have
* heard about through a valid pre-association advertisement (recall
* that GetDeviceForGuid(guid, device) worked above or we wouldn't
* be here). In this case, we just fall through to the IP name
* service resolution process.
*
* If we are connected to a remote daemon via a valid MAC/device
* address, we are trying to make a second STA connection and this
* is not supported. We require an explicit disconnect before we
* allow this; and so this is an error.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Connection case three"));
qcc::String localDevice("");
if (P2PConMan::Instance().IsConnected(localDevice) == false) {
QCC_LogError(ER_P2P_FORBIDDEN, ("WFDTransport::Connect(): Second STA connection forbidden"));
return ER_P2P_FORBIDDEN;
}
} else if (connected && ourGroupOwner) {
/*
* Handle case four, already connected to the desired group owner.
* This means we are done since we are already connected to the
* device we want to be connected to.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Connection case four. Already connected to device \"%s\"", device.c_str()));
} else {
/*
* Handle case one, completely disconnected.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Connection case one. Not connected to device \"%s\"", device.c_str()));
assert(!connected && !ourGroupOwner && "WFDTransport::Connect(): Impossible.");
/*
* As mentioned in the extended comment above, we may be completely
* disconnected, but we may have an outstanding advertisement. If
* this is the case, we are trying to be both a service and a
* client. When we advertised, we did a CreateTemporaryNetwork()
* which put the P2P connection manager into a state where it
* expected to be a GO. If we are going to try and do a Connect()
* here, and rely on the IP name service to pick up the slack and
* advertise our service, we are going to have to undo that
* temporary network creation and put our connection manager into
* the idle state so it can deal the request to connect as a STA
* which will follow. We've already done all of the tests to ensure
* that this will be done with as few problems as possible, so we
* just go for it.
*
* It will be the case that after we do this DestroyTemporaryNetwork()
* we will not be able to accept any new connections for the services
* we might have advertised. So while we are off trying to connect to
* another link, anyone who might connect to us will fail.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): DestroyTemporaryNetwork()"));
QStatus status = P2PConMan::Instance().DestroyTemporaryNetwork();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Unable to destroy temporary network"));
return status;
}
/*
* If we are not connected onto a common physical network with the
* device the first order of business is to make that happen. Creating
* a temporary network means bringing up the entire infrastructure of
* the network, so this may also be a very time-consuming call during
* which time we will block. Since human intervention may actually be
* required on the remote side for Wi-Fi authentication, we may be
* talking on the order of a couple of minutes here if things happen in
* the worst case.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): CreateTemporaryNetwork() with device \"%s\"", device.c_str()));
status = P2PConMan::Instance().CreateTemporaryNetwork(device, P2PConMan::DEVICE_SHOULD_BE_STA);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Unable to CreateTemporaryNetwork() with device \"%s\"", device.c_str()));
/*
* Okay, we've tried to connect as a STA and failed. It could
* be the case that we were a service and in the ready state
* (ready to accept new inbound connections) but we are hosting
* a pure peer-to-peer app that wants to be both a client and a
* service. If we still want to be a service, we need to return
* to the ready state and not just forget about the whole service
* thing.
*/
if (m_isAdvertising) {
qcc::String localDevice("");
QStatus status = P2PConMan::Instance().CreateTemporaryNetwork(localDevice, P2PConMan::DEVICE_SHOULD_BE_GO);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Unable to return to SHOULD_BE_GO"));
}
}
}
}
}
/*
* At this point, we are coming from one of three directions.
*
* It could be the case that we have just formed a new connection based on a
* provided GUID in the correctly parsed and normalized transport spec.
* This case indicates that the discovery event that precipitated the
* Connect() is a Wi-Fi P2P pre-association service discovery event. If we
* find ourselves in that state, we have no layer three (IP) addressing
* information, and we must discover it before we can proceed.
*
* It could be the case that we have a GUID in a correctly parsed and
* normalized transport spec that refers to a pre-existing connection. In
* that case, we expect that we will have already found IP addressing
* information for the specified device. We don't remember that address
* information so this case folds into the previous one. XXX Should we?
*
* It could also be the case that the underlying discovery event was from
* the IP name service, In that case we expect to have a pre-existing
* temporary network and we do have layer three addressing information.
* The IP address may or may not refer to the group owner since the IP
* name service is a multicast protocol running on all of the nodes in the
* group. This is how we can discover and connect to other services
* advertising as Wi-Fi Direct services even though basic WFD discovery
* is broken/crippled in Android as of Jellybean.
*
* The next goal is to get a connect spec (spec) with IP addressing in it.
* If the variable preAssociationEvent is true, it means one of the first
* two cases above, and if it is false, it means the third.
*/
qcc::String spec;
if (!preAssociationEvent) {
qcc::String spec = connectSpec;
QCC_DbgPrintf(("WFDTransport::Connect(): Provided connect spec is \"%s\"", spec.c_str()));
} else {
/*
* Since preAssociationEvent is true, we know we have a GUID from the
* original connect spec passed to us. We also have looked up the
* device corresponding to that GUID.
*
* The ultimate goal now is to essentially create the same connect spec
* that would have been passed to a TCPTransport::Connect() if the
* network formation had just happened magically. We are essentially
* translating a spec like "wfd:guid=2b1188267ee74bc9a910b69435779523"
* into a one like "wfd:r4addr=192.168.1.100,r4port=9956". Note that
* this is exactly the same form as we would see in the third case
* above -- one that came directly from the IP name service.
*
* This is going to result in IP name service exchanges and may also
* therefore take a long time to complete. If the other side misses the
* original who-has requests, it could take some multiple of 40 seconds
* for the IP addresses to be found.
*/
qcc::String newSpec;
QCC_DbgPrintf(("WFDTransport::Connect(): CreateConnectSpec()"));
status = P2PConMan::Instance().CreateConnectSpec(device, guid, newSpec);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Unable to CreateConnectSpec() with device \"%s\"", device.c_str()));
return status;
}
/*
* The newSpec is coming almost directly from the IP name service. The
* name service will not know to prepend the spec with "wfd:" since it
* is used across multiple transports, but we need it now.
*/
spec = qcc::String("wfd:") + newSpec;
QCC_DbgPrintf(("WFDTransport::Connect(): CreateConnectSpec() says connect spec is \"%s\"", spec.c_str()));
}
/*
* We have now folded all of the different cases down into one. We have a
* connect spec just like any other connect spec with layer three (IP)
* address information in it. Just like any other spec, we need to make
* sure it is normalized since it is coming from the "outside world."
*/
status = NormalizeListenSpec(spec.c_str(), normSpec, argMap);
if (ER_OK != status) {
QCC_LogError(status, ("WFDTransport::Connect(): Invalid connect spec \"%s\"", spec.c_str()));
return status;
}
QCC_DbgPrintf(("WFDTransport::Connect(): Final normalized connect spec is \"%s\"", normSpec.c_str()));
/*
* From this point on, the Wi-Fi Direct transport connect looks just like
* the TCP transport connect.
*
* The fields r4addr and r4port are guaranteed to be present now (since we
* successfully ran the spec through NormalizeListenSpec() to check for
* just that).
*/
IPAddress ipAddr(argMap.find("r4addr")->second);
uint16_t port = StringToU32(argMap["r4port"]);
/*
* The semantics of the Connect method tell us that we want to connect to a
* remote daemon. TCP will happily allow us to connect to ourselves, but
* this is not always possible in the various transports AllJoyn may use.
* To avoid unnecessary differences, we do not allow a requested connection
* to "ourself" to succeed.
*
* The code here is not a failsafe way to prevent this since thre are going
* to be multiple processes involved that have no knowledge of what the
* other is doing (for example, the wireless supplicant and this daemon).
* This means we can't synchronize and there will be race conditions that
* can cause the tests for selfness to fail. The final check is made in the
* bus hello protocol, which will abort the connection if it detects it is
* conected to itself. We just attempt to short circuit the process where
* we can and not allow connections to proceed that will be bound to fail.
*
* One defintion of a connection to ourself is if we find that a listener
* has has been started via a call to our own StartListener() with the same
* connectSpec as we have now. This is the simple case, but it also turns
* out to be the uncommon case.
*
* It is perfectly legal to start a listener using the INADDR_ANY address,
* which tells the system to listen for connections on any network interface
* that happens to be up or that may come up in the future. This is the
* default listen address and is the most common case. If this option has
* been used, we expect to find a listener with a normalized adresss that
* looks like "r4addr=0.0.0.0,port=y". If we detect this kind of connectSpec
* we have to look at the currently up interfaces and see if any of them
* match the address provided in the connectSpec. If so, we are attempting
* to connect to ourself and we must fail that request.
*/
char anyspec[64];
snprintf(anyspec, sizeof(anyspec), "%s:r4addr=0.0.0.0,r4port=%u", GetTransportName(), port);
qcc::String normAnySpec;
map<qcc::String, qcc::String> normArgMap;
status = NormalizeListenSpec(anyspec, normAnySpec, normArgMap);
if (ER_OK != status) {
QCC_LogError(status, ("WFDTransport::Connect(): Invalid INADDR_ANY connect spec"));
return status;
}
/*
* Look to see if we are already listening on the provided connectSpec
* either explicitly or via the INADDR_ANY address.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Checking for connection to self"));
m_listenFdsLock.Lock(MUTEX_CONTEXT);
bool anyEncountered = false;
for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) {
QCC_DbgPrintf(("WFDTransport::Connect(): Checking listenSpec %s", i->first.c_str()));
/*
* If the provided connectSpec is already explicitly listened to, it is
* an error. We expect to never see INADDR_ANY in a normSpec.
*/
if (i->first == normSpec) {
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
QCC_DbgPrintf(("WFDTransport::Connect(): Explicit connection to self"));
return ER_BUS_ALREADY_LISTENING;
}
/*
* If we are listening to INADDR_ANY and the supplied port, then we have
* to look to the currently UP interfaces to decide if this call is bogus
* or not. Set a flag to remind us.
*/
if (i->first == normAnySpec) {
QCC_DbgPrintf(("WFDTransport::Connect(): Possible implicit connection to self detected"));
anyEncountered = true;
}
}
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
/*
* If we are listening to INADDR_ANY, we are going to have to see if any
* currently UP interfaces have an address that matches the connectSpec
* addr.
*/
if (anyEncountered) {
QCC_DbgPrintf(("WFDTransport::Connect(): Checking for implicit connection to self"));
std::vector<qcc::IfConfigEntry> entries;
QStatus status = qcc::IfConfig(entries);
/*
* Only do the check for self-ness if we can get interfaces to check.
* This is a non-fatal error since we know that there is an end-to-end
* check happening in the bus hello exchange, so if there is a problem
* it will simply be detected later.
*/
if (status == ER_OK) {
/*
* Loop through the network interface entries looking for an UP
* interface that has the same IP address as the one we're trying to
* connect to. We know any match on the address will be a hit since
* we matched the port during the listener check above. Since we
* have a listener listening on *any* UP interface on the specified
* port, a match on the interface address with the connect address
* is a hit.
*/
for (uint32_t i = 0; i < entries.size(); ++i) {
QCC_DbgPrintf(("WFDTransport::Connect(): Checking interface %s", entries[i].m_name.c_str()));
if (entries[i].m_flags & qcc::IfConfigEntry::UP) {
QCC_DbgPrintf(("WFDTransport::Connect(): Interface UP with addresss %s", entries[i].m_addr.c_str()));
IPAddress foundAddr(entries[i].m_addr);
if (foundAddr == ipAddr) {
QCC_DbgPrintf(("WFDTransport::Connect(): Attempted connection to self; exiting"));
return ER_BUS_ALREADY_LISTENING;
}
}
}
}
}
/*
* This is a new not previously satisfied connection request, so attempt
* to connect to the remote WFD address and port specified in the connectSpec.
*/
SocketFd sockFd = qcc::INVALID_SOCKET_FD;
status = Socket(QCC_AF_INET, QCC_SOCK_STREAM, sockFd);
if (status == ER_OK) {
/* Turn off Nagle */
status = SetNagle(sockFd, false);
}
if (status == ER_OK) {
/*
* We got a socket, now tell WFD to connect to the remote address and
* port.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Connect()"));
status = qcc::Connect(sockFd, ipAddr, port);
if (status == ER_OK) {
/*
* We now have a WFD connection established, but DBus (the wire
* protocol which we are using) requires that every connection,
* irrespective of transport, start with a single zero byte. This
* is so that the Unix-domain socket transport used by DBus can pass
* SCM_RIGHTS out-of-band when that byte is sent.
*/
uint8_t nul = 0;
size_t sent;
QCC_DbgPrintf(("WFDTransport::Connect(): Send() one byte"));
status = Send(sockFd, &nul, 1, sent);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Connect(): Failed to send initial NUL byte"));
}
isConnected = true;
} else {
QCC_LogError(status, ("WFDTransport::Connect(): Failed"));
}
} else {
QCC_LogError(status, ("WFDTransport::Connect(): qcc::Socket() failed"));
}
if (status == ER_OK) {
/*
* The underlying transport mechanism is started, but we need to create
* a WFDEndpoint object that will orchestrate the movement of data
* across the transport.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): new WFDEndpoint()"));
bool falsiness = false;
WFDEndpoint conn(this, m_bus, falsiness, normSpec, sockFd, ipAddr, port, guid);
/*
* On the active side of a connection, we don't need an authentication
* thread to run since we have the caller thread to fill that role.
*/
conn->SetActive();
conn->SetAuthenticating();
/*
* Initialize the "features" for this endpoint
*/
conn->GetFeatures().isBusToBus = true;
conn->GetFeatures().allowRemote = m_bus.GetInternal().AllowRemoteMessages();
conn->GetFeatures().handlePassing = false;
qcc::String authName;
qcc::String redirection;
/*
* This is a little tricky. We usually manage endpoints in one place
* using the main server accept loop thread. This thread expects
* endpoints to have an RX thread and a TX thread running, and these
* threads are expected to run through the EndpointExit function when
* they are stopped. The general endpoint management uses these
* mechanisms. However, we are about to get into a state where we are
* off trying to start an endpoint, but we are using another thread
* which has called into WFDTransport::Connect(). We are about to do
* blocking I/O in the authentication establishment dance, but we can't
* just kill off this thread since it isn't ours for the whacking. If
* the transport is stopped, we do however need a way to stop an
* in-process establishment. It's not reliable to just close a socket
* out from uder a thread, so we really need to Alert() the thread
* making the blocking calls. So we keep a separate list of Thread*
* that may need to be Alert()ed and run through that list when the
* transport is stopping. This will cause the I/O calls in Establish()
* to return and we can then allow the "external" threads to return
* and avoid nasty deadlocks.
*/
Thread* thread = GetThread();
m_endpointListLock.Lock(MUTEX_CONTEXT);
m_activeEndpointsThreadList.insert(thread);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
/*
* Go ahead and do the authentication in the context of this thread. Even
* though we don't have the server accept loop thread watching this endpoint
* we keep we keep the states consistent since the endpoint will eventually
* to there.
*/
QCC_DbgPrintf(("WFDTransport::Connect(): Establish()"));
status = conn->Establish("ANONYMOUS", authName, redirection);
if (status == ER_OK) {
conn->SetListener(this);
status = conn->Start();
if (status == ER_OK) {
conn->SetEpStarted();
conn->SetAuthDone();
} else {
conn->SetEpFailed();
conn->SetAuthDone();
}
}
/*
* If we have a successful authentication, we pass the connection off to the
* server accept loop to manage.
*/
if (status == ER_OK) {
QCC_DbgPrintf(("WFDTransport::Connect(): Success. Pass connection."));
m_endpointListLock.Lock(MUTEX_CONTEXT);
m_endpointList.insert(conn);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
newep = BusEndpoint::cast(conn);
} else {
QCC_LogError(status, ("WFDTransport::Connect(): Starting the WFDEndpoint failed"));
/*
* Although the destructor of a remote endpoint includes a Stop and Join
* call, there are no running threads since Start() failed.
*/
conn->Invalidate();
}
/*
* In any case, we are done with blocking I/O on the current thread, so
* we need to remove its pointer from the list we kept around to break it
* out of blocking I/O. If we were successful, the WFDEndpoint was passed
* to the m_endpointList, where the main server accept loop will deal with
* it using its RX and TX thread-based mechanisms. If we were unsuccessful
* the WFDEndpoint was destroyed and we will return an error below after
* cleaning up the underlying socket.
*/
m_endpointListLock.Lock(MUTEX_CONTEXT);
set<Thread*>::iterator i = find(m_activeEndpointsThreadList.begin(), m_activeEndpointsThreadList.end(), thread);
assert(i != m_activeEndpointsThreadList.end() && "WFDTransport::Connect(): Thread* not on m_activeEndpointsThreadList");
m_activeEndpointsThreadList.erase(i);
m_endpointListLock.Unlock(MUTEX_CONTEXT);
} else {
/*
* If we got an error, and have not created an endpoint, we need to cleanup
* the socket. If an endpoint was created, the endpoint will be responsible
* for the cleanup.
*/
if (isConnected) {
qcc::Shutdown(sockFd);
}
if (sockFd >= 0) {
qcc::Close(sockFd);
}
}
if (status != ER_OK) {
/* If we got this connection and its endpoint up without
* a problem, we return a pointer to the new endpoint. We aren't going to
* clean it up since it is an active connection, so we can safely pass the
* endoint back up to higher layers.
* Invalidate the endpoint in case of error.
*/
newep->Invalidate();
} else {
assert(newep->IsValid() && "WFDTransport::Connect(): If the conn is up, the conn should be valid");
}
QCC_DbgPrintf(("WFDTransport::Connect(): Done."));
return status;
}
QStatus WFDTransport::Disconnect(const char* connectSpec)
{
QCC_DbgTrace(("WFDTransport::Disconnect(): %s", connectSpec));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing, and by extension the endpoint threads which
* must be running to properly clean up. See the comment in Start() for
* details about what IsRunning actually means, which might be subtly
* different from your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::Disconnect(): Not running or stopping; exiting"));
return ER_BUS_TRANSPORT_NOT_STARTED;
}
/*
* If we pass the IsRunning() gate above, we must have a server accept
* thread spinning up or shutting down but not yet joined. Since the name
* service is started before the server accept thread is spun up, and
* stopped after it is stopped, we must have a started name service or
* someone isn't playing by the rules; so an assert is appropriate here.
*/
assert(P2PNameService::Instance().Started() && "WFDTransport::Disconnect(): P2PNameService not started");
/*
* Higher level code tells us which connection is refers to by giving us the
* same connect spec it used in the Connect() call. For the Wi-Fi Direct
* transport, this is going to be the GUID found in the original service
* discovery event.
*/
qcc::String normSpec;
map<qcc::String, qcc::String> argMap;
QStatus status = NormalizeTransportSpec(connectSpec, normSpec, argMap);
if (ER_OK != status) {
QCC_LogError(status, ("WFDTransport::Disconnect(): Invalid WFD connect spec \"%s\"", connectSpec));
return status;
}
map<qcc::String, qcc::String>::iterator iter = argMap.find("guid");
assert(iter != argMap.end() && "WFDTransport::Connect(): Transport spec must provide \"guid\"");
qcc::String guid = iter->second;
/*
* Now we must stop the remote endpoint(s) associated with the GUID. Be
* careful here since calling Stop() on the WFDEndpoint is going to cause
* the transmit and receive threads of the underlying RemoteEndpoint to
* exit, which will cause our EndpointExit() to be called, which will walk
* the list of endpoints and delete the one we are stopping. Once we poke
* ep->Stop(), the pointer to ep must be considered dead.
*/
status = ER_BUS_BAD_TRANSPORT_ARGS;
m_endpointListLock.Lock(MUTEX_CONTEXT);
for (set<WFDEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) {
WFDEndpoint ep = *i;
if (ep->GetGuid() == guid) {
ep->SetSuddenDisconnect(false);
ep->Stop();
i = m_endpointList.begin();
}
}
m_endpointListLock.Unlock(MUTEX_CONTEXT);
/*
* We've started the process of getting rid of any endpoints we may have created.
* Now we have to actually get rid of the temporary network itself. Since the
* network is related to the device, not the GUID, we have to get the device
* (MAC address) first.
*/
qcc::String device;
status = P2PNameService::Instance().GetDeviceForGuid(guid, device);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Disconnect(): Device corresponding to GUID \"%s\" is gone", guid.c_str()));
return status;
}
/*
* Now, leave the P2P Group that our device is participating in.
*/
status = P2PConMan::Instance().DestroyTemporaryNetwork();
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::Disconnect(): Unable to DestroyTemporaryNetwork"));
return status;
}
return status;
}
QStatus WFDTransport::StartListen(const char* listenSpec)
{
QCC_DbgTrace(("WFDTransport::StartListen()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::StartListen(): Not running or stopping; exiting"));
return ER_BUS_TRANSPORT_NOT_STARTED;
}
/*
* Normalize the listen spec. Although this looks like a connectSpec it is
* different in that reasonable defaults are possible. We do the
* normalization here so we can report an error back to the caller.
*/
qcc::String normSpec;
map<qcc::String, qcc::String> argMap;
QStatus status = NormalizeListenSpec(listenSpec, normSpec, argMap);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::StartListen(): Invalid WFD listen spec \"%s\"", listenSpec));
return status;
}
QCC_DbgPrintf(("WFDTransport::StartListen(): r4addr = \"%s\", r4port = \"%s\"",
argMap["r4addr"].c_str(), argMap["r4port"].c_str()));
/*
* The daemon code is in a state where it lags in functionality a bit with
* respect to the common code. Common supports the use of IPv6 addresses
* but the name service is not quite ready for prime time. Until the name
* service can properly distinguish between various cases, we fail any
* request to listen on an IPv6 address.
*/
IPAddress ipAddress;
status = ipAddress.SetAddress(argMap["r4addr"].c_str());
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::StartListen(): Unable to SetAddress(\"%s\")", argMap["r4addr"].c_str()));
return status;
}
if (ipAddress.IsIPv6()) {
status = ER_INVALID_ADDRESS;
QCC_LogError(status, ("WFDTransport::StartListen(): IPv6 address (\"%s\") in \"r4addr\" not allowed", argMap["r4addr"].c_str()));
return status;
}
/*
* Because we are sending a *request* to start listening on a given
* normalized listen spec to another thread, and the server thread starts
* and stops listening on given listen specs when it decides to eventually
* run, it is be possible for a calling thread to send multiple requests to
* start or stop listening on the same listenSpec before the server thread
* responds.
*
* In order to deal with these two timelines, we keep a list of normalized
* listenSpecs that we have requested to be started, and not yet requested
* to be removed. This list (the mListenSpecs) must be consistent with
* client requests to start and stop listens. This list is not necessarily
* consistent with what is actually being listened on. That is a separate
* list called mListenFds.
*
* So, check to see if someone has previously requested that the address and
* port in question be listened on. We need to do this here to be able to
* report an error back to the caller.
*/
m_listenSpecsLock.Lock(MUTEX_CONTEXT);
for (list<qcc::String>::iterator i = m_listenSpecs.begin(); i != m_listenSpecs.end(); ++i) {
if (*i == normSpec) {
m_listenSpecsLock.Unlock(MUTEX_CONTEXT);
return ER_BUS_ALREADY_LISTENING;
}
}
m_listenSpecsLock.Unlock(MUTEX_CONTEXT);
QueueStartListen(normSpec);
return ER_OK;
}
void WFDTransport::QueueStartListen(qcc::String& normSpec)
{
QCC_DbgTrace(("WFDTransport::QueueStartListen()"));
/*
* In order to start a listen, we send the server accept thread a message
* containing the START_LISTEN_INSTANCE request code and the normalized
* listen spec which specifies the address and port instance to listen on.
*/
ListenRequest listenRequest;
listenRequest.m_requestOp = START_LISTEN_INSTANCE;
listenRequest.m_requestParam = normSpec;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
void WFDTransport::DoStartListen(qcc::String& normSpec)
{
QCC_DbgTrace(("WFDTransport::DoStartListen()"));
/*
* Parse the normalized listen spec. The easiest way to do this is to
* re-normalize it. If there's an error at this point, we have done
* something wrong since the listen spec was presumably successfully
* normalized before sending it in -- so we assert.
*/
qcc::String spec;
map<qcc::String, qcc::String> argMap;
QStatus status = NormalizeListenSpec(normSpec.c_str(), spec, argMap);
assert(status == ER_OK && "WFDTransport::DoStartListen(): Invalid WFD listen spec");
QCC_DbgPrintf(("WFDTransport::DoStartListen(): r4addr = \"%s\", r4port = \"%s\"",
argMap["r4addr"].c_str(), argMap["r4port"].c_str()));
m_listenFdsLock.Lock(MUTEX_CONTEXT);
/*
* Figure out what local address and port the listener should use.
*/
IPAddress listenAddr(argMap["r4addr"]);
uint16_t listenPort = StringToU32(argMap["r4port"]);
bool ephemeralPort = (listenPort == 0);
/*
* Create the actual TCP listener sockets and set SO_REUSEADDR/SO_REUSEPORT
* so we don't have to wait for four minutes to relaunch the daemon if it
* crashes.
*/
SocketFd listenFd = qcc::INVALID_SOCKET_FD;
status = Socket(QCC_AF_INET, QCC_SOCK_STREAM, listenFd);
if (status != ER_OK) {
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
QCC_LogError(status, ("WFDTransport::DoStartListen(): Socket() failed"));
return;
}
/*
* Set the SO_REUSEADDR socket option so we don't have to wait for four
* minutes while the endpoint is in TIME_WAIT if we crash (or control-C).
*/
status = qcc::SetReuseAddress(listenFd, true);
if (status != ER_OK && status != ER_NOT_IMPLEMENTED) {
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
QCC_LogError(status, ("WFDTransport::DoStartListen(): SetReuseAddress() failed"));
qcc::Close(listenFd);
return;
}
/*
* We call accept in a loop so we need the listenFd to non-blocking
*/
status = qcc::SetBlocking(listenFd, false);
if (status != ER_OK) {
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
QCC_LogError(status, ("WFDTransport::DoStartListen(): SetBlocking() failed"));
qcc::Close(listenFd);
return;
}
/*
* Bind the socket to the listen address and start listening for incoming
* connections on it.
*/
if (ephemeralPort) {
/*
* First try binding to the default port
*/
listenPort = PORT_DEFAULT;
status = Bind(listenFd, listenAddr, listenPort);
if (status != ER_OK) {
listenPort = 0;
status = Bind(listenFd, listenAddr, listenPort);
}
} else {
status = Bind(listenFd, listenAddr, listenPort);
}
if (status == ER_OK) {
/*
* If the port was not set (or set to zero) then we will have bound an ephemeral port. If
* so call GetLocalAddress() to update the connect spec with the port allocated by bind.
*/
if (ephemeralPort) {
qcc::GetLocalAddress(listenFd, listenAddr, listenPort);
normSpec = qcc::String(GetTransportName()) + qcc::String(":r4addr=") + argMap["r4addr"] +
qcc::String(",r4port=") + U32ToString(listenPort);
}
status = qcc::Listen(listenFd, MAX_LISTEN_CONNECTIONS);
if (status == ER_OK) {
QCC_DbgPrintf(("WFDTransport::DoStartListen(): Listening on %s/%d", argMap["r4addr"].c_str(), listenPort));
m_listenFds.push_back(pair<qcc::String, SocketFd>(normSpec, listenFd));
} else {
QCC_LogError(status, ("WFDTransport::DoStartListen(): Listen failed"));
}
} else {
QCC_LogError(status, ("WFDTransport::DoStartListen(): Failed to bind to %s/%d", listenAddr.ToString().c_str(), listenPort));
}
/*
* In the WFDTransport, we only support discovery of services that are
* advertised over Wi-Fi Direct pre-association service discovery. We
* explicitly don't allow the IP name service to insinuate itself onto
* Wi-Fi Direct established links and begin advertising willy-nilly.
* we only enable the IP name service for the specific use case of
* discovering IP address and port from daemon GUID.
*/
m_listenPort = listenPort;
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
/*
* Signal the (probably) waiting run thread so it will wake up and add this
* new socket to its list of sockets it is waiting for connections on.
*/
if (status == ER_OK) {
Alert();
}
}
QStatus WFDTransport::StopListen(const char* listenSpec)
{
QCC_DbgTrace(("WFDTransport::StopListen()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::StopListen(): Not running or stopping; exiting"));
return ER_BUS_TRANSPORT_NOT_STARTED;
}
/*
* Normalize the listen spec. We are going to use the name string that was
* put together for the StartListen call to find the listener instance to
* stop, so we need to do it exactly the same way.
*/
qcc::String normSpec;
map<qcc::String, qcc::String> argMap;
QStatus status = NormalizeListenSpec(listenSpec, normSpec, argMap);
if (status != ER_OK) {
QCC_LogError(status, ("WFDTransport::StopListen(): Invalid WFD listen spec \"%s\"", listenSpec));
return status;
}
/*
* Because we are sending a *request* to stop listening on a given
* normalized listen spec to another thread, and the server thread starts
* and stops listening on given listen specs when it decides to eventually
* run, it is be possible for a calling thread to send multiple requests to
* start or stop listening on the same listenSpec before the server thread
* responds.
*
* In order to deal with these two timelines, we keep a list of normalized
* listenSpecs that we have requested to be started, and not yet requested
* to be removed. This list (the mListenSpecs) must be consistent with
* client requests to start and stop listens. This list is not necessarily
* consistent with what is actually being listened on. That is reflected by
* a separate list called mListenFds.
*
* We consult the list of listen spects for duplicates when starting to
* listen, and we make sure that a listen spec is on the list before
* queueing a request to stop listening. Asking to stop listening on a
* listen spec we aren't listening on is not an error, since the goal of the
* user is to not listen on a given address and port -- and we aren't.
*/
m_listenSpecsLock.Lock(MUTEX_CONTEXT);
for (list<qcc::String>::iterator i = m_listenSpecs.begin(); i != m_listenSpecs.end(); ++i) {
if (*i == normSpec) {
m_listenSpecs.erase(i);
QueueStopListen(normSpec);
break;
}
}
m_listenSpecsLock.Unlock(MUTEX_CONTEXT);
return ER_OK;
}
void WFDTransport::QueueStopListen(qcc::String& normSpec)
{
QCC_DbgTrace(("WFDTransport::QueueStopListen()"));
/*
* In order to stop a listen, we send the server accept thread a message
* containing the STOP_LISTEN_INTANCE request code and the normalized listen
* spec which specifies the address and port instance to stop listening on.
*/
ListenRequest listenRequest;
listenRequest.m_requestOp = STOP_LISTEN_INSTANCE;
listenRequest.m_requestParam = normSpec;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
void WFDTransport::DoStopListen(qcc::String& normSpec)
{
QCC_DbgTrace(("WFDTransport::DoStopListen()"));
/*
* Since the name service is started before the server accept thread is spun
* up, and stopped after it is stopped, we must have a started name service or
* someone isn't playing by the rules; so an assert is appropriate here.
*/
assert(P2PNameService::Instance().Started() && "WFDTransport::DoStopListen(): P2PNameService not started");
/*
* Find the (single) listen spec and remove it from the list of active FDs
* used by the server accept loop (run thread). This is okay to do since
* we are assuming that, since we should only be called in the context of
* the server accept loop, it knows that an FD will be deleted here.
*/
m_listenFdsLock.Lock(MUTEX_CONTEXT);
qcc::SocketFd stopFd = qcc::INVALID_SOCKET_FD;
bool found = false;
for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) {
if (i->first == normSpec) {
stopFd = i->second;
m_listenFds.erase(i);
found = true;
break;
}
}
m_listenFdsLock.Unlock(MUTEX_CONTEXT);
/*
* If we took a socketFD off of the list of active FDs, we need to tear it
* down and alert the server accept loop that the list of FDs on which it
* is listening has changed.
*/
if (found) {
qcc::Shutdown(stopFd);
qcc::Close(stopFd);
}
}
bool WFDTransport::NewDiscoveryOp(DiscoveryOp op, qcc::String namePrefix, bool& isFirst)
{
QCC_DbgTrace(("WFDTransport::NewDiscoveryOp()"));
bool first = false;
if (op == ENABLE_DISCOVERY) {
QCC_DbgPrintf(("WFDTransport::NewDiscoveryOp(): Registering discovery of namePrefix \"%s\"", namePrefix.c_str()));
first = m_advertising.empty();
m_discovering.push_back(namePrefix);
} else {
list<qcc::String>::iterator i = find(m_discovering.begin(), m_discovering.end(), namePrefix);
if (i == m_discovering.end()) {
QCC_DbgPrintf(("WFDTransport::NewDiscoveryOp(): Cancel of non-existent namePrefix \"%s\"", namePrefix.c_str()));
} else {
QCC_DbgPrintf(("WFDTransport::NewDiscoveryOp(): Unregistering discovery of namePrefix \"%s\"", namePrefix.c_str()));
m_discovering.erase(i);
}
}
isFirst = first;
return m_discovering.empty();
}
bool WFDTransport::NewAdvertiseOp(AdvertiseOp op, qcc::String name, bool& isFirst)
{
QCC_DbgTrace(("WFDTransport::NewAdvertiseOp()"));
bool first = false;
if (op == ENABLE_ADVERTISEMENT) {
QCC_DbgPrintf(("WFDTransport::NewAdvertiseOp(): Registering advertisement of namePrefix \"%s\"", name.c_str()));
first = m_advertising.empty();
m_advertising.push_back(name);
} else {
list<qcc::String>::iterator i = find(m_advertising.begin(), m_advertising.end(), name);
if (i == m_advertising.end()) {
QCC_DbgPrintf(("WFDTransport::NewAdvertiseOp(): Cancel of non-existent name \"%s\"", name.c_str()));
} else {
QCC_DbgPrintf(("WFDTransport::NewAdvertiseOp(): Unregistering advertisement of namePrefix \"%s\"", name.c_str()));
m_advertising.erase(i);
}
}
isFirst = first;
return m_advertising.empty();
}
bool WFDTransport::NewListenOp(ListenOp op, qcc::String normSpec)
{
QCC_DbgTrace(("WFDTransport::NewListenOp()"));
if (op == START_LISTEN) {
QCC_DbgPrintf(("WFDTransport::NewListenOp(): Registering listen of normSpec \"%s\"", normSpec.c_str()));
m_listening.push_back(normSpec);
} else {
list<qcc::String>::iterator i = find(m_listening.begin(), m_listening.end(), normSpec);
if (i == m_listening.end()) {
QCC_DbgPrintf(("WFDTransport::NewAdvertiseOp(): StopListen of non-existent spec \"%s\"", normSpec.c_str()));
} else {
QCC_DbgPrintf(("WFDTransport::NewAdvertiseOp(): StopListen of normSpec \"%s\"", normSpec.c_str()));
m_listening.erase(i);
}
}
return m_listening.empty();
}
void WFDTransport::EnableDiscovery(const char* namePrefix)
{
QCC_DbgTrace(("WFDTransport::EnableDiscovery()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::EnableDiscovery(): Not running or stopping; exiting"));
return;
}
QueueEnableDiscovery(namePrefix);
}
void WFDTransport::QueueEnableDiscovery(const char* namePrefix)
{
QCC_DbgTrace(("WFDTransport::QueueEnableDiscovery()"));
ListenRequest listenRequest;
listenRequest.m_requestOp = ENABLE_DISCOVERY_INSTANCE;
listenRequest.m_requestParam = namePrefix;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
void WFDTransport::DisableDiscovery(const char* namePrefix)
{
QCC_DbgTrace(("WFDTransport::DisableDiscovery()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::DisbleDiscovery(): Not running or stopping; exiting"));
return;
}
QueueDisableDiscovery(namePrefix);
}
void WFDTransport::QueueDisableDiscovery(const char* namePrefix)
{
QCC_DbgTrace(("WFDTransport::QueueDisableDiscovery()"));
ListenRequest listenRequest;
listenRequest.m_requestOp = DISABLE_DISCOVERY_INSTANCE;
listenRequest.m_requestParam = namePrefix;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
QStatus WFDTransport::EnableAdvertisement(const qcc::String& advertiseName, bool quietly, TransportMask transports)
{
QCC_DbgTrace(("WFDTransport::EnableAdvertisement()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::EnableAdvertisement(): Not running or stopping; exiting"));
return ER_BUS_TRANSPORT_NOT_STARTED;
}
QueueEnableAdvertisement(advertiseName);
return ER_OK;
}
void WFDTransport::QueueEnableAdvertisement(const qcc::String& advertiseName)
{
QCC_DbgTrace(("WFDTransport::QueueEnableAdvertisement()"));
ListenRequest listenRequest;
listenRequest.m_requestOp = ENABLE_ADVERTISEMENT_INSTANCE;
listenRequest.m_requestParam = advertiseName;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
void WFDTransport::DisableAdvertisement(const qcc::String& advertiseName, TransportMask transports)
{
QCC_DbgTrace(("WFDTransport::DisableAdvertisement()"));
/*
* We only want to allow this call to proceed if we have a running server
* accept thread that isn't in the process of shutting down. We use the
* thread response from IsRunning to give us an idea of what our server
* accept (Run) thread is doing. See the comment in Start() for details
* about what IsRunning actually means, which might be subtly different from
* your intuitition.
*
* If we see IsRunning(), the thread might actually have gotten a Stop(),
* but has not yet exited its Run routine and become STOPPING. To plug this
* hole, we need to check IsRunning() and also m_stopping, which is set in
* our Stop() method.
*/
if (IsRunning() == false || m_stopping == true) {
QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("WFDTransport::DisableAdvertisement(): Not running or stopping; exiting"));
return;
}
QueueDisableAdvertisement(advertiseName);
}
void WFDTransport::QueueDisableAdvertisement(const qcc::String& advertiseName)
{
QCC_DbgTrace(("WFDTransport::QueueDisableAdvertisement()"));
ListenRequest listenRequest;
listenRequest.m_requestOp = DISABLE_ADVERTISEMENT_INSTANCE;
listenRequest.m_requestParam = advertiseName;
m_listenRequestsLock.Lock(MUTEX_CONTEXT);
m_listenRequests.push(listenRequest);
m_listenRequestsLock.Unlock(MUTEX_CONTEXT);
/*
* Wake the server accept loop thread up so it will process the request we
* just queued.
*/
Alert();
}
void WFDTransport::P2PNameServiceCallback(const qcc::String& guid, qcc::String& name, uint8_t timer)
{
QCC_DbgTrace(("WFDTransport::P2PNameServiceCallback(): guid = \"%s\", timer = %d", guid.c_str(), timer));
/*
* Whenever the P2P name service receives a message indicating that a
* bus-name is out on the network via pre-association service discovery, it
* sends a message back to us via this callback that will conatin the GUID
* of the remote daemon thad did the advertisement, the list of well-known
* names being advertised and a validation timer.
*
* Although it may seem that this method and the P2PConManNameCallback() are
* redundant, they actually come from different places and serve different
* functions. This method receives pre-association service discovery callbacks
* and contains no layer three addressing information. The other callback
* receives IP name service-related information and does include layer three
* addressing information.
*
* Because they are fundamentally different (layer two versus layer three)
* the busAddr/connectSpec provided back to clients is different. Here, we
* have no busAddr since there is no layer three information, so we provide
* our layer two mapping key (the GUID of the remote daemon that advertised
* the name we just found) back to the client.
*
* If the client decides to JoinSession as a result of the advertisement we
* are about to pass on, the daemon does a Connect() where we notice that
* the connectSpec provides a GUID. This tells us that we are bringing up a
* new link and we need to discover the layer three addressing before
* continuing.
*/
qcc::String connectSpec = qcc::String(GetTransportName()) + qcc::String(":guid=") + guid;
/*
* Let AllJoyn know that we've found a service.
*/
if (m_listener) {
QCC_DbgPrintf(("WFDTransport::P2PNameServiceCallback(): Call listener with busAddr \"%s\", timer %d.", connectSpec.c_str(), timer));
std::vector<qcc::String> wkns;
wkns.push_back(name);
m_listener->FoundNames(connectSpec, guid, TRANSPORT_WFD, &wkns, timer);
}
}
void WFDTransport::P2PConManNameCallback(const qcc::String& busAddr, const qcc::String& guid, std::vector<qcc::String>& nameList, uint8_t timer)
{
QCC_DbgTrace(("WFDTransport::P2PConManNameCallback(): busAddr = \"%s\", guid = \"%s\", timer = %d", busAddr.c_str(), guid.c_str(), timer));
QCC_DEBUG_ONLY(
for (uint32_t i = 0; i < nameList.size(); ++i) {
QCC_DbgPrintf(("WFDTransport::P2PConManNameCallback(): nameList[%d] = \"%s\"", i, nameList[i].c_str()));
}
);
/*
* Whenever the P2P connection manager receives a message indicating that a
* bus-name is out on the network via the IP name service, it sends a
* message back to us via this callback that will conatin a bus address
* (with an IP address and port0 the GUID of the remote daemon thad did the
* advertisement, the list of well-known names being advertised and a
* validation timer.
*
* Although it may seem that this method and the P2PNameServiceCallback()
* are redundant, they actually come from different places and serve
* different functions. This method receives IP name service-related
* information that includes layer three addressing information while the
* other method gets pre-association service discovery callbacks that no
* layer three addressing information.
*
* Because they are fundamentally different (layer three here versus layer
* two there) the busAddr/connectSpec provided back to clients is different.
* Here, we have a busAddr containing layer three information, so we pass it
* on back to the client.
*
* If the client decides to JoinSession as a result of the advertisement we
* are about to pass on, the daemon does a Connect() where we notice that
* the connectSpec provides IP addressing information. This tells us that
* we are "borrowing" an existing link and we don't need to go through the
* gyrations of discovering the layer three addressing.
*/
qcc::String connectSpec = qcc::String(GetTransportName()) + qcc::String(":") + busAddr;
/*
* Let AllJoyn know that we've found a service through our "alternate
* IP channel."
*/
if (m_listener) {
m_listener->FoundNames(connectSpec, guid, TRANSPORT_WFD, &nameList, timer);
}
}
void WFDTransport::P2PConManStateCallback(P2PConMan::LinkState state, const qcc::String& interface)
{
QCC_DbgTrace(("WFDTransport::P2PConManStateCallback(): state = %d, interface = \"%s\"", state, interface.c_str()));
/*
* Whenever the P2P connection manager notices a link coming up or going down
* it calls us back here to let us know.
*/
}
} // namespace ajn
| 44.883221 | 212 | 0.652571 | [
"object",
"vector",
"model"
] |
dcbdd8e2e10ce4751dbfa13833d2e3d47bce1c1b | 654 | hpp | C++ | include/game/skirmish/meta/terrainmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 3 | 2015-03-28T02:51:58.000Z | 2018-11-08T16:49:53.000Z | include/game/skirmish/meta/terrainmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 39 | 2015-05-18T08:29:16.000Z | 2020-07-18T21:17:44.000Z | include/game/skirmish/meta/terrainmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | null | null | null | #ifndef QRW_TERRAINMETACLASS_HPP
#define QRW_TERRAINMETACLASS_HPP
#include "meta/reflectable.hpp"
#include "meta/metaclass.hpp"
namespace qrw {
class TerrainMetaClass : public MetaClass
{
public:
TerrainMetaClass(const MetaManager& metaManager);
~TerrainMetaClass();
virtual void serialize(const Reflectable* object, YAML::Emitter& out) const final override;
virtual Reflectable* deserialize(const YAML::Node& in) const final override;
private:
TerrainMetaClass(const TerrainMetaClass& rhs) = delete;
TerrainMetaClass& operator=(const TerrainMetaClass& rhs) = delete;
};
} // namespace qrw
#endif // QRW_TERRAINMETACLASS_HPP
| 21.8 | 92 | 0.772171 | [
"object"
] |
dcbf7e791429a005c8732cfd92dff0e94ad8d85e | 2,700 | cpp | C++ | src/lib/utils/meta_tables/abstract_meta_table.cpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 583 | 2015-01-10T00:55:32.000Z | 2022-03-25T12:24:30.000Z | src/lib/utils/meta_tables/abstract_meta_table.cpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 1,573 | 2015-01-07T15:47:22.000Z | 2022-03-31T11:48:03.000Z | src/lib/utils/meta_tables/abstract_meta_table.cpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 145 | 2015-03-09T16:26:07.000Z | 2022-02-15T12:53:23.000Z | #include "abstract_meta_table.hpp"
#include "statistics/table_statistics.hpp"
#include "utils/assert.hpp"
#include "utils/meta_table_manager.hpp"
namespace opossum {
AbstractMetaTable::AbstractMetaTable(const TableColumnDefinitions& column_definitions)
: _column_definitions(column_definitions) {}
std::shared_ptr<Table> AbstractMetaTable::_generate() const {
auto table = _on_generate();
if (table->chunk_count()) {
table->last_chunk()->finalize();
}
table->set_table_statistics(TableStatistics::from_table(*table));
return table;
}
bool AbstractMetaTable::can_insert() const { return false; }
bool AbstractMetaTable::can_update() const { return false; }
bool AbstractMetaTable::can_delete() const { return false; }
void AbstractMetaTable::_insert(const std::vector<AllTypeVariant>& values) {
Assert(can_insert(), "Cannot insert into " + name() + ".");
_validate_data_types(values);
_on_insert(values);
}
void AbstractMetaTable::_remove(const std::vector<AllTypeVariant>& values) {
Assert(can_delete(), "Cannot delete from " + name() + ".");
_validate_data_types(values);
_on_remove(values);
}
void AbstractMetaTable::_update(const std::vector<AllTypeVariant>& selected_values,
const std::vector<AllTypeVariant>& update_values) {
Assert(can_update(), "Cannot update " + name() + ".");
_validate_data_types(selected_values);
_validate_data_types(update_values);
_on_update(selected_values, update_values);
}
void AbstractMetaTable::_on_insert(const std::vector<AllTypeVariant>& values) {
Fail("Cannot insert into " + MetaTableManager::META_PREFIX + name() + ".");
}
void AbstractMetaTable::_on_remove(const std::vector<AllTypeVariant>& values) {
Fail("Cannot delete from " + MetaTableManager::META_PREFIX + name() + ".");
}
void AbstractMetaTable::_on_update(const std::vector<AllTypeVariant>& selected_values,
const std::vector<AllTypeVariant>& update_values) {
Fail("Cannot update " + MetaTableManager::META_PREFIX + name() + ".");
}
void AbstractMetaTable::_validate_data_types(const std::vector<AllTypeVariant>& values) const {
Assert(values.size() == column_definitions().size(), "Number of values must match column definitions.");
for (size_t column = 0; column < values.size(); column++) {
const auto value_type = data_type_from_all_type_variant(values[column]);
const auto column_type = column_definitions()[column].data_type;
Assert(value_type == column_type, "Data types must match column definitions.");
}
}
const TableColumnDefinitions& AbstractMetaTable::column_definitions() const { return _column_definitions; }
} // namespace opossum
| 35.526316 | 107 | 0.731111 | [
"vector"
] |
dcc0f8356fb66ee96347d2e1e0824eda277e5b37 | 22,918 | cpp | C++ | src/proj/iso19111/operation/oputils.cpp | jeroen/libproj | 993fc4f3531a7f902a7e518c4ce7b6d12ddd5c47 | [
"MIT"
] | 12 | 2020-08-06T07:08:24.000Z | 2021-10-06T15:08:21.000Z | src/proj/iso19111/operation/oputils.cpp | jeroen/libproj | 993fc4f3531a7f902a7e518c4ce7b6d12ddd5c47 | [
"MIT"
] | 19 | 2020-08-11T15:44:19.000Z | 2022-01-16T00:06:03.000Z | src/proj/iso19111/operation/oputils.cpp | jeroen/libproj | 993fc4f3531a7f902a7e518c4ce7b6d12ddd5c47 | [
"MIT"
] | 2 | 2020-08-07T02:32:32.000Z | 2020-08-27T10:57:21.000Z | /******************************************************************************
*
* Project: PROJ
* Purpose: ISO19111:2019 implementation
* Author: Even Rouault <even dot rouault at spatialys dot com>
*
******************************************************************************
* Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef FROM_PROJ_CPP
#define FROM_PROJ_CPP
#endif
#include <string.h>
#include "R-libproj/proj/coordinateoperation.hpp"
#include "R-libproj/proj/crs.hpp"
#include "R-libproj/proj/util.hpp"
#include "R-libproj/proj/internal/internal.hpp"
#include "R-libproj/proj/internal/io_internal.hpp"
#include "R-libproj/iso19111/operation/oputils.hpp"
#include "R-libproj/iso19111/operation/parammappings.hpp"
#include "R-libproj/proj_constants.h"
// ---------------------------------------------------------------------------
NS_PROJ_START
using namespace internal;
namespace operation {
// ---------------------------------------------------------------------------
//! @cond Doxygen_Suppress
const char *BALLPARK_GEOCENTRIC_TRANSLATION = "Ballpark geocentric translation";
const char *NULL_GEOGRAPHIC_OFFSET = "Null geographic offset";
const char *NULL_GEOCENTRIC_TRANSLATION = "Null geocentric translation";
const char *BALLPARK_GEOGRAPHIC_OFFSET = "Ballpark geographic offset";
const char *BALLPARK_VERTICAL_TRANSFORMATION =
" (ballpark vertical transformation)";
const char *BALLPARK_VERTICAL_TRANSFORMATION_NO_ELLIPSOID_VERT_HEIGHT =
" (ballpark vertical transformation, without ellipsoid height to vertical "
"height correction)";
// ---------------------------------------------------------------------------
OperationParameterNNPtr createOpParamNameEPSGCode(int code) {
const char *name = OperationParameter::getNameForEPSGCode(code);
assert(name);
return OperationParameter::create(createMapNameEPSGCode(name, code));
}
// ---------------------------------------------------------------------------
util::PropertyMap createMethodMapNameEPSGCode(int code) {
const char *name = nullptr;
size_t nMethodNameCodes = 0;
const auto methodNameCodes = getMethodNameCodes(nMethodNameCodes);
for (size_t i = 0; i < nMethodNameCodes; ++i) {
const auto &tuple = methodNameCodes[i];
if (tuple.epsg_code == code) {
name = tuple.name;
break;
}
}
assert(name);
return createMapNameEPSGCode(name, code);
}
// ---------------------------------------------------------------------------
util::PropertyMap createMapNameEPSGCode(const std::string &name, int code) {
return util::PropertyMap()
.set(common::IdentifiedObject::NAME_KEY, name)
.set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG)
.set(metadata::Identifier::CODE_KEY, code);
}
// ---------------------------------------------------------------------------
util::PropertyMap createMapNameEPSGCode(const char *name, int code) {
return util::PropertyMap()
.set(common::IdentifiedObject::NAME_KEY, name)
.set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG)
.set(metadata::Identifier::CODE_KEY, code);
}
// ---------------------------------------------------------------------------
util::PropertyMap &addDomains(util::PropertyMap &map,
const common::ObjectUsage *obj) {
auto ar = util::ArrayOfBaseObject::create();
for (const auto &domain : obj->domains()) {
ar->add(domain);
}
if (!ar->empty()) {
map.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, ar);
}
return map;
}
// ---------------------------------------------------------------------------
static const char *getCRSQualifierStr(const crs::CRSPtr &crs) {
auto geod = dynamic_cast<crs::GeodeticCRS *>(crs.get());
if (geod) {
if (geod->isGeocentric()) {
return " (geocentric)";
}
auto geog = dynamic_cast<crs::GeographicCRS *>(geod);
if (geog) {
if (geog->coordinateSystem()->axisList().size() == 2) {
return " (geog2D)";
} else {
return " (geog3D)";
}
}
}
return "";
}
// ---------------------------------------------------------------------------
std::string buildOpName(const char *opType, const crs::CRSPtr &source,
const crs::CRSPtr &target) {
std::string res(opType);
const auto &srcName = source->nameStr();
const auto &targetName = target->nameStr();
const char *srcQualifier = "";
const char *targetQualifier = "";
if (srcName == targetName) {
srcQualifier = getCRSQualifierStr(source);
targetQualifier = getCRSQualifierStr(target);
if (strcmp(srcQualifier, targetQualifier) == 0) {
srcQualifier = "";
targetQualifier = "";
}
}
res += " from ";
res += srcName;
res += srcQualifier;
res += " to ";
res += targetName;
res += targetQualifier;
return res;
}
// ---------------------------------------------------------------------------
void addModifiedIdentifier(util::PropertyMap &map,
const common::IdentifiedObject *obj, bool inverse,
bool derivedFrom) {
// If original operation is AUTH:CODE, then assign INVERSE(AUTH):CODE
// as identifier.
auto ar = util::ArrayOfBaseObject::create();
for (const auto &idSrc : obj->identifiers()) {
auto authName = *(idSrc->codeSpace());
const auto &srcCode = idSrc->code();
if (derivedFrom) {
authName = concat("DERIVED_FROM(", authName, ")");
}
if (inverse) {
if (starts_with(authName, "INVERSE(") && authName.back() == ')') {
authName = authName.substr(strlen("INVERSE("));
authName.resize(authName.size() - 1);
} else {
authName = concat("INVERSE(", authName, ")");
}
}
auto idsProp = util::PropertyMap().set(
metadata::Identifier::CODESPACE_KEY, authName);
ar->add(metadata::Identifier::create(srcCode, idsProp));
}
if (!ar->empty()) {
map.set(common::IdentifiedObject::IDENTIFIERS_KEY, ar);
}
}
// ---------------------------------------------------------------------------
util::PropertyMap
createPropertiesForInverse(const OperationMethodNNPtr &method) {
util::PropertyMap map;
const std::string &forwardName = method->nameStr();
if (!forwardName.empty()) {
if (starts_with(forwardName, INVERSE_OF)) {
map.set(common::IdentifiedObject::NAME_KEY,
forwardName.substr(INVERSE_OF.size()));
} else {
map.set(common::IdentifiedObject::NAME_KEY,
INVERSE_OF + forwardName);
}
}
addModifiedIdentifier(map, method.get(), true, false);
return map;
}
// ---------------------------------------------------------------------------
util::PropertyMap createPropertiesForInverse(const CoordinateOperation *op,
bool derivedFrom,
bool approximateInversion) {
assert(op);
util::PropertyMap map;
// The domain(s) are unchanged by the inverse operation
addDomains(map, op);
const std::string &forwardName = op->nameStr();
// Forge a name for the inverse, either from the forward name, or
// from the source and target CRS names
const char *opType;
if (starts_with(forwardName, BALLPARK_GEOCENTRIC_TRANSLATION)) {
opType = BALLPARK_GEOCENTRIC_TRANSLATION;
} else if (starts_with(forwardName, BALLPARK_GEOGRAPHIC_OFFSET)) {
opType = BALLPARK_GEOGRAPHIC_OFFSET;
} else if (starts_with(forwardName, NULL_GEOGRAPHIC_OFFSET)) {
opType = NULL_GEOGRAPHIC_OFFSET;
} else if (starts_with(forwardName, NULL_GEOCENTRIC_TRANSLATION)) {
opType = NULL_GEOCENTRIC_TRANSLATION;
} else if (dynamic_cast<const Transformation *>(op) ||
starts_with(forwardName, "Transformation from ")) {
opType = "Transformation";
} else if (dynamic_cast<const Conversion *>(op)) {
opType = "Conversion";
} else {
opType = "Operation";
}
auto sourceCRS = op->sourceCRS();
auto targetCRS = op->targetCRS();
std::string name;
if (!forwardName.empty()) {
if (dynamic_cast<const Transformation *>(op) == nullptr &&
dynamic_cast<const ConcatenatedOperation *>(op) == nullptr &&
(starts_with(forwardName, INVERSE_OF) ||
forwardName.find(" + ") != std::string::npos)) {
std::vector<std::string> tokens;
std::string curToken;
bool inString = false;
for (size_t i = 0; i < forwardName.size(); ++i) {
if (inString) {
curToken += forwardName[i];
if (forwardName[i] == '\'') {
inString = false;
}
} else if (i + 3 < forwardName.size() &&
memcmp(&forwardName[i], " + ", 3) == 0) {
tokens.push_back(curToken);
curToken.clear();
i += 2;
} else if (forwardName[i] == '\'') {
inString = true;
curToken += forwardName[i];
} else {
curToken += forwardName[i];
}
}
if (!curToken.empty()) {
tokens.push_back(curToken);
}
for (size_t i = tokens.size(); i > 0;) {
i--;
if (!name.empty()) {
name += " + ";
}
if (starts_with(tokens[i], INVERSE_OF)) {
name += tokens[i].substr(INVERSE_OF.size());
} else if (tokens[i] == AXIS_ORDER_CHANGE_2D_NAME ||
tokens[i] == AXIS_ORDER_CHANGE_3D_NAME) {
name += tokens[i];
} else {
name += INVERSE_OF + tokens[i];
}
}
} else if (!sourceCRS || !targetCRS ||
forwardName != buildOpName(opType, sourceCRS, targetCRS)) {
if (forwardName.find(" + ") != std::string::npos) {
name = INVERSE_OF + '\'' + forwardName + '\'';
} else {
name = INVERSE_OF + forwardName;
}
}
}
if (name.empty() && sourceCRS && targetCRS) {
name = buildOpName(opType, targetCRS, sourceCRS);
}
if (approximateInversion) {
name += " (approx. inversion)";
}
if (!name.empty()) {
map.set(common::IdentifiedObject::NAME_KEY, name);
}
const std::string &remarks = op->remarks();
if (!remarks.empty()) {
map.set(common::IdentifiedObject::REMARKS_KEY, remarks);
}
addModifiedIdentifier(map, op, true, derivedFrom);
const auto so = dynamic_cast<const SingleOperation *>(op);
if (so) {
const int soMethodEPSGCode = so->method()->getEPSGCode();
if (soMethodEPSGCode > 0) {
map.set("OPERATION_METHOD_EPSG_CODE", soMethodEPSGCode);
}
}
return map;
}
// ---------------------------------------------------------------------------
util::PropertyMap addDefaultNameIfNeeded(const util::PropertyMap &properties,
const std::string &defaultName) {
if (!properties.get(common::IdentifiedObject::NAME_KEY)) {
return util::PropertyMap(properties)
.set(common::IdentifiedObject::NAME_KEY, defaultName);
} else {
return properties;
}
}
// ---------------------------------------------------------------------------
static std::string createEntryEqParam(const std::string &a,
const std::string &b) {
return a < b ? a + b : b + a;
}
static std::set<std::string> buildSetEquivalentParameters() {
std::set<std::string> set;
const char *const listOfEquivalentParameterNames[][7] = {
{"latitude_of_point_1", "Latitude_Of_1st_Point", nullptr},
{"longitude_of_point_1", "Longitude_Of_1st_Point", nullptr},
{"latitude_of_point_2", "Latitude_Of_2nd_Point", nullptr},
{"longitude_of_point_2", "Longitude_Of_2nd_Point", nullptr},
{"satellite_height", "height", nullptr},
{EPSG_NAME_PARAMETER_FALSE_EASTING,
EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN,
EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, nullptr},
{EPSG_NAME_PARAMETER_FALSE_NORTHING,
EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN,
EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, nullptr},
{EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR,
EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE,
EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, nullptr},
{WKT1_LATITUDE_OF_ORIGIN, WKT1_LATITUDE_OF_CENTER,
EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN,
EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN,
EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, "Central_Parallel",
nullptr},
{WKT1_CENTRAL_MERIDIAN, WKT1_LONGITUDE_OF_CENTER,
EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN,
EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN,
EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE,
EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, nullptr},
{"pseudo_standard_parallel_1", WKT1_STANDARD_PARALLEL_1, nullptr},
};
for (const auto ¶mList : listOfEquivalentParameterNames) {
for (size_t i = 0; paramList[i]; i++) {
auto a = metadata::Identifier::canonicalizeName(paramList[i]);
for (size_t j = i + 1; paramList[j]; j++) {
auto b = metadata::Identifier::canonicalizeName(paramList[j]);
set.insert(createEntryEqParam(a, b));
}
}
}
return set;
}
bool areEquivalentParameters(const std::string &a, const std::string &b) {
static const std::set<std::string> setEquivalentParameters =
buildSetEquivalentParameters();
auto a_can = metadata::Identifier::canonicalizeName(a);
auto b_can = metadata::Identifier::canonicalizeName(b);
return setEquivalentParameters.find(createEntryEqParam(a_can, b_can)) !=
setEquivalentParameters.end();
}
// ---------------------------------------------------------------------------
bool isTimeDependent(const std::string &methodName) {
return ci_find(methodName, "Time dependent") != std::string::npos ||
ci_find(methodName, "Time-dependent") != std::string::npos;
}
// ---------------------------------------------------------------------------
std::string computeConcatenatedName(
const std::vector<CoordinateOperationNNPtr> &flattenOps) {
std::string name;
for (const auto &subOp : flattenOps) {
if (!name.empty()) {
name += " + ";
}
const auto &l_name = subOp->nameStr();
if (l_name.empty()) {
name += "unnamed";
} else {
name += l_name;
}
}
return name;
}
// ---------------------------------------------------------------------------
metadata::ExtentPtr getExtent(const CoordinateOperationNNPtr &op,
bool conversionExtentIsWorld,
bool &emptyIntersection) {
auto conv = dynamic_cast<const Conversion *>(op.get());
if (conv) {
emptyIntersection = false;
return metadata::Extent::WORLD;
}
const auto &domains = op->domains();
if (!domains.empty()) {
emptyIntersection = false;
return domains[0]->domainOfValidity();
}
auto concatenated = dynamic_cast<const ConcatenatedOperation *>(op.get());
if (!concatenated) {
emptyIntersection = false;
return nullptr;
}
return getExtent(concatenated->operations(), conversionExtentIsWorld,
emptyIntersection);
}
// ---------------------------------------------------------------------------
static const metadata::ExtentPtr nullExtent{};
const metadata::ExtentPtr &getExtent(const crs::CRSNNPtr &crs) {
const auto &domains = crs->domains();
if (!domains.empty()) {
return domains[0]->domainOfValidity();
}
const auto *boundCRS = dynamic_cast<const crs::BoundCRS *>(crs.get());
if (boundCRS) {
return getExtent(boundCRS->baseCRS());
}
return nullExtent;
}
const metadata::ExtentPtr getExtentPossiblySynthetized(const crs::CRSNNPtr &crs,
bool &approxOut) {
const auto &rawExtent(getExtent(crs));
approxOut = false;
if (rawExtent)
return rawExtent;
const auto compoundCRS = dynamic_cast<const crs::CompoundCRS *>(crs.get());
if (compoundCRS) {
// For a compoundCRS, take the intersection of the extent of its
// components.
const auto &components = compoundCRS->componentReferenceSystems();
metadata::ExtentPtr extent;
approxOut = true;
for (const auto &component : components) {
const auto &componentExtent(getExtent(component));
if (extent && componentExtent)
extent = extent->intersection(NN_NO_CHECK(componentExtent));
else if (componentExtent)
extent = componentExtent;
}
return extent;
}
return rawExtent;
}
// ---------------------------------------------------------------------------
metadata::ExtentPtr getExtent(const std::vector<CoordinateOperationNNPtr> &ops,
bool conversionExtentIsWorld,
bool &emptyIntersection) {
metadata::ExtentPtr res = nullptr;
for (const auto &subop : ops) {
const auto &subExtent =
getExtent(subop, conversionExtentIsWorld, emptyIntersection);
if (!subExtent) {
if (emptyIntersection) {
return nullptr;
}
continue;
}
if (res == nullptr) {
res = subExtent;
} else {
res = res->intersection(NN_NO_CHECK(subExtent));
if (!res) {
emptyIntersection = true;
return nullptr;
}
}
}
emptyIntersection = false;
return res;
}
// ---------------------------------------------------------------------------
// Returns the accuracy of an operation, or -1 if unknown
double getAccuracy(const CoordinateOperationNNPtr &op) {
if (dynamic_cast<const Conversion *>(op.get())) {
// A conversion is perfectly accurate.
return 0.0;
}
double accuracy = -1.0;
const auto &accuracies = op->coordinateOperationAccuracies();
if (!accuracies.empty()) {
try {
accuracy = c_locale_stod(accuracies[0]->value());
} catch (const std::exception &) {
}
} else {
auto concatenated =
dynamic_cast<const ConcatenatedOperation *>(op.get());
if (concatenated) {
accuracy = getAccuracy(concatenated->operations());
}
}
return accuracy;
}
// ---------------------------------------------------------------------------
// Returns the accuracy of a set of concatenated operations, or -1 if unknown
double getAccuracy(const std::vector<CoordinateOperationNNPtr> &ops) {
double accuracy = -1.0;
for (const auto &subop : ops) {
const double subops_accuracy = getAccuracy(subop);
if (subops_accuracy < 0.0) {
return -1.0;
}
if (accuracy < 0.0) {
accuracy = 0.0;
}
accuracy += subops_accuracy;
}
return accuracy;
}
// ---------------------------------------------------------------------------
void exportSourceCRSAndTargetCRSToWKT(const CoordinateOperation *co,
io::WKTFormatter *formatter) {
auto l_sourceCRS = co->sourceCRS();
assert(l_sourceCRS);
auto l_targetCRS = co->targetCRS();
assert(l_targetCRS);
const bool isWKT2 = formatter->version() == io::WKTFormatter::Version::WKT2;
const bool canExportCRSId =
(isWKT2 && formatter->use2019Keywords() &&
!(formatter->idOnTopLevelOnly() && formatter->topLevelHasId()));
const bool hasDomains = !co->domains().empty();
if (hasDomains) {
formatter->pushDisableUsage();
}
formatter->startNode(io::WKTConstants::SOURCECRS, false);
if (canExportCRSId && !l_sourceCRS->identifiers().empty()) {
// fake that top node has no id, so that the sourceCRS id is
// considered
formatter->pushHasId(false);
l_sourceCRS->_exportToWKT(formatter);
formatter->popHasId();
} else {
l_sourceCRS->_exportToWKT(formatter);
}
formatter->endNode();
formatter->startNode(io::WKTConstants::TARGETCRS, false);
if (canExportCRSId && !l_targetCRS->identifiers().empty()) {
// fake that top node has no id, so that the targetCRS id is
// considered
formatter->pushHasId(false);
l_targetCRS->_exportToWKT(formatter);
formatter->popHasId();
} else {
l_targetCRS->_exportToWKT(formatter);
}
formatter->endNode();
if (hasDomains) {
formatter->popDisableUsage();
}
}
//! @endcond
// ---------------------------------------------------------------------------
} // namespace operation
NS_PROJ_END
| 35.586957 | 80 | 0.555459 | [
"vector"
] |
dcc2c26f9803e6aea170121c45db8977b800ea44 | 10,238 | hpp | C++ | contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | // ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY 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.
//
// FlexibleSUSY 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 FlexibleSUSY. If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================
// File generated at Sat 27 Aug 2016 12:47:55
#ifndef NUHMSSM_SLHA_IO_H
#define NUHMSSM_SLHA_IO_H
#include "NUHMSSM_two_scale_model_slha.hpp"
#include "NUHMSSM_info.hpp"
#include "NUHMSSM_observables.hpp"
#include "NUHMSSM_physical.hpp"
#include "slha_io.hpp"
#include "ckm.hpp"
#include "ew_input.hpp"
#include "lowe.h"
#include <Eigen/Core>
#include <string>
#include <utility>
#define Pole(p) physical.p
#define PHYSICAL(p) model.get_physical().p
#define PHYSICAL_SLHA(p) model.get_physical_slha().p
#define LOCALPHYSICAL(p) physical.p
#define MODEL model
#define MODELPARAMETER(p) model.get_##p()
#define OBSERVABLES observables
#define LowEnergyConstant(p) Electroweak_constants::p
#define SCALES(p) scales.p
namespace flexiblesusy {
struct NUHMSSM_input_parameters;
class Spectrum_generator_settings;
struct NUHMSSM_scales {
NUHMSSM_scales() : HighScale(0.), SUSYScale(0.), LowScale(0.) {}
double HighScale, SUSYScale, LowScale;
};
class NUHMSSM_slha_io {
public:
NUHMSSM_slha_io();
~NUHMSSM_slha_io() {}
void clear();
void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }
void fill(NUHMSSM_input_parameters&) const;
void fill(NUHMSSM_mass_eigenstates&) const;
template <class T> void fill(NUHMSSM_slha<T>&) const;
void fill(Physical_input&) const;
void fill(Spectrum_generator_settings&) const;
double get_parameter_output_scale() const;
const SLHA_io& get_slha_io() const { return slha_io; }
void read_from_file(const std::string&);
void read_from_source(const std::string&);
void read_from_stream(std::istream&);
void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }
void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }
void set_extpar(const NUHMSSM_input_parameters&);
template <class T> void set_extra(const NUHMSSM_slha<T>&, const NUHMSSM_scales&, const NUHMSSM_observables&);
void set_minpar(const NUHMSSM_input_parameters&);
void set_sminputs(const softsusy::QedQcd&);
template <class T> void set_spectrum(const NUHMSSM_slha<T>&);
template <class T> void set_spectrum(const NUHMSSM<T>&);
void set_spinfo(const Problems<NUHMSSM_info::NUMBER_OF_PARTICLES>&);
void set_print_imaginary_parts_of_majorana_mixings(bool);
void write_to_file(const std::string&);
void write_to_stream(std::ostream& ostr = std::cout) { slha_io.write_to_stream(ostr); }
static void fill_minpar_tuple(NUHMSSM_input_parameters&, int, double);
static void fill_extpar_tuple(NUHMSSM_input_parameters&, int, double);
template <class T>
static void fill_slhaea(SLHAea::Coll&, const NUHMSSM_slha<T>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);
template <class T>
static SLHAea::Coll fill_slhaea(const NUHMSSM_slha<T>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);
private:
SLHA_io slha_io; ///< SLHA io class
bool print_imaginary_parts_of_majorana_mixings;
static unsigned const NUMBER_OF_DRBAR_BLOCKS = 14;
static char const * const drbar_blocks[NUMBER_OF_DRBAR_BLOCKS];
void set_mass(const NUHMSSM_physical&, bool);
void set_mixing_matrices(const NUHMSSM_physical&, bool);
template <class T> void set_model_parameters(const NUHMSSM_slha<T>&);
void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);
void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);
double read_scale() const;
void fill_drbar_parameters(NUHMSSM_mass_eigenstates&) const;
void fill_physical(NUHMSSM_physical&) const;
};
/**
* Reads DR-bar parameters, pole masses and mixing matrices from a
* SLHA output file.
*/
template <class T>
void NUHMSSM_slha_io::fill(NUHMSSM_slha<T>& model) const
{
fill(static_cast<NUHMSSM_mass_eigenstates&>(model));
fill_physical(model.get_physical_slha());
}
template <class T>
void NUHMSSM_slha_io::fill_slhaea(
SLHAea::Coll& slhaea, const NUHMSSM_slha<T>& model,
const softsusy::QedQcd& qedqcd, const NUHMSSM_scales& scales,
const NUHMSSM_observables& observables)
{
NUHMSSM_slha_io slha_io;
const NUHMSSM_input_parameters& input = model.get_input();
const Problems<NUHMSSM_info::NUMBER_OF_PARTICLES>& problems
= model.get_problems();
const bool error = problems.have_problem();
slha_io.set_spinfo(problems);
slha_io.set_sminputs(qedqcd);
slha_io.set_minpar(input);
slha_io.set_extpar(input);
if (!error) {
slha_io.set_spectrum(model);
slha_io.set_extra(model, scales, observables);
}
slhaea = slha_io.get_slha_io().get_data();
}
template <class T>
SLHAea::Coll NUHMSSM_slha_io::fill_slhaea(
const NUHMSSM_slha<T>& model, const softsusy::QedQcd& qedqcd,
const NUHMSSM_scales& scales, const NUHMSSM_observables& observables)
{
SLHAea::Coll slhaea;
NUHMSSM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);
return slhaea;
}
/**
* Stores the model (DR-bar) parameters in the SLHA object.
*
* @param model model class
*/
template <class T>
void NUHMSSM_slha_io::set_model_parameters(const NUHMSSM_slha<T>& model)
{
{
std::ostringstream block;
block << "Block gauge Q= " << FORMAT_SCALE(model.get_scale()) << '\n'
<< FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), "gY")
<< FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), "g2")
<< FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), "g3")
;
slha_io.set_block(block);
}
slha_io.set_block("Yu", ToMatrix(MODELPARAMETER(Yu_slha)), "Yu", model.get_scale());
slha_io.set_block("Yd", ToMatrix(MODELPARAMETER(Yd_slha)), "Yd", model.get_scale());
slha_io.set_block("Ye", ToMatrix(MODELPARAMETER(Ye_slha)), "Ye", model.get_scale());
slha_io.set_block("Te", MODELPARAMETER(TYe_slha), "TYe", model.get_scale());
slha_io.set_block("Td", MODELPARAMETER(TYd_slha), "TYd", model.get_scale());
slha_io.set_block("Tu", MODELPARAMETER(TYu_slha), "TYu", model.get_scale());
{
std::ostringstream block;
block << "Block HMIX Q= " << FORMAT_SCALE(model.get_scale()) << '\n'
<< FORMAT_ELEMENT(1, (MODELPARAMETER(Mu)), "Mu")
<< FORMAT_ELEMENT(101, (MODELPARAMETER(BMu)), "BMu")
<< FORMAT_ELEMENT(102, (MODELPARAMETER(vd)), "vd")
<< FORMAT_ELEMENT(103, (MODELPARAMETER(vu)), "vu")
;
slha_io.set_block(block);
}
slha_io.set_block("MSQ2", MODELPARAMETER(mq2_slha), "mq2", model.get_scale());
slha_io.set_block("MSE2", MODELPARAMETER(me2_slha), "me2", model.get_scale());
slha_io.set_block("MSL2", MODELPARAMETER(ml2_slha), "ml2", model.get_scale());
slha_io.set_block("MSU2", MODELPARAMETER(mu2_slha), "mu2", model.get_scale());
slha_io.set_block("MSD2", MODELPARAMETER(md2_slha), "md2", model.get_scale());
{
std::ostringstream block;
block << "Block MSOFT Q= " << FORMAT_SCALE(model.get_scale()) << '\n'
<< FORMAT_ELEMENT(21, (MODELPARAMETER(mHd2)), "mHd2")
<< FORMAT_ELEMENT(22, (MODELPARAMETER(mHu2)), "mHu2")
<< FORMAT_ELEMENT(1, (MODELPARAMETER(MassB)), "MassB")
<< FORMAT_ELEMENT(2, (MODELPARAMETER(MassWB)), "MassWB")
<< FORMAT_ELEMENT(3, (MODELPARAMETER(MassG)), "MassG")
;
slha_io.set_block(block);
}
{
std::ostringstream block;
block << "Block Phases Q= " << FORMAT_SCALE(model.get_scale()) << '\n'
<< FORMAT_ELEMENT(1, (Re(MODELPARAMETER(PhaseGlu))), "Re(PhaseGlu)")
;
slha_io.set_block(block);
}
{
std::ostringstream block;
block << "Block IMPhases Q= " << FORMAT_SCALE(model.get_scale()) << '\n'
<< FORMAT_ELEMENT(1, (Im(MODELPARAMETER(PhaseGlu))), "Im(PhaseGlu)")
;
slha_io.set_block(block);
}
}
/**
* Writes extra SLHA blocks
*
* @param model model class
*/
template <class T>
void NUHMSSM_slha_io::set_extra(
const NUHMSSM_slha<T>& model, const NUHMSSM_scales& scales,
const NUHMSSM_observables& observables)
{
const NUHMSSM_physical physical(model.get_physical_slha());
}
/**
* Stores the model (DR-bar) parameters, masses and mixing matrices in
* the SLHA object.
*
* @param model model class in BPMZ convention
*/
template <class T>
void NUHMSSM_slha_io::set_spectrum(const NUHMSSM<T>& model)
{
const NUHMSSM_slha<T> model_slha(model);
set_spectrum(model_slha);
}
/**
* Stores the model (DR-bar) parameters, masses and mixing matrices in
* the SLHA object.
*
* @param model model class in SLHA convention
*/
template <class T>
void NUHMSSM_slha_io::set_spectrum(const NUHMSSM_slha<T>& model)
{
const NUHMSSM_physical physical(model.get_physical_slha());
const bool write_sm_masses = model.do_calculate_sm_pole_masses();
set_model_parameters(model);
set_mass(physical, write_sm_masses);
set_mixing_matrices(physical, write_sm_masses);
if (slha_io.get_modsel().quark_flavour_violated)
set_ckm(model.get_ckm_matrix(), model.get_scale());
if (slha_io.get_modsel().lepton_flavour_violated)
set_pmns(model.get_pmns_matrix(), model.get_scale());
}
} // namespace flexiblesusy
#undef Pole
#undef PHYSICAL
#undef PHYSICAL_SLHA
#undef LOCALPHYSICAL
#undef MODEL
#undef MODELPARAMETER
#undef OBSERVABLES
#undef LowEnergyConstant
#undef SCALES
#endif
| 35.303448 | 142 | 0.705802 | [
"object",
"vector",
"model"
] |
dcc36b1a8557cf30ac030302fcb7545da55c7886 | 12,988 | cc | C++ | vendor/github.com/tensorflow/tensorflow/tensorflow/tools/graph_transforms/fold_constants_lib.cc | owennewo/kfserving | 89f73c87525b8e06ea799f69f2979c4ad272fcb3 | [
"Apache-2.0"
] | 5 | 2019-01-13T16:15:25.000Z | 2019-07-07T16:17:32.000Z | tensorflow/tools/graph_transforms/fold_constants_lib.cc | shekharpalit/tensorflow | 6aa83398ab03bfae822f36772757097bcb98b6ed | [
"Apache-2.0"
] | 13 | 2020-11-13T18:53:29.000Z | 2022-03-12T00:33:00.000Z | tensorflow/tools/graph_transforms/fold_constants_lib.cc | shekharpalit/tensorflow | 6aa83398ab03bfae822f36772757097bcb98b6ed | [
"Apache-2.0"
] | 6 | 2018-11-29T20:52:00.000Z | 2021-02-19T22:43:32.000Z | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/tools/graph_transforms/fold_constants_lib.h"
#include <algorithm>
#include <iterator>
#include <map>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/common_runtime/shape_refiner.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
namespace {
using StringPieceSet = std::unordered_set<StringPiece, StringPieceHasher>;
template <typename T>
using StringPieceMap = std::unordered_map<StringPiece, T, StringPieceHasher>;
} // namespace
Status ReplaceSendRecvs(const GraphDef& original_graph_def,
const GraphDef& rewritten_graph_def,
const std::vector<string>& inputs,
const std::vector<string>& outputs,
GraphDef* output_graph_def) {
// recv_node_names serves as a string storage for recv node names.
std::vector<string> recv_node_names(inputs.size());
StringPieceMap<TensorId> recv_node_map;
StringPieceSet input_nodes;
for (int i = 0; i < inputs.size(); ++i) {
// RewriteGraphForExecution adds a recv node for each input edge. We assume
// here that adding such recv node did not fail. For example, the original
// graph did not already have a node with the name for the new added recv
// node.
TensorId id = ParseTensorName(inputs[i]);
input_nodes.insert(id.first);
string& recv_node_name = recv_node_names[i];
recv_node_name = strings::StrCat("_recv_", id.first, "_", id.second);
recv_node_map.emplace(recv_node_name, id);
}
StringPieceMap<const NodeDef*> original_map;
for (const NodeDef& node : original_graph_def.node()) {
original_map.emplace(node.name(), &node);
}
for (const NodeDef& node : rewritten_graph_def.node()) {
if ((node.op() == "_Send") || (node.op() == "_Recv")) {
// If the op is a Send or Recv that wasn't in the original, skip it.
if (original_map.count(node.name()) == 0) {
continue;
}
}
NodeDef* new_node = output_graph_def->add_node();
new_node->MergeFrom(node);
for (int i = 0; i < new_node->input_size(); ++i) {
string& input = *new_node->mutable_input(i);
TensorId id = ParseTensorName(input);
const auto iter = recv_node_map.find(id.first);
if (iter != recv_node_map.end()) {
// The node being substituted is a Recv node, and it has only one
// output. If this input is not a control input, then replace the input
// with the mapped value. Otherwise, replace the node name only.
if (id.second != Graph::kControlSlot) {
CHECK_EQ(id.second, 0);
input = iter->second.ToString();
} else {
id.first = iter->second.first;
input = id.ToString();
}
}
}
// RewriteGraphForExecution() did not remove this input node. Remove this
// node name from input_nodes so that a duplicate does not get added to the
// output_graph_def.
auto iter = input_nodes.find(new_node->name());
if (iter != input_nodes.end()) {
input_nodes.erase(iter);
}
}
// Some input nodes are removed in rewrite_graph_def. Add those nodes to
// output_graph_def.
for (StringPiece name : input_nodes) {
const NodeDef& removed_node = *CHECK_NOTNULL(original_map[name]);
output_graph_def->add_node()->MergeFrom(removed_node);
}
return Status::OK();
}
Status RewriteInputsAsPlaceholders(const TransformFuncContext& context,
GraphDef* graph_def) {
std::unordered_set<string> input_names;
for (const string& input_name : context.input_names) {
input_names.emplace(ParseTensorName(input_name).first);
}
for (NodeDef& node : *graph_def->mutable_node()) {
if (input_names.find(node.name()) == input_names.end()) {
continue;
}
if (node.op() == "PlaceholderWithDefault") {
node.set_op("Placeholder");
node.clear_input();
} else if (node.op() != "Placeholder") {
return errors::InvalidArgument(
"Input '", node.name(),
"' was expected to be a Placeholder or PlaceholderWithDefault op, "
"but was ",
node.op());
}
}
return Status::OK();
}
Status RemoveUnusedNodes(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
StringPieceMap<const NodeDef*> node_map;
for (const NodeDef& node : input_graph_def.node()) {
node_map.emplace(node.name(), &node);
}
std::unordered_set<TensorId, TensorId::Hasher> input_names;
for (const string& input : context.input_names) {
input_names.insert(ParseTensorName(input));
}
StringPieceSet used_nodes;
StringPieceSet current_nodes;
for (const string& name : context.output_names) {
TensorId id = ParseTensorName(name);
used_nodes.insert(id.first);
current_nodes.insert(id.first);
}
while (!current_nodes.empty()) {
StringPieceSet next_nodes;
for (StringPiece node_name : current_nodes) {
if (node_map.count(node_name) == 0) {
LOG(ERROR) << "Bad graph structure, no node named '" << node_name
<< "' found for input lookup";
return errors::InvalidArgument("Bad graph structure, no node named '",
node_name, "' found for input lookup");
}
const NodeDef& node = *(node_map[node_name]);
for (const string& input : node.input()) {
TensorId id = ParseTensorName(input);
if (input_names.count(id) > 0) {
continue;
}
if (used_nodes.insert(id.first).second) {
next_nodes.insert(id.first);
}
}
}
current_nodes.swap(next_nodes);
}
for (const TensorId& id : input_names) {
used_nodes.insert(id.first);
}
FilterGraphDef(
input_graph_def,
[&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },
output_graph_def);
TF_RETURN_IF_ERROR(RewriteInputsAsPlaceholders(context, output_graph_def));
return Status::OK();
}
// Converts a shape inference handle to a PartialTensorShape.
Status ShapeHandleToTensorShape(const shape_inference::ShapeHandle& handle,
shape_inference::InferenceContext* context,
PartialTensorShape* shape) {
// The default is already unknown.
if (!context->RankKnown(handle)) return Status::OK();
std::vector<int64> dims(context->Rank(handle));
for (int32 i = 0; i < dims.size(); ++i) {
dims[i] = context->Value(context->Dim(handle, i));
}
return PartialTensorShape::MakePartialShape(dims.data(), dims.size(), shape);
}
// Converts any sub-graphs that can be resolved into constant expressions into
// single Const ops.
Status FoldConstants(const GraphDef& input_graph_def,
const TransformFuncContext& context,
GraphDef* output_graph_def) {
Graph input_graph(OpRegistry::Global());
TF_RETURN_IF_ERROR(input_graph.AddFunctionLibrary(input_graph_def.library()));
ShapeRefiner shape_refiner(input_graph.versions(), input_graph.op_registry());
shape_refiner.set_require_shape_inference_fns(false);
shape_refiner.set_disable_constant_propagation(false);
shape_refiner.set_function_library_for_shape_inference(
&input_graph.flib_def());
bool clear_output_shapes;
TF_RETURN_IF_ERROR(context.GetOneBoolParameter("clear_output_shapes", true,
&clear_output_shapes));
if (clear_output_shapes) {
// Some older GraphDefs have saved _output_shapes attributes which are out
// of date and cause import errors, so clean them up first.
GraphDef cleaned_graph_def;
RemoveAttributes(input_graph_def, {"_output_shapes"}, &cleaned_graph_def);
TF_RETURN_IF_ERROR(
ImportGraphDef({}, cleaned_graph_def, &input_graph, &shape_refiner));
} else {
TF_RETURN_IF_ERROR(
ImportGraphDef({}, input_graph_def, &input_graph, &shape_refiner));
}
// Sorted array of input names as lookup table.
std::vector<TensorId> input_names;
input_names.reserve(context.input_names.size());
std::transform(context.input_names.begin(), context.input_names.end(),
std::back_inserter(input_names),
[](const string& name) { return ParseTensorName(name); });
const auto compare = [](TensorId lhs, TensorId rhs) {
return lhs.first < rhs.first;
};
std::sort(input_names.begin(), input_names.end(), compare);
// Set statically inferred shapes.
std::unordered_map<string, std::vector<PartialTensorShape>> shape_map;
for (const Node* const node : input_graph.nodes()) {
auto ctx = shape_refiner.GetContext(node);
if (ctx == nullptr) {
continue;
}
std::vector<PartialTensorShape>& partial_shapes = shape_map[node->name()];
if (ctx->num_outputs() <= 0) continue;
partial_shapes.resize(ctx->num_outputs());
// Check all outputs.
for (const Edge* out_edge : node->out_edges()) {
if (out_edge->IsControlEdge()) continue;
const int output_idx = out_edge->src_output();
TF_RETURN_IF_ERROR(ShapeHandleToTensorShape(ctx->output(output_idx), ctx,
&partial_shapes[output_idx]));
}
// RewriteGraphForExecution() will add a Recv node for each input. Shape
// refiner does not include shape information of these Recv nodes. Therefore
// we add entries for Recv nodes here.
const auto pair = std::equal_range(input_names.begin(), input_names.end(),
TensorId{node->name(), 0}, compare);
for (auto it = pair.first; it != pair.second; ++it) {
const string recv_name =
strings::StrCat("_recv_", it->first, "_", it->second);
auto& recv_partial_shapes = shape_map[recv_name];
// For whatever reason (for example, name collision) if the map entry was
// already there, then do nothing.
if (recv_partial_shapes.empty()) {
recv_partial_shapes.push_back(partial_shapes[it->second]);
}
}
}
subgraph::RewriteGraphMetadata unused_metadata;
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
&input_graph, context.input_names, context.output_names, {}, {},
false /* use_function_convention */, &unused_metadata));
ConstantFoldingOptions cf_opts;
cf_opts.shape_map = &shape_map;
// Exclude specified nodes from constant folding.
if (context.params.count("exclude_op") > 0) {
const auto& excluded_nodes = context.params.at("exclude_op");
const std::set<string> excluded_nodes_set(excluded_nodes.begin(),
excluded_nodes.end());
cf_opts.consider = [excluded_nodes_set](const Node* n) {
return excluded_nodes_set.find(n->op_def().name()) ==
excluded_nodes_set.end();
};
}
TF_RETURN_IF_ERROR(context.GetOneInt64Parameter(
"max_constant_size_in_bytes", cf_opts.max_constant_size_in_bytes,
&cf_opts.max_constant_size_in_bytes));
// Constant folding.
bool was_mutated;
TF_RETURN_IF_ERROR(ConstantFold(cf_opts, nullptr, Env::Default(), nullptr,
&input_graph, &was_mutated));
GraphDef folded_graph_def;
input_graph.ToGraphDef(&folded_graph_def);
GraphDef send_recvs_replaced;
TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def,
context.input_names, context.output_names,
&send_recvs_replaced));
TF_RETURN_IF_ERROR(
RemoveUnusedNodes(send_recvs_replaced, context, output_graph_def));
return Status::OK();
}
REGISTER_GRAPH_TRANSFORM("fold_constants", FoldConstants);
} // namespace graph_transforms
} // namespace tensorflow
| 38.886228 | 80 | 0.669002 | [
"shape",
"vector",
"transform"
] |
dcc93f4c2ac83947bd5cac72b429a1f1485c6967 | 655 | cpp | C++ | lecture19/vector_ex2.cpp | jamesmtuck/ncstate_ece309_fall2021 | bdf7df74ed20aa86a31e04a35b3c723a1751a439 | [
"MIT"
] | null | null | null | lecture19/vector_ex2.cpp | jamesmtuck/ncstate_ece309_fall2021 | bdf7df74ed20aa86a31e04a35b3c723a1751a439 | [
"MIT"
] | null | null | null | lecture19/vector_ex2.cpp | jamesmtuck/ncstate_ece309_fall2021 | bdf7df74ed20aa86a31e04a35b3c723a1751a439 | [
"MIT"
] | 2 | 2021-09-13T03:00:31.000Z | 2021-10-20T06:16:15.000Z | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v(5, 0); // declare a vector with 5 zeros already inserted
// print them out, all five zeros
for (int i = 0; i < v.size(); i++)
cout << v[i] << " "; // O(1) access using array notation
cout << endl;
v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; // modify contents using operator[]
v.resize(10,-1); // O(n), make array of length 10, put -1 in new spots
for(int j=0; j<10000000; j++)
for (int i = 0; i < v.size(); i++)
v[i]; //cout << v[i] << " "; // prints: 0 1 2 3 4 -1 -1 -1 -1 -1
// vector< vector<int> > twoDvector;
return 0;
}
| 24.259259 | 77 | 0.541985 | [
"vector"
] |
dcd093a369ae548c3677f2dcb8f344b278fbc069 | 10,137 | cpp | C++ | libraries/I2C/EEPROM24.cpp | kotl/esp8266-arduinolibs | a4683416ff0773ee85d538d1f6a648b9d0523c8c | [
"MIT"
] | 23 | 2018-04-21T16:24:47.000Z | 2022-02-24T15:59:12.000Z | libraries/I2C/EEPROM24.cpp | kotl/esp8266-arduinolibs | a4683416ff0773ee85d538d1f6a648b9d0523c8c | [
"MIT"
] | 2 | 2021-01-14T14:07:24.000Z | 2021-07-21T05:47:40.000Z | libraries/I2C/EEPROM24.cpp | kotl/esp8266-arduinolibs | a4683416ff0773ee85d538d1f6a648b9d0523c8c | [
"MIT"
] | 19 | 2018-12-03T10:20:52.000Z | 2022-02-04T13:47:35.000Z | /*
* Copyright (C) 2012 Southern Storm Software, Pty Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "EEPROM24.h"
#include "I2CMaster.h"
/**
* \class EEPROM24 EEPROM24.h <EEPROM24.h>
* \brief Reading and writing EEPROM's from the 24LCXX family.
*
* The 24LCXX family of EEPROM's provide a variety of memory sizes from
* 16 bytes up to 128 kBytes that can be accessed via the I2C protocol.
* These chips can be used to augment the 1 kByte or so of builtin EEPROM
* memory that is typical on Arduino boards. The EEPROM should be wired
* to an Arduino Uno as follows:
*
* \image html eeprom_circuit.png
*
* Access to a 24LCXX chip is initialized as follows:
*
* \code
* SoftI2C i2c(A4, A5);
* EEPROM24 eeprom(i2c, EEPROM_24LC256);
* \endcode
*
* Once initialized, read() and write() can be used to manipulate the
* contents of the EEPROM's memory.
*
* The following EEPROM types are supported by this class:
*
* <table>
* <tr><td>Chip</td><td>Type</td><td>Size</td></tr>
* <tr><td>24lc00</td><td>\c EEPROM_24LC00</td><td>16 bytes</td></tr>
* <tr><td>24lc01</td><td>\c EEPROM_24LC01</td><td>128 bytes</td></tr>
* <tr><td>24lc014</td><td>\c EEPROM_24LC014</td><td>128 bytes</td></tr>
* <tr><td>24lc02</td><td>\c EEPROM_24LC02</td><td>256 bytes</td></tr>
* <tr><td>24lc024</td><td>\c EEPROM_24LC024</td><td>256 bytes</td></tr>
* <tr><td>24lc025</td><td>\c EEPROM_24LC025</td><td>256 bytes</td></tr>
* <tr><td>24lc04</td><td>\c EEPROM_24LC04</td><td>512 bytes</td></tr>
* <tr><td>24lc08</td><td>\c EEPROM_24LC08</td><td>1 kByte</td></tr>
* <tr><td>24lc16</td><td>\c EEPROM_24LC16</td><td>2 kBytes</td></tr>
* <tr><td>24lc32</td><td>\c EEPROM_24LC32</td><td>4 kBytes</td></tr>
* <tr><td>24lc64</td><td>\c EEPROM_24LC64</td><td>8 kBytes</td></tr>
* <tr><td>24lc128</td><td>\c EEPROM_24LC128</td><td>16 kBytes</td></tr>
* <tr><td>24lc256</td><td>\c EEPROM_24LC256</td><td>32 kBytes</td></tr>
* <tr><td>24lc512</td><td>\c EEPROM_24LC512</td><td>64 kBytes</td></tr>
* <tr><td>24lc1025</td><td>\c EEPROM_24LC1025</td><td>128 kBytes</td></tr>
* <tr><td>24lc1026</td><td>\c EEPROM_24LC1026</td><td>128 kBytes</td></tr>
* </table>
*
* There can be multiple 24LCXX chips on the same I2C bus, as long as their
* A0, A1, and A2 address pins are set to different values. For example,
* two 24LC256 chips can be used to provide the same memory capacity as a
* single 24LC512 chip. The optional <i>bank</i> parameter to the constructor
* is used to assign different bank addresses to each chip:
*
* \code
* SoftI2C i2c(A4, A5);
* EEPROM24 eeprom0(i2c, EEPROM_24LC256, 0);
* EEPROM24 eeprom1(i2c, EEPROM_24LC256, 1);
* \endcode
*
* \sa I2CMaster
*/
/**
* \brief Constructs a new EEPROM access object on \a bus for an EEPROM
* of the specified \a type.
*
* The \a bank can be used to choose between multiple EEPROM's on
* \a bus of the specified \a type. The \a bank corresponds to the value
* that is set on the EEPROM's A0, A1, and A2 address pins. Note that
* some EEPROM's have less than 3 address pins; consult the datasheet
* for more information.
*/
EEPROM24::EEPROM24(I2CMaster &bus, unsigned long type, uint8_t bank)
: _bus(&bus)
, _size((type & 0xFFFF) * ((type >> 16) & 0x0FFF))
, _pageSize((type >> 16) & 0x0FFF)
, _mode((uint8_t)((type >> 28) & 0x0F))
, i2cAddress(0x50)
{
// Adjust the I2C address for the memory bank of the chip.
switch (_mode) {
case EE_BSEL_NONE:
i2cAddress += (bank & 0x07);
break;
case EE_BSEL_8BIT_ADDR: {
uint8_t addrBits = 8;
unsigned long size = 0x0100;
while (size < _size) {
++addrBits;
size <<= 1;
}
if (addrBits < 11)
i2cAddress += ((bank << (addrBits - 8)) & 0x07);
break; }
case EE_BSEL_17BIT_ADDR:
i2cAddress += ((bank << 1) & 0x06);
break;
case EE_BSEL_17BIT_ADDR_ALT:
i2cAddress += bank & 0x03;
break;
}
}
/**
* \fn unsigned long EEPROM24::size() const
* \brief Returns the size of the EEPROM in bytes.
*
* \sa pageSize()
*/
/**
* \fn unsigned long EEPROM24::pageSize() const
* \brief Returns the size of a single EEPROM page in bytes.
*
* Writes that are a multiple of the page size and aligned on a page
* boundary will typically be more efficient than non-aligned writes.
*
* \sa size()
*/
/**
* \brief Returns true if the EEPROM is available on the I2C bus;
* false otherwise.
*
* This function can be used to probe the I2C bus to determine if the
* EEPROM is present or not.
*
* \sa read(), write()
*/
bool EEPROM24::available()
{
// Perform a "Current Address Read" on the EEPROM. We don't care about
// the returned byte. We only care if the read request was ACK'ed or not.
if (!_bus->startRead(i2cAddress, 1))
return false;
_bus->read();
return true;
}
/**
* \brief Reads a single byte from the EEPROM at \a address.
*
* \sa write()
*/
uint8_t EEPROM24::read(unsigned long address)
{
if (address >= _size)
return 0;
writeAddress(address);
if (!_bus->startRead(i2cAddress, 1))
return 0;
return _bus->read();
}
/**
* \brief Reads a block of \a length bytes from the EEPROM at \a address
* into the specified \a data buffer.
*
* Returns the number of bytes that were read, which may be short if
* \a address + \a length is greater than size() or the EEPROM is
* not available on the I2C bus.
*
* \sa write(), available()
*/
size_t EEPROM24::read(unsigned long address, void *data, size_t length)
{
if (address >= _size || !length)
return 0;
if ((address + length) > _size)
length = (size_t)(_size - address);
writeAddress(address);
if (!_bus->startRead(i2cAddress, length))
return 0;
uint8_t *d = (uint8_t *)data;
unsigned int count = 0;
while (_bus->available()) {
*d++ = _bus->read();
++count;
}
return count;
}
/**
* \brief Writes a byte \a value to \a address in the EEPROM.
*
* Returns true if the byte was written successfully, or false if
* \a address is out of range or the EEPROM is not available on the I2C bus.
*
* \sa read(), available()
*/
bool EEPROM24::write(unsigned long address, uint8_t value)
{
if (address >= _size)
return false;
writeAddress(address);
_bus->write(value);
return waitForWrite();
}
/**
* \brief Writes \a length bytes from a \a data buffer to \a address
* in the EEPROM.
*
* Returns the number of bytes that were written, which may be short if
* \a address + \a length is greater than size() or the EEPROM is not
* available on the I2C bus.
*
* Best performance will be achieved if \a address and \a length are a
* multiple of pageSize().
*
* \sa read(), available(), pageSize()
*/
size_t EEPROM24::write(unsigned long address, const void *data, size_t length)
{
if (address >= _size)
return 0;
if ((address + length) > _size)
length = (size_t)(_size - address);
bool needAddress = true;
size_t result = 0;
size_t page = 0;
const uint8_t *d = (const uint8_t *)data;
while (length > 0) {
if (needAddress) {
writeAddress(address);
needAddress = false;
}
_bus->write(*d++);
++address;
++page;
if ((address & (_pageSize - 1)) == 0) {
// At the end of a page, so perform a flush.
if (!waitForWrite())
return result; // Could not write this page.
needAddress = true;
result += page;
page = 0;
}
--length;
}
if (!needAddress) {
if (!waitForWrite())
return result; // Could not write the final page.
}
return result + page;
}
void EEPROM24::writeAddress(unsigned long address)
{
switch (_mode) {
case EE_BSEL_NONE:
_bus->startWrite(i2cAddress);
_bus->write((uint8_t)(address >> 8));
_bus->write((uint8_t)address);
break;
case EE_BSEL_8BIT_ADDR:
_bus->startWrite(i2cAddress | (((uint8_t)(address >> 8)) & 0x07));
_bus->write((uint8_t)address);
break;
case EE_BSEL_17BIT_ADDR:
_bus->startWrite(i2cAddress | (((uint8_t)(address >> 16)) & 0x01));
_bus->write((uint8_t)(address >> 8));
_bus->write((uint8_t)address);
break;
case EE_BSEL_17BIT_ADDR_ALT:
_bus->startWrite(i2cAddress | (((uint8_t)(address >> 14)) & 0x04));
_bus->write((uint8_t)(address >> 8));
_bus->write((uint8_t)address);
break;
}
}
bool EEPROM24::waitForWrite()
{
// 1000 iterations is going to be approximately 100ms when the I2C
// clock is 100 kHz. If there has been no response in that time
// then we assume that the write has failed and timeout.
if (!_bus->endWrite())
return false;
unsigned count = 1000;
while (count > 0) {
_bus->startWrite(i2cAddress);
if (_bus->endWrite())
return true;
--count;
}
return false;
}
| 32.594855 | 78 | 0.635395 | [
"object"
] |
dcd14c3b7a09306c9d6a1a45b021b9f543d28f79 | 387 | cc | C++ | lib/material/Lambertian.cc | westrik/millipede | b2049b9333c1888e75fb8688a24be35f5724ac4d | [
"MIT"
] | 1 | 2020-11-12T08:26:55.000Z | 2020-11-12T08:26:55.000Z | lib/material/Lambertian.cc | westrik/millipede | b2049b9333c1888e75fb8688a24be35f5724ac4d | [
"MIT"
] | null | null | null | lib/material/Lambertian.cc | westrik/millipede | b2049b9333c1888e75fb8688a24be35f5724ac4d | [
"MIT"
] | null | null | null | #include "Lambertian.h"
#include "../Millipede.h"
namespace Millipede {
bool Lambertian::scatter(const Ray& ray_in, const HitRecord& hit_record, Colour& attenuation,
Ray& scattered) const {
Vector target = hit_record.p + hit_record.normal + random_in_unit_sphere();
scattered = Ray(hit_record.p, target - hit_record.p);
attenuation = albedo;
return true;
}
} | 25.8 | 94 | 0.705426 | [
"vector"
] |
dcd311e3d8c6664ab73a9dbce9f99e201ca9b777 | 6,528 | cpp | C++ | src/Particle.cpp | M4T1A5/IndieSpeedRun2013 | 75b1adc4716c2e32f308289cce51a78a10681697 | [
"Zlib"
] | null | null | null | src/Particle.cpp | M4T1A5/IndieSpeedRun2013 | 75b1adc4716c2e32f308289cce51a78a10681697 | [
"Zlib"
] | null | null | null | src/Particle.cpp | M4T1A5/IndieSpeedRun2013 | 75b1adc4716c2e32f308289cce51a78a10681697 | [
"Zlib"
] | null | null | null | #include <Particle.h>
using namespace EGEMotor;
using namespace EGEMath;
Particle::Particle(Vector Position, Vector Direction, Vector Scale, Texture* Texture, float Life)
: m_position(Position),
m_direction(Direction),
m_scale(Scale),
m_sprite(Texture),
m_life(Life),
m_startLife(Life),
m_dead(false)
{
m_sprite.setPosition(Position);
m_sprite.setScale(Scale);
m_sprite.setLayer(300);
m_sprite.setOriginPoint(5);
}
Particle::~Particle()
{}
bool Particle::Update(float DeltaTime)
{
m_position += m_direction * DeltaTime;
m_sprite.setPosition(m_position);
m_life -= DeltaTime;
if (m_life < 0)
return true;
return false;
}
void Particle::Draw(Viewport* viewport)
{
viewport->draw(&m_sprite);
}
//Tornado Particle
Tornado::Tornado(Vector position, Vector direction, Vector scale, Texture* texture)
: Particle(position,Vector(direction.x/5.0f,-direction.y/5.0f),scale,texture,3.0f)
{
m_startY = position.y;
m_direction = Vector(direction.x/5.0f,-direction.y/5.0f);
m_animation = new Animation(&m_sprite,3,400,600, 20,0,true);
m_sprite.setColor(255,255,255,180);
AreaOfEffect = 100;
if (direction.x > 0)
{
m_scale.x = -m_scale.x;
m_sprite.setScale(m_scale);
}
m_sprite.setLayer(285);
//m_sprite.setColor(1,1,1,1);
m_timer = 2;
m_sprite.setOriginPoint(5);
}
bool Tornado::Update(float DeltaTime)
{
m_animation->Update(DeltaTime);
m_sprite.setPosition(Vector(m_position.x -= DeltaTime * 100 , float(m_startY + 50 * sin(PI*(-m_life/m_startLife)))));
if (Particle::Update(DeltaTime))
{
m_timer -= DeltaTime;
if (m_timer < 0)
return true;
setColor(255,255,255,255.0f*(m_timer/2.0f));
}
return false;
}
void Tornado::setColor(int R,int G,int B,int A)
{
m_r = R;
m_g = G;
m_b = B;
m_a = A;
m_sprite.setColor(unsigned int(m_r), unsigned int(m_g), unsigned int(m_b), unsigned int(m_a));
}
Bug::Bug(Vector position, Vector direction, Vector scale, Texture* texture)
: Particle(position,Vector(direction.x/5.0f,-direction.y/5.0f),scale,texture,5.0f)
{
m_direction = Vector(direction.x/-5.0f,-direction.y/5.0f);
m_animation = new Animation(&m_sprite,3,200,200, 20);
m_sprite.setColor(255,255,255,255);
AreaOfEffect = 30;
if (direction.x > 0)
{
m_scale.x = -m_scale.x;
m_sprite.setScale(m_scale);
}
m_sprite.setLayer(285);
//m_sprite.setColor(1,1,1,1);
m_life = 5;
m_sprite.setOriginPoint(5);
}
bool Bug::Update(float DeltaTime)
{
m_animation->Update(DeltaTime);
return Particle::Update(DeltaTime);
}
Cat::Cat(Vector position, Vector direction, Vector scale, Texture* texture)
: Particle(position,Vector(direction.x/5.0f,-direction.y/5.0f),scale,texture,5.0f)
{
m_direction = Vector(direction.x/-5.0f,-direction.y/5.0f);
m_sprite.setColor(255,255,255,255);
AreaOfEffect = 60;
if (direction.x > 0)
{
m_scale.x = -m_scale.x;
m_sprite.setScale(m_scale);
}
m_sprite.setLayer(285);
//m_sprite.setColor(1,1,1,1);
m_life = 10;
m_sprite.setOriginPoint(5);
}
////Feather Particle
//feather::feather(vector Position, vector Direction, vector Scale, texture* Texture, bool Enemy)
// : particle(Position,1000*Direction,Scale,Texture,5.0f + (0-(rand()%300)/100.0f))
//{
// if (Enemy)
// setColor(140,182,123);
// else
// setColor();
// m_scale = vector(
// Scale.x + Scale.x * (0.2f - (rand()%400)/1000.0f),
// Scale.y + Scale.y * (0.2f - (rand()%400)/1000.0f)
// );
// if (rand()%100 < 50)
// {
// m_scale.y = -m_scale.y;
// }
//
// //m_sprite.setOrigin(vector(m_sprite.getTransformedSize().x/2,-m_sprite.getTransformedSize().y/2));
//
// m_sprite.setScale(m_scale);
// m_sprite.setLayer(280);
//
// m_timer = -0.08f;
// m_rotate = (rand()%1000)/100.0f;
//}
//void feather::setColor(int R,int G,int B,int A)
//{
// m_r = R - 15.0f + rand()%15;
// m_g = G - 15.0f + rand()%15;
// m_b = B - 15.0f + rand()%15;
// m_a = A - 100.0f + rand()%50;
// m_sprite.setColor(unsigned int(m_r), unsigned int(m_g), unsigned int(m_b), unsigned int(m_a));
//}
//bool feather::update(float DeltaTime)
//{
// m_timer += DeltaTime;
// if (m_timer < 0)
// {
// m_direction *= (1-DeltaTime)*(1-DeltaTime);
// m_position += m_direction * DeltaTime;
// m_sprite.setPosition(m_position);
// particle::update(DeltaTime);
// m_rotate += DeltaTime*3600.0f;
// m_sprite.setRotation(m_rotate);
// }
// else
// {
// m_life -= DeltaTime;
// if (m_life < 0)
// return true;
// m_sprite.setColor(unsigned int(m_r), unsigned int(m_g), unsigned int(m_b), unsigned int((m_life/m_startLife) * m_a));
// m_rotate += DeltaTime * 3.0f;
// m_position.y += DeltaTime * 5.0f;
// m_sprite.setPosition(m_position);
// if (m_scale.y > 0)
// {
// m_sprite.setRotation( sin(m_rotate) * 20);
// }
// else
// {
// m_sprite.setRotation( 180 + sin(m_rotate) * 20);
// }
// }
// return false;
//}
/////Score Particle
//scoreParticle::scoreParticle(al::vector Position, al::vector Direction, al::texture* Texture, al::font* Font, float Score)
// : particle(Position,Direction,vector(1,1),Texture,3.0f)
//{
// m_sprite.setTexture(Texture);
// m_sprite.setOriginPoint(5);
// m_sprite.setLayer(300);
// m_text.setFont(Font);
// m_text.setCharacterSize(60);
// m_text.setString(std::to_string(long double(Score)));
// m_text.setOriginPoint(5);
// m_text.setLayer(300);
//
//}
//bool scoreParticle::update(float DeltaTime)
//{
// //m_direction.y += 20 * DeltaTime;
// //m_position += 50 * m_direction * DeltaTime;
// m_life -= DeltaTime;
// m_scale = vector(1-(m_life/m_startLife),1-(m_life/m_startLife));
//
// m_sprite.setColor(255, 255, 255, unsigned int((m_life/m_startLife) * 255));
// m_sprite.setPosition(m_position);
// m_sprite.setScale(m_scale);
//
// m_text.setColor(255, 255, 255, unsigned int((m_life/m_startLife) * 255));
// m_text.setPosition(m_position);
// m_text.setScale(m_scale);
//
// //stayOnScreen();
//
// if (m_life < 0)
// return true;
// return false;
//}
//void scoreParticle::draw(viewport* Viewport)
//{
// Viewport->draw(&m_sprite);
// Viewport->draw(&m_text);
//}
//void scoreParticle::stayOnScreen()
//{
// float left = 0;
// float right = WINDOW_WIDTH;
// float top = 0;
// float bottom = WINDOW_HEIGHT;
// if (m_position.x < left)
// {
// m_direction.x = -m_direction.x;
// m_position.x = left;
// }
// else
// if (m_position.x > right)
// {
// m_direction.x = -m_direction.x;
// m_position.x = right;
// }
// if (m_position.y < top)
// {
// m_direction.y = -m_direction.y;
// m_position.y = top;
// }
// else
// if (m_position.y > bottom)
// {
// m_direction.y = -m_direction.y;
// m_position.y = bottom;
// }
//} | 24.449438 | 124 | 0.668045 | [
"vector"
] |
dcd47dd0f79e6e5c12700b355392b7e49ac40078 | 2,548 | cc | C++ | dali/operators/generic/transpose/transpose_gpu.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2022-02-17T19:54:05.000Z | 2022-02-17T19:54:08.000Z | dali/operators/generic/transpose/transpose_gpu.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/generic/transpose/transpose_gpu.cc | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "dali/operators/generic/transpose/transpose.h"
#include "dali/kernels/transpose/transpose_gpu.h"
#include "dali/kernels/kernel_manager.h"
#include "dali/core/error_handling.h"
namespace dali {
class TransposeGPU : public Transpose<GPUBackend> {
public:
using Kernel = kernels::TransposeGPU;
explicit inline TransposeGPU(const OpSpec &spec) : Transpose(spec) {
kmgr_.Resize<Kernel>(1);
}
bool CanInferOutputs() const override {
return true;
}
protected:
bool SetupImpl(vector<OutputDesc> &descs, const DeviceWorkspace &ws) override {
Transpose<GPUBackend>::SetupImpl(descs, ws);
const auto &input = ws.template Input<GPUBackend>(0);
kernels::KernelContext ctx;
ctx.gpu.stream = ws.stream();
kmgr_.Setup<Kernel>(0, ctx, input.shape(), make_span(perm_), input.type_info().size());
return true;
}
void RunImpl(DeviceWorkspace &ws) override {
const auto &input = ws.Input<GPUBackend>(0);
auto &output = ws.Output<GPUBackend>(0);
output.SetLayout(output_layout_);
GetData(in_data_, input);
GetData(out_data_, output);
kernels::KernelContext ctx;
ctx.gpu.stream = ws.stream();
kmgr_.Run<Kernel>(0, ctx, out_data_.data(), in_data_.data());
}
private:
void GetData(vector<void *> &data, TensorList<GPUBackend> &tl) {
int N = tl.num_samples();
data.resize(N);
for (int i = 0; i < N; i++) {
data[i] = tl.raw_mutable_tensor(i);
}
}
void GetData(vector<const void *> &data, const TensorList<GPUBackend> &tl) {
int N = tl.num_samples();
data.resize(N);
for (int i = 0; i < N; i++) {
data[i] = tl.raw_tensor(i);
}
}
kernels::KernelManager kmgr_;
vector<const void *> in_data_;
vector<void *> out_data_;
};
DALI_REGISTER_OPERATOR(Transpose, TransposeGPU, GPU);
} // namespace dali
| 28.629213 | 91 | 0.691523 | [
"shape",
"vector"
] |
dcd671c4627d5910dd459ab90d2a05b04abc7fd5 | 63,071 | cpp | C++ | src/base/subscriber/EphemManager.cpp | Randl/GMAT | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 2 | 2020-01-01T13:14:57.000Z | 2020-12-09T07:05:07.000Z | src/base/subscriber/EphemManager.cpp | rdadan/GMAT-R2016a | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 1 | 2018-03-15T08:58:37.000Z | 2018-03-20T20:11:26.000Z | src/base/subscriber/EphemManager.cpp | rdadan/GMAT-R2016a | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 3 | 2019-10-13T10:26:49.000Z | 2020-12-09T07:06:55.000Z | //$Id$
//------------------------------------------------------------------------------
// EphemManager
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Author: Wendy C. Shoan
// Created: 2014.10.28
//
/**
* Base class implementation for the EphemManager. The EphemManager is
* responsible for creating, loading, and managing private/hidden EphemerisFile
* objects associated with its specified Spacecraft object.
* NOTE: currently, the EphemManager will only handle SPK Orbit files.
* NOTE: code to get occultation and contact intervals based on
* prototypes written by Joel Parker/GSFC and Yeerang Lim/KAIST
*/
//------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include "EphemManager.hpp"
#include "GmatBase.hpp"
#include "CoordinateSystem.hpp"
#include "EphemerisFile.hpp"
#include "Publisher.hpp"
#include "Spacecraft.hpp"
#include "FileManager.hpp"
#include "MessageInterface.hpp"
#include "SubscriberException.hpp"
#include "FileUtil.hpp"
#include "StringUtil.hpp"
#include "TimeTypes.hpp"
#include "GmatConstants.hpp"
#ifdef __USE_SPICE__
#include "SpiceInterface.hpp"
#endif
//#define DEBUG_EPHEM_MANAGER
//#define DEBUG_EPHEM_MANAGER_FILES
//#define DEBUG_EM_COVERAGE
//#define DEBUG_OCCULTATION
//#define DEBUG_SPK_COVERAGE
//#define DEBUG_CONTACT
//#define DEBUG_EM_TIME_SPENT
//#define DEBUG_EM_TIME_ADJUST
//#define DEBUG_EM_FILENAME
#ifdef DEBUG_EM_TIME_SPENT
#include <time.h>
#endif
/**
* Manager for ephemeris recording for the specified object
*/
//------------------------------------------------------------------------------
// default constructor
//------------------------------------------------------------------------------
EphemManager::EphemManager(bool deleteFiles) :
initialEpoch ("InitialSpacecraftEpoch"),
finalEpoch ("FinalSpacecraftEpoch"),
theType (SPK),
theObjName (""),
theObj (NULL),
solarSys (NULL),
ephemFile (NULL),
coordSys (NULL),
coordSysName (""),
ephemName (""),
ephemCount (0),
fileName (""),
recording (false),
deleteTmpFiles (deleteFiles),
intStart (0.0),
intStop (0.0),
coverStart (0.0),
coverStop (0.0)
{
#ifdef __USE_SPICE__
spice = NULL;
cover = NULL;
#endif
}
//------------------------------------------------------------------------------
// destructor
//------------------------------------------------------------------------------
EphemManager::~EphemManager()
{
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("Destructing EphemManager ...\n");
MessageInterface::ShowMessage(" and deleteTmpFiles = %s\n",
(deleteTmpFiles? "true" : "false"));
#endif
// Stop recording
if (recording) StopRecording(true);
// Unsubscribe
if (ephemFile)
{
Publisher *pub = Publisher::Instance();
pub->Unsubscribe(ephemFile);
}
// Unload the SPK files that we have already loaded
for (unsigned int ii = 0; ii < fileList.size(); ii++)
{
std::string eachFile = fileList.at(ii);
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage(
"Destructing EphemManager ...about to unload SPK kernel %s\n",
eachFile.c_str());
#endif
#ifdef __USE_SPICE__
spice->UnloadKernel(eachFile.c_str());
#endif
}
if (deleteTmpFiles)
{
// Remove all of the temporary SPK files
for (unsigned int ii = 0; ii < fileList.size(); ii++)
{
std::string eachFile = fileList.at(ii);
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage(
"Destructing EphemManager ...about to delete file %s\n",
eachFile.c_str());
#endif
remove(eachFile.c_str());
}
}
fileList.clear();
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("Destructing EphemManager ... deleting ephemFile\n");
#endif
// delete the current EphemerisFile
if (ephemFile) delete ephemFile;
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("Destructing EphemManager ... deleting spice\n");
#endif
// delete the SpiceInterface
#ifdef __USE_SPICE__
if (spice) delete spice;
#endif
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("Destructing EphemManager ... DONE\n");
#endif
}
//------------------------------------------------------------------------------
// copy constructor
//------------------------------------------------------------------------------
EphemManager::EphemManager(const EphemManager& copy) :
initialEpoch (copy.initialEpoch),
finalEpoch (copy.finalEpoch),
theType (copy.theType),
theObjName (copy.theObjName),
theObj (NULL),
solarSys (NULL),
ephemFile (NULL),
coordSys (NULL),
coordSysName (copy.coordSysName),
ephemName (""),
ephemCount (0),
fileName (copy.fileName),
recording (copy.recording),
deleteTmpFiles (copy.deleteTmpFiles),
intStart (copy.intStart),
intStop (copy.intStop),
coverStart (copy.coverStart),
coverStop (copy.coverStop)
{
#ifdef __USE_SPICE__
spice = NULL;
cover = NULL;
#endif
}
//------------------------------------------------------------------------------
// operator=
//------------------------------------------------------------------------------
EphemManager& EphemManager::operator=(const EphemManager& copy)
{
if (© == this)
return *this;
initialEpoch = copy.initialEpoch;
finalEpoch = copy.finalEpoch;
theType = copy.theType;
theObjName = copy.theObjName;
theObj = copy.theObj;
solarSys = copy.solarSys;
// ephemFile = (EphemerisFile*)(copy.ephemFile)->Clone(); // need to Subscribe here?
ephemFile = NULL;
coordSys = copy.coordSys;
coordSysName = copy.coordSysName;
ephemName = ""; // OR copy.ephemName;
ephemCount = copy.ephemCount;
fileName = copy.fileName;
recording = copy.recording;
deleteTmpFiles = copy.deleteTmpFiles;
intStart = copy.intStart;
intStop = copy.intStop;
coverStart = copy.coverStart;
coverStop = copy.coverStop;
#ifdef __USE_SPICE__
if (spice) delete spice;
spice = NULL;
cover = NULL;
#endif
// @todo - what to do with the files already created here ... and what if the copy
// is in the middle of recording? need to check deleteTmpFiles flag?
fileList = copy.fileList; // ?????
return *this;
}
//------------------------------------------------------------------------------
// Initialize()
//------------------------------------------------------------------------------
bool EphemManager::Initialize()
{
if (!coordSys)
throw SubscriberException("Coordinate system for EphemManager has not been set!\n");
if (!theObj)
throw SubscriberException("Spacecraft for EphemManager has not been set!\n");
if (!solarSys)
throw SubscriberException("SolarSystem for EphemManager has not been set!\n");
#ifdef __USE_SPICE__
// Create SPICE interface
if (!spice) spice = new SpiceInterface();
#endif
return true;
}
//------------------------------------------------------------------------------
// RecordEphemerisData()
//------------------------------------------------------------------------------
bool EphemManager::RecordEphemerisData()
{
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage(
"Entering EphemManager::RecordEphemerisData for SC %s\n",
theObj->GetName().c_str());
#endif
Spacecraft *theSc = (Spacecraft*) theObj;
#ifndef __USE_SPICE__
std::string errmsg = "ERROR - cannot record ephemeris data for spacecraft ";
errmsg += theSc->GetName() + " without SPICE included in build!\n";
throw SubscriberException(errmsg);
#else
// If it's already recording, continue
if (!ephemFile)
{
#ifdef DEBUG_EPHEM_MANAGER_FILES
MessageInterface::ShowMessage(
"In EphemManager::RecordEphemerisData for SC %s, setting up ephemFile\n",
theObj->GetName().c_str());
#endif
if (theType != SPK)
throw SubscriberException("Only SPK currently allowed for EphemManager\n");
if (!spice)
spice = new SpiceInterface();
// Set up the name for the EphemerisFile, and the file name
std::stringstream ss("");
// ss << "tmp_" << theObjName << "_" << ephemCount << "_" << GmatTimeUtil::FormatCurrentTime(4);
ss << "tmp_" << theObjName << "_" << GmatTimeUtil::FormatCurrentTime(4);
ephemName = ss.str();
ss << ".bsp";
fileName = ss.str();
#ifdef DEBUG_EM_FILENAME
MessageInterface::ShowMessage("(base) Filename for NEW ephemFile is determined to be: %s\n",
fileName.c_str());
#endif
ephemFile = new EphemerisFile(ephemName);
#ifdef DEBUG_EPHEM_MANAGER_FILES
MessageInterface::ShowMessage(
"In EphemManager::RecordEphemerisData, ephemFile is at <%p> with name %s\n",
ephemFile, ephemName.c_str());
#endif
// For now, put it in the Output path << this should be put into the
// appropriate TMPDIR for the platform
// FileManager *fm = FileManager::Instance();
// std::string spkPath = fm->GetPathname(FileManager::OUTPUT_PATH);
// fileName = spkPath + fileName;
std::string spkTmpPath = GmatFileUtil::GetTemporaryDirectory();
fileName = spkTmpPath + fileName;
#ifdef DEBUG_EM_FILENAME
MessageInterface::ShowMessage("(full-path) Filename for NEW ephemFile is determined to be: %s\n",
fileName.c_str());
#endif
#ifdef DEBUG_EPHEM_MANAGER_FILES
MessageInterface::ShowMessage(
"In EphemManager::RecordEphemerisData, fileName (full path) = %s\n",
fileName.c_str());
#endif
// Set up the EphemerisFile to write what we need - currently only SPK Orbit
ephemFile->SetStringParameter("FileFormat", "SPK");
ephemFile->SetStringParameter("StateType", "Cartesian");
ephemFile->SetStringParameter("Spacecraft", theObjName);
ephemFile->SetStringParameter("CoordinateSystem", coordSysName); // only MJ2000Eq so far!!
ephemFile->SetStringParameter("Filename", fileName);
ephemFile->SetStringParameter("Interpolator", "Hermite");
ephemFile->SetIntegerParameter(ephemFile->GetParameterID("InterpolationOrder"), 7);
ephemFile->SetBackgroundGeneration(true);
ephemFile->SetInternalCoordSystem(coordSys);
ephemFile->SetRefObject(theObj, Gmat::SPACECRAFT, theObjName);
ephemFile->SetRefObject(coordSys, Gmat::COORDINATE_SYSTEM, coordSysName);
ephemFile->Initialize();
// Subscribe to the data
Publisher *pub = Publisher::Instance();
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage(
"In EphemManager::RecordEphemerisData, subscribing to publisher\n");
#endif
pub->Subscribe(ephemFile);
ephemCount++;
}
else if (!recording)
{
// Set up the name for the EphemerisFile, and the file name
std::stringstream ss("");
// ss << "tmp_" << theObjName << "_" << ephemCount << "_" << GmatTimeUtil::FormatCurrentTime(4);
ss << "tmp_" << theObjName << "_" << GmatTimeUtil::FormatCurrentTime(4);
ephemName = ss.str();
ss << ".bsp";
fileName = ss.str();
std::string spkTmpPath = GmatFileUtil::GetTemporaryDirectory();
fileName = spkTmpPath + fileName;
#ifdef DEBUG_EM_FILENAME
MessageInterface::ShowMessage("(full path) Filename for existing ephemFile is determined to be: %s\n",
fileName.c_str());
#endif
// if it has an ephemFile but it is not recording,
// reset the SPK filename
ephemFile->SetStringParameter("Filename", fileName);
}
else
{
// continue recording
#ifdef DEBUG_EPHEM_MANAGER_FILES
MessageInterface::ShowMessage(
"In EphemManager::RecordEphemerisData for SC %s, ephemFile is already recording!!!\n",
theObj->GetName().c_str());
#endif
}
recording = true;
return true;
#endif
}
//------------------------------------------------------------------------------
// ProvideEphemerisData()
//------------------------------------------------------------------------------
bool EphemManager::ProvideEphemerisData()
{
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("ProvideEphemerisData called ----- fileName = %s\n",
fileName.c_str());
#endif
StopRecording(true); // false); SPK appending turned off for now.
RecordEphemerisData();
return true;
}
//------------------------------------------------------------------------------
// StopRecording(bool done = true)
//------------------------------------------------------------------------------
void EphemManager::StopRecording(bool done)
{
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("StopRecording ----- fileName = %s, done = %s\n",
fileName.c_str(), (done? "true" : "false"));
#endif
// Finalize and close the SPK file
if (done)
{
// // Unsubscribe
// Publisher *pub = Publisher::Instance();
// pub->Unsubscribe(ephemFile);
// Delete the current ephemFile - this should finalize the SPK writing and then
// close the <fileName> file
#ifdef DEBUG_EM_FILENAME
MessageInterface::ShowMessage("In StopRecording, closing ephem file ...");
#endif
ephemFile->CloseEphemerisFile(false, true);
// Made general method name (LOJ: 2015.11.16)
//bool notAllDataWritten = ephemFile->InsufficientSPKData();
bool notAllDataWritten = ephemFile->InsufficientDataPoints();
if (notAllDataWritten)
{
std::string warn = "*** WARNING *** Insufficient ephemeris data ";
warn += "available for spacecraft " + theObj->GetName();
warn += " to write last segment. Event location may be ";
warn += "incomplete. Try increasing the propagation time.\n";
MessageInterface::ShowMessage(warn);
}
// delete ephemFile;
}
else // appending - this is turned OFF for now
{
#ifdef __USE_SPICE__
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("-==-==-= Now attempting to UNload fileList \"%s\"\n",
fileName.c_str());
#endif
if (spice->IsLoaded(fileName))
spice->UnloadKernel(fileName); // need to unload before re-loading?
#endif
// tell the EphemerisFile to close the SPK and leave ready for appending
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("-==-==-= Calling CloseEphemerisFile\n");
#endif
ephemFile->CloseEphemerisFile(false, true);
//bool notAllDataWritten = ephemFile->InsufficientSPKData();
bool notAllDataWritten = ephemFile->InsufficientDataPoints();
if (notAllDataWritten)
{
std::string warn = "*** WARNING *** Insufficient ephemeris data ";
warn += "available for spacecraft " + theObj->GetName();
warn += " to write last segment. Event location may be ";
warn += "incomplete. Try increasing the propagation time.\n";
MessageInterface::ShowMessage(warn);
}
}
// Load the current SPK file, if it has been written
if (GmatFileUtil::DoesFileExist(fileName))
{
#ifdef __USE_SPICE__
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("-==-==-= Now attempting to re-load file \"%s\"\n",
fileName.c_str());
#endif
spice->LoadKernel(fileName);
#endif
#ifdef DEBUG_EPHEM_MANAGER
MessageInterface::ShowMessage("-==-==-= adding fileName %s to fileList\n",
fileName.c_str());
#endif
// save the just written file name
if (find(fileList.begin(), fileList.end(), fileName) ==
fileList.end())
fileList.push_back(fileName);
}
#ifdef DEBUG_EPHEM_MANAGER
else
{
MessageInterface::ShowMessage("-==-==-= %s DOES NOT exist and so cannot be reloaded!!!\n",
fileName.c_str());
}
#endif
// if (done) ephemFile = NULL;
recording = false;
}
//------------------------------------------------------------------------------
// bool GetOccultationIntervals(const std::string &occType,
// const std::string &frontBody,
// const std::string &frontShape,
// const std::string &frontFrame,
// const std::string &backBody,
// const std::string &backShape,
// const std::string &backFrame,
// const std::string &abbCorrection,
// Integer naifId,
// Integer step,
// Real &intvlStart,
// Real &intvlStop,
// Integer &numIntervals,
// RealArray &starts,
// RealArray &ends);
//------------------------------------------------------------------------------
/**
* This method determines the intervals of occultation given the input front
* body, back body, abberration correction, naif ID, and step size.
*
* @param occType UMBRA, PENUMBRA, ANTUMBRA, ALL
* @param frontBody the front body
* @param frontShape the shape of the front body
* @param frontFrame the frame of the front body
* @param backBody the back body
* @param backShape the shape of the back body
* @param backFrame the frame of the back body
* @param abbCorrection the aberration correction for the operation
* @param naifId the NAIF ID for the spacecraft
* @param step step size (s)
* @param intvlStart start of the resulting interval
* @param intvlStop stop of the resulting interval
* @param numIntervals the number of intervals detected (output)
* @param starts array of start times for the intervals (output)
* @param ends array of end times for the intervals (output)
*
*/
//------------------------------------------------------------------------------
/// method to determine occultation intervals
bool EphemManager::GetOccultationIntervals(const std::string &occType,
const std::string &frontBody,
const std::string &frontShape,
const std::string &frontFrame,
const std::string &backBody,
const std::string &backShape,
const std::string &backFrame,
const std::string &abCorrection,
Real s,
Real e,
bool useEntireIntvl,
Real stepSize,
Integer &numIntervals,
RealArray &starts,
RealArray &ends)
{
Spacecraft *theSc = (Spacecraft*) theObj;
#ifndef __USE_SPICE__
std::string errmsg = "ERROR - cannot compute occultation intervals for spacecraft ";
errmsg += theSc->GetName() + " without SPICE included in build!\n";
throw SubscriberException(errmsg);
#else
#ifdef DEBUG_OCCULTATION
MessageInterface::ShowMessage("In GetOccultationIntervals:\n");
MessageInterface::ShowMessage(" occType = %s\n", occType.c_str());
MessageInterface::ShowMessage(" frontBody = %s\n", frontBody.c_str());
MessageInterface::ShowMessage(" frontShape = %s\n", frontShape.c_str());
MessageInterface::ShowMessage(" frontFrame = %s\n", frontFrame.c_str());
MessageInterface::ShowMessage(" backBody = %s\n", backBody.c_str());
MessageInterface::ShowMessage(" backShape = %s\n", backShape.c_str());
MessageInterface::ShowMessage(" backFrame = %s\n", backFrame.c_str());
MessageInterface::ShowMessage(" abCorrection = %s\n", abCorrection.c_str());
#endif
Integer theNAIFId = theSc->GetIntegerParameter("NAIFId");
std::string theNAIFIdStr = GmatStringUtil::ToString(theNAIFId);
// window we want to search
SPICEDOUBLE_CELL(window, 200000);
scard_c(0, &window); // reset (empty) the cell
// Get coverage window (no light time corrections needed)
GetRequiredCoverageWindow(&window, s, e, useEntireIntvl, abCorrection);
SpiceInt numInt = wncard_c(&window);
// CSPICE data
ConstSpiceChar *occultationType; // = occType.c_str();
ConstSpiceChar *front = frontBody.c_str();
ConstSpiceChar *fshape = frontShape.c_str();
ConstSpiceChar *fframe = frontFrame.c_str();
ConstSpiceChar *back = backBody.c_str();
ConstSpiceChar *bshape = backShape.c_str();
ConstSpiceChar *bframe = backFrame.c_str();
ConstSpiceChar *abcorr = abCorrection.c_str();
ConstSpiceChar *obsrvr = theNAIFIdStr.c_str();
SpiceDouble step = stepSize;
if (occType == "ALL")
occultationType = "ANY"; // <future> find SPICE constant for this
else if (occType == "Umbra")
occultationType = SPICE_GF_FULL;
else if (occType == "Penumbra")
occultationType = SPICE_GF_PARTL;
else // Antumbra
occultationType = SPICE_GF_ANNULR;
SPICEDOUBLE_CELL(result, 200000);
scard_c(0, &result); // reset (empty) the result cell
#ifdef DEBUG_OCCULTATION
MessageInterface::ShowMessage("Calling gfoclt_c with:\n");
MessageInterface::ShowMessage(" occultationType = %s\n", occultationType);
MessageInterface::ShowMessage(" front = %s\n", frontBody.c_str());
MessageInterface::ShowMessage(" fshape = %s\n", frontShape.c_str());
MessageInterface::ShowMessage(" fframe = %s\n", frontFrame.c_str());
MessageInterface::ShowMessage(" back = %s\n", backBody.c_str());
MessageInterface::ShowMessage(" bshape = %s\n", backShape.c_str());
MessageInterface::ShowMessage(" bframe = %s\n", backFrame.c_str());
MessageInterface::ShowMessage(" abcorr = %s\n", abCorrection.c_str());
MessageInterface::ShowMessage(" obsrvr = %s\n", theNAIFIdStr.c_str());
MessageInterface::ShowMessage(" step = %12.10f\n", stepSize);
#endif
#ifdef DEBUG_EM_TIME_SPENT
clock_t t = clock();
#endif
gfoclt_c(occultationType, front, fshape, fframe, back, bshape, bframe, abcorr,
obsrvr, step, &window, &result);
#ifdef DEBUG_EM_TIME_SPENT
Real timeSpent = (Real) (clock() - t);
MessageInterface::ShowMessage(" -------------- time in gfoclt_c call for %s is %12.10f (sec)\n",
occType.c_str(), (timeSpent / CLOCKS_PER_SEC));
#endif
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
SpiceChar err[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling gfoclt_c!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
// MessageInterface::ShowMessage("----- error message = %s\n",
// errmsg.c_str());
reset_c();
throw SubscriberException(errmsg);
}
SpiceInt sz = wncard_c(&result);
numIntervals = (Integer) sz;
#ifdef DEBUG_OCCULTATION
MessageInterface::ShowMessage("---------- For occType = %s, %d events found\n",
occType.c_str(), numIntervals);
#endif
for (Integer ii = 0; ii < numIntervals; ii++)
{
SpiceDouble s, e;
wnfetd_c(&result, ii, &s, &e);
Real ss = spice->SpiceTimeToA1(s);
Real ee = spice->SpiceTimeToA1(e);
starts.push_back(ss); // OR starts.at(ii) = s? (and same for e)?
ends.push_back(ee);
}
scard_c(0, &window); // reset (empty) the window cell
scard_c(0, &result); // reset (empty) the result cell
return true;
#endif
}
/// @YRL
//------------------------------------------------------------------------------
// bool GetContactIntervals(const std::string &observerID,
// Real minElevation,
// const std::string &obsFrameName,
// StringArray &occultingBodyNames,
// const std::string &abCorrection,
// Real s,
// Real e,
// bool useEntireIntvl,
// bool useLightTime,
// bool transmit,
// Real stepSize,
// Integer &numIntervals,
// RealArray &starts,
// RealArray &ends)
//------------------------------------------------------------------------------
/**
* This method determines the contact intervals given the input observer,
* abberration correction, times, and stepsize.
*
* @param observerID NAIF ID of the observer
* @param minElevation minimum elevation of the GS
* @param obsFrameName frame name for the observer
* @param occultingBodyNames array of occulting bodies
* @param abCorrection aberration correction
* @param s start time
* @param e end time
* @param useEntireIntvl the flag to use entire available interval
* @param useLightTime use light time delay flag
* @param transmit transmit or receive
* @param stepSize stepsize
* @param numIntervals number of intervals returned (output)
* @param starts array of start times for the intervals (output)
* @param ends array of end times for the intervals (output)
*
* Note: initial implementation by Yeerang Lim/KAIST
*
*/
//------------------------------------------------------------------------------
bool EphemManager::GetContactIntervals(const std::string &observerID,
Real minElevation,
const std::string &obsFrameName,
StringArray &occultingBodyNames,
const std::string &abCorrection,
Real s,
Real e,
bool useEntireIntvl,
bool useLightTime,
bool transmit,
Real stepSize,
Integer &numIntervals,
RealArray &starts,
RealArray &ends)
{
Spacecraft *theSc = (Spacecraft*) theObj;
#ifndef __USE_SPICE__
std::string errmsg = "ERROR - cannot compute contact intervals for spacecraft ";
errmsg += theSc->GetName() + " without SPICE included in build!\n";
throw SubscriberException(errmsg);
#else
Integer theNAIFId = theSc->GetIntegerParameter("NAIFId");
std::string theNAIFIdStr = GmatStringUtil::ToString(theNAIFId);
#ifdef DEBUG_CONTACT
MessageInterface::ShowMessage("In GetContactIntervals:\n");
MessageInterface::ShowMessage(" observerID = %s\n", observerID.c_str());
MessageInterface::ShowMessage(" theNAIFIdStr = %s\n", theNAIFIdStr.c_str());
MessageInterface::ShowMessage(" minElevation = %12.10f\n", minElevation);
MessageInterface::ShowMessage(" obsFrameName = %s\n", obsFrameName.c_str());
MessageInterface::ShowMessage(" abCorrection = %s\n", abCorrection.c_str());
MessageInterface::ShowMessage(" s = %12.10f\n", s);
MessageInterface::ShowMessage(" e = %12.10f\n", e);
MessageInterface::ShowMessage(" stepSize = %12.10f\n", stepSize);
#endif
// std::string theNAIFFrameStr = theSc->GetStringParameter(theSc->GetParameterID("SpiceFrameId"));
// window we want to search
SPICEDOUBLE_CELL(initWindow, 200000);
scard_c(0, &initWindow); // reset (empty) the cell
// window we want to search
SPICEDOUBLE_CELL(window, 200000);
scard_c(0, &window); // reset (empty) the cell
Integer obsID;
GmatStringUtil::ToInteger(observerID, obsID);
// NOTE we should find a way to do this once per FindEvents, before the first
// call to this method (for the first observer). Since I can't use SPICE
// types in plugins (i.e. ContactLocator), I can't pass a window out of this
// class. The current way of calling this method each time will be a
// performance hit if there are lots of observers.
GetRequiredCoverageWindow(&window, s, e, useEntireIntvl, abCorrection,
true, useLightTime,
transmit, stepSize, obsID);
std::string theCrdSys = "LATITUDINAL";
std::string theCoord = "LATITUDE";
std::string theRelate = ">";
std::string theOccType = "ANY";
std::string theFront = "";
std::string theFShape = "ELLIPSOID";
std::string theFFrame = "";
std::string theTShape = "POINT";
// CSPICE data
ConstSpiceChar *target = theNAIFIdStr.c_str(); // NAIF Id of the spacecraft
ConstSpiceChar *tframe = obsFrameName.c_str(); // SpiceFrameId for the observer OR ' '?
ConstSpiceChar *abcorr = abCorrection.c_str(); // Aberration correction
ConstSpiceChar *obsrvr = observerID.c_str(); // NAIF ID of the observer
ConstSpiceChar *crdsys = theCrdSys.c_str(); //
ConstSpiceChar *coord = theCoord.c_str(); //
ConstSpiceChar *relate = theRelate.c_str(); //
ConstSpiceChar *occultationType = theOccType.c_str(); //
ConstSpiceChar *fshape = theFShape.c_str(); //
ConstSpiceChar *tshape = theTShape.c_str(); //
ConstSpiceChar *front;
ConstSpiceChar *fframe;
SpiceDouble refval = minElevation * GmatMathConstants::RAD_PER_DEG;
SpiceDouble adjust = 0.0;
SpiceInt nintvls = (SpiceInt)1e6;
SpiceDouble step = stepSize;
SPICEDOUBLE_CELL(result, 200000);
scard_c(0, &result); // reset (empty) the coverage cell
SPICEDOUBLE_CELL(subtracted, 200000);
scard_c(0, &subtracted); // reset (empty) the coverage cell
SPICEDOUBLE_CELL(obsResults, 200000);
scard_c(0, &obsResults); // reset (empty) the coverage cell
SPICEDOUBLE_CELL(occultResults, 200000);
scard_c(0, &occultResults); // reset (empty) the coverage cell
#ifdef DEBUG_CONTACT
MessageInterface::ShowMessage("In GetContactIntervals, about to call gfposc_c\n");
MessageInterface::ShowMessage(" target = %s\n", theNAIFIdStr.c_str());
MessageInterface::ShowMessage(" tframe = %s\n", obsFrameName.c_str());
MessageInterface::ShowMessage(" abcorr = %s\n", abCorrection.c_str());
MessageInterface::ShowMessage(" obsrvr = %s\n", observerID.c_str());
MessageInterface::ShowMessage(" crdsys = %s\n", theCrdSys.c_str());
MessageInterface::ShowMessage(" coord = %s\n", theCoord.c_str());
MessageInterface::ShowMessage(" relate = %s\n", theRelate.c_str());
MessageInterface::ShowMessage(" refval = %12.10f\n", refval);
MessageInterface::ShowMessage(" adjust = %12.10f\n", (Real) adjust);
MessageInterface::ShowMessage(" step = %12.10f\n", stepSize);
MessageInterface::ShowMessage(" nintvls = %d\n", (Integer) nintvls);
#endif
gfposc_c(target, tframe, abcorr, obsrvr, crdsys, coord, relate,
refval, adjust, step, nintvls, &window, &obsResults);
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
SpiceChar err[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling gfposc_c!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
throw SubscriberException(errmsg);
}
SpiceInt szObs = wncard_c(&obsResults);
#ifdef DEBUG_CONTACT
Integer numObs = (Integer) szObs;
MessageInterface::ShowMessage("--- size of obsResults = %d\n",
numObs);
for (Integer ii = 0; ii < numObs; ii++)
{
SpiceDouble sObs, eObs;
wnfetd_c(&obsResults, ii, &sObs, &eObs);
Real ssObs = spice->SpiceTimeToA1(sObs);
Real eeObs = spice->SpiceTimeToA1(eObs);
MessageInterface::ShowMessage("------ start %d = %12.10f\n",
ii, ssObs);
MessageInterface::ShowMessage("------ end %d = %12.10f\n",
ii, eeObs);
}
#endif
if ((Integer) szObs > 0)
{
for (unsigned int ii = 0; ii < occultingBodyNames.size(); ii++ )
{
CelestialBody *body = solarSys->GetBody(occultingBodyNames.at(ii));
theFFrame = body->GetStringParameter(body->GetParameterID("SpiceFrameId"));
Integer bodyNaifId = body->GetIntegerParameter(body->GetParameterID("NAIFId"));
theFront = GmatStringUtil::Trim(GmatStringUtil::ToString(bodyNaifId));
front = theFront.c_str();
fframe = theFFrame.c_str();
#ifdef DEBUG_CONTACT
MessageInterface::ShowMessage("Calling gfoclt_c (for body %s) with:\n",
body->GetName().c_str());
MessageInterface::ShowMessage(" occultationType = %s\n", theOccType.c_str());
MessageInterface::ShowMessage(" front = %s\n", theFront.c_str());
MessageInterface::ShowMessage(" fshape = %s\n", theFShape.c_str());
MessageInterface::ShowMessage(" fframe = %s\n", theFFrame.c_str());
MessageInterface::ShowMessage(" target = %s\n", theNAIFIdStr.c_str());
MessageInterface::ShowMessage(" tshape = %s\n", theTShape.c_str());
MessageInterface::ShowMessage(" tframe = \" \"\n");
MessageInterface::ShowMessage(" abcorr = %s\n", abCorrection.c_str());
MessageInterface::ShowMessage(" obsrvr = %s\n", observerID.c_str());
MessageInterface::ShowMessage(" step = %12.10f\n", stepSize);
#endif
gfoclt_c(occultationType, front, fshape, fframe, target, tshape, " ", abcorr,
obsrvr, step, &obsResults, &occultResults);
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
SpiceChar err[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling gfoclt_c!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
throw SubscriberException(errmsg);
}
#ifdef DEBUG_CONTACT
SpiceInt szOcc = wncard_c(&occultResults);
Integer numOcc = (Integer) szOcc;
MessageInterface::ShowMessage("--- size of occultResults = %d\n",
numOcc);
for (Integer ii = 0; ii < numOcc; ii++)
{
SpiceDouble sOcc, eOcc;
wnfetd_c(&occultResults, ii, &sOcc, &eOcc);
Real ssOcc = spice->SpiceTimeToA1(sOcc);
Real eeOcc = spice->SpiceTimeToA1(eOcc);
MessageInterface::ShowMessage("------ start %d = %12.10f\n",
ii, ssOcc);
MessageInterface::ShowMessage("------ end %d = %12.10f\n",
ii, eeOcc);
}
#endif
wndifd_c(&obsResults, &occultResults, &subtracted);
copy_c(&subtracted, &obsResults);
#ifdef DEBUG_CONTACT
szObs = wncard_c(&obsResults);
numObs = (Integer) szObs;
MessageInterface::ShowMessage("--- After subtracting occultation results, size of obsResults = %d\n",
numObs);
for (Integer ii = 0; ii < numObs; ii++)
{
SpiceDouble sObs, eObs;
wnfetd_c(&obsResults, ii, &sObs, &eObs);
Real ssObs = spice->SpiceTimeToA1(sObs);
Real eeObs = spice->SpiceTimeToA1(eObs);
MessageInterface::ShowMessage("------ start %d = %12.10f\n",
ii, ssObs);
MessageInterface::ShowMessage("------ end %d = %12.10f\n",
ii, eeObs);
}
#endif
// wndifd_c(&obsResults, &occultResults, &result);
}
}
copy_c(&obsResults, &result);
// wndifd_c(&obsResults, &occultResults, &result);
SpiceInt sz = wncard_c(&result);
numIntervals = (Integer) sz;
#ifdef DEBUG_CONTACT
MessageInterface::ShowMessage("--- size of result = %d\n",
numIntervals);
#endif
for (Integer ii = 0; ii < numIntervals; ii++)
{
SpiceDouble s, e;
wnfetd_c(&result, ii, &s, &e);
Real ss = spice->SpiceTimeToA1(s);
Real ee = spice->SpiceTimeToA1(e);
starts.push_back(ss); // OR starts.at(ii) = s? (and same for e)?
ends.push_back(ee);
}
scard_c(0, &initWindow); // reset (empty) the window cell
scard_c(0, &window); // reset (empty) the window cell
scard_c(0, &result); // reset (empty) the window cell
scard_c(0, &subtracted); // reset (empty) the window cell
scard_c(0, &obsResults); // reset (empty) the window cell
scard_c(0, &occultResults); // reset (empty) the window cell
return true;
#endif
}
bool EphemManager::GetCoverage(Real s, Real e,
bool useEntireIntvl,
bool includeAll,
Real &intvlStart,
Real &intvlStop,
Real &cvrStart,
Real &cvrStop)
{
#ifndef __USE_SPICE__
Spacecraft *theSc = (Spacecraft*) theObj;
std::string errmsg = "ERROR - cannot compute occultation intervals for spacecraft ";
errmsg += theSc->GetName() + " without SPICE included in build!\n";
throw SubscriberException(errmsg);
#else
SPICEDOUBLE_CELL(coverWindow, 200000);
scard_c(0, &coverWindow); // reset (empty) the cell
// Get the coverage for the spacecraft (without light time corrections)
GetRequiredCoverageWindow(&coverWindow, s, e, useEntireIntvl, "NONE", includeAll);
// return the start and stop times of the window we are using
intvlStart = intStart;
intvlStop = intStop;
// return the start and stop times of the full coverage window
cvrStart = coverStart;
cvrStop = coverStop;
scard_c(0, &coverWindow); // reset (empty) the cell
return true;
#endif
}
#ifdef __USE_SPICE__
//------------------------------------------------------------------------------
// void GetRequiredCoverageWindow(SpiceCell* w, Real s1, Real e1,
// bool useEntireIntvl,
// const std::string &abCorr = "NONE",
// bool includeAll = true,
// bool lightTimeCorrection = false,
// bool transmitDirection = false,
// Real stepSize = 10.0,
// Integer obsID = -999);
//------------------------------------------------------------------------------
void EphemManager::GetRequiredCoverageWindow(SpiceCell* w, Real s1, Real e1,
bool useEntireIntvl,
const std::string &abCorr,
bool includeAll,
bool lightTimeCorrection,
bool transmitDirection,
Real stepSize,
Integer obsID)
{
#ifdef DEBUG_EM_COVERAGE
MessageInterface::ShowMessage("In GetRequiredCoverageWindow:\n");
MessageInterface::ShowMessage(" s1 = %12.10f\n", s1);
MessageInterface::ShowMessage(" e1 = %12.10f\n", e1);
MessageInterface::ShowMessage(" useEntireIntvl = %s\n",
(useEntireIntvl? "true":"false"));
#endif
// @todo - most of this should be moved to SpiceInterface and
// made very general (for SPK, CK, etc.)
Spacecraft *theSc = (Spacecraft*) theObj;
Integer forNaifId = theSc->GetIntegerParameter("NAIFId");
if (!spice)
spice = new SpiceInterface();
// Which files do we need to check?
StringArray inKernels = fileList;
if (includeAll)
{
StringArray inputKernels = theSc->GetStringArrayParameter("OrbitSpiceKernelName");
for (unsigned int ii = 0; ii < inputKernels.size(); ii++)
inKernels.push_back(inputKernels.at(ii));
}
#ifdef DEBUG_EM_COVERAGE
MessageInterface::ShowMessage("In GetRequiredCoverageWindow:\n");
MessageInterface::ShowMessage(" forNaifId = %d\n", forNaifId);
MessageInterface::ShowMessage(" kernels are:\n");
if (inKernels.empty()) MessageInterface::ShowMessage(" EMPTY!!!!\n");
else
{
for (unsigned int ii = 0; ii < inKernels.size(); ii++)
MessageInterface::ShowMessage(" %d %s\n", (Integer) ii, inKernels.at(ii).c_str());
}
MessageInterface::ShowMessage(" fileList are:\n");
if (fileList.empty()) MessageInterface::ShowMessage(" EMPTY!!!!\n");
else
{
for (unsigned int ii = 0; ii < fileList.size(); ii++)
MessageInterface::ShowMessage(" %d %s\n", (Integer) ii, fileList.at(ii).c_str());
}
#endif
// first check to see if a kernel specified is not loaded; if not,
// try to load it
for (unsigned int ii = 0; ii < inKernels.size(); ii++)
if (!spice->IsLoaded(inKernels.at(ii))) spice->LoadKernel(inKernels.at(ii));
SpiceInt idSpice = forNaifId;
SpiceInt arclen = 4;
SpiceInt typlen = 5;
bool firstInt = true;
bool idOnKernel = false;
ConstSpiceChar *kernelName = NULL;
SpiceInt objId = 0;
SpiceInt numInt = 0;
SpiceChar *kernelType;
SpiceChar *arch;
SpiceDouble b;
SpiceDouble e;
Real bA1;
Real eA1;
SPICEINT_CELL(ids, 200);
SPICEDOUBLE_CELL(cover, 200000);
char kStr[5] = " ";
char aStr[4] = " ";
// start with an empty cell
scard_c(0, &cover); // reset the coverage cell
// look through each kernel
for (unsigned int ii = 0; ii < inKernels.size(); ii++)
{
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Checking coverage for ID %d on kernel %s\n",
forNaifId, (inKernels.at(ii)).c_str());
#endif
// SPICE expects forward slashes for directory separators
std::string kName = GmatStringUtil::Replace(inKernels.at(ii), "\\", "/");
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("--- Setting kernel name to %s\n", kName.c_str());
#endif
kernelName = kName.c_str();
// check the type of kernel
arch = aStr;
kernelType = kStr;
getfat_c(kernelName, arclen, typlen, arch, kernelType);
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error determining type of kernel \"";
errmsg += inKernels.at(ii) + "\". Message received from CSPICE is: [";
errmsg += errStr + "]\n";
reset_c();
delete [] err;
throw SubscriberException(errmsg);
}
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Kernel is of type %s\n",
kernelType);
#endif
// only deal with SPK kernels
if (eqstr_c( kernelType, "spk" ))
{
spkobj_c(kernelName, &ids);
// get the list of objects (IDs) for which data exists in the SPK kernel
for (SpiceInt jj = 0; jj < card_c(&ids); jj++)
{
objId = SPICE_CELL_ELEM_I(&ids,jj);
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Kernel contains data for object %d\n",
(Integer) objId);
#endif
// look to see if this kernel contains data for the object we're interested in
if (objId == idSpice)
{
idOnKernel = true;
break;
}
}
// only deal with kernels containing data for the object we're interested in
if (idOnKernel)
{
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Checking kernel %s for data for object %d\n",
(inKernels.at(ii)).c_str(), (Integer) objId);
#endif
spkcov_c (kernelName, idSpice, &cover);
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error determining coverage for SPK kernel \"";
errmsg += inKernels.at(ii) + "\". Message received from CSPICE is: [";
errmsg += errStr + "]\n";
reset_c();
delete [] err;
throw SubscriberException(errmsg);
}
numInt = wncard_c(&cover);
// We assume that the intervals contained in the resulting window
// are in time order
firstInt = false;
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Number of intervals found = %d\n",
(Integer) numInt);
#endif
}
}
if (firstInt)
{
std::stringstream errmsg("");
errmsg << "Error - no data available for body with NAIF ID " << forNaifId << " on specified SPK kernels\n";
throw SubscriberException(errmsg.str());
}
#ifdef DEBUG_SPK_COVERAGE
else
{
MessageInterface::ShowMessage("Number of intervals found for body with NAIF ID %d = %d\n",
forNaifId, (Integer) numInt);
}
#endif
}
// window we want to search
SPICEDOUBLE_CELL(window, 200000);
scard_c(0, &window); // reset (empty) the window cell
// Get the start and stop times for the complete coverage window
SpiceInt szCoverage = wncard_c(&cover);
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("----- number of intervals in full coverage window is %d\n",
szCoverage);
#endif
if (((Integer) szCoverage) > 0)
{
SpiceDouble s001, e001, s002, e002;
wnfetd_c(&cover, 0, &s001, &e001);
wnfetd_c(&cover, szCoverage-1, &s002, &e002);
coverStart = spice->SpiceTimeToA1(s001);
coverStop = spice->SpiceTimeToA1(e002);
}
else
{
coverStart = 0.0;
coverStop = 0.0;
}
// Set this initially - it will be computed later on if necessary
intStart = coverStart;
intStop = coverStop;
// Figure out the window we want to use
if (useEntireIntvl)
{
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Using ENTIRE interval and the size of the window = %d\n",
(Integer) wncard_c(&cover));
MessageInterface::ShowMessage(" and number of elements in the window = %d\n",
(Integer) card_c(&cover));
for (Integer ii = 0; ii < (Integer) card_c(&cover); ii++)
MessageInterface::ShowMessage(" element %d = %12.10f\n",
ii, (Real) SPICE_CELL_ELEM_D(&cover, (SpiceInt) ii));
#endif
if (lightTimeCorrection)
{
ConstSpiceChar *abcorrection = abCorr.c_str();
// Shift entire window by the light time
SpiceDouble pos[3];
std::string targetID = GmatStringUtil::Trim(GmatStringUtil::ToString(forNaifId));
std::string obsrvrID = GmatStringUtil::Trim(GmatStringUtil::ToString(obsID));
ConstSpiceChar* tID = targetID.c_str();
ConstSpiceChar* oID = obsrvrID.c_str();
Real dir = 1.0; // RECEIVE
if (transmitDirection) // TRANSMIT
dir = -1.0;
// First, get the number of elements (not intervals) in the window
SpiceInt numEl = card_c(&cover);
// SpiceDouble lt[numEl];
SpiceDouble *lt = new SpiceDouble[numEl];
SpiceDouble d = 0.0;
SpiceDouble newD = 0.0;
// Loop over the elements and adjust the time based on the light time
// at that time
for (Integer ii = 0; ii < (Integer) numEl; ii++)
{
d = SPICE_CELL_ELEM_D(&cover, (SpiceInt) ii);
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("Element of cover (%d) = %12.10f\n",
ii, (Real) d);
#endif
spkpos_c(oID, d, "J2000", abcorrection, tID, pos, <[ii]);
if (failed_c())
{
ConstSpiceChar option[] = "SHORT";
SpiceInt numChar = MAX_SHORT_MESSAGE_VALUE;
SpiceChar err[MAX_SHORT_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling spkpos_c!!!";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c(); // reset SPICE error flags
throw SubscriberException(errmsg);
}
newD = d + dir * lt[ii];
SPICE_CELL_SET_D(newD, (SpiceInt) ii, &cover);
}
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("After spkpos_c, the array of light time delays:\n");
for (Integer ii = 0; ii < numEl; ii++)
MessageInterface::ShowMessage(" lt[%d] = %12.10f\n",
ii, lt[ii]);
#endif
// Truncate the search interval (beginning for transmit, end for
// receive)
if (transmitDirection)
wncond_c(lt[0], 0.0, &cover);
else // receive
wncond_c(0.0, lt[numEl-1], &cover);
delete lt;
// Trim to find valid endpoint
Integer trimIterMax = 1000;
Real trimMax = 2.0;
Real trimErrTol = 1.0e-3;
Real trimErr = (Real) GmatRealConstants::INTEGER_MAX;
Real trim = 0.0;
Real trimA = trimMax;
Real trimB = trim;
Integer trimIter = 0;
Integer testInterval = 0;
SpiceDouble lTime;
SPICEDOUBLE_CELL(testWindow, 200010);
scard_c(0, &testWindow); // reset (empty) the test window cell
while (trimIter < trimIterMax)
{
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("BEFORE copying, the size of the cover = %d\n",
(Integer) wncard_c(&cover));
MessageInterface::ShowMessage(" and number of elements in the cover = %d\n",
(Integer) card_c(&cover));
#endif
copy_c(&cover, &testWindow);
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("After copying, the size of the testWindow = %d\n",
(Integer) wncard_c(&testWindow));
MessageInterface::ShowMessage(" and number of elements in the testWindow = %d\n",
(Integer) card_c(&testWindow));
#endif
if (transmitDirection) // transmit
{
wncond_c(0.0, trim, &testWindow);
testInterval = (Integer) card_c(&testWindow) - 1;
}
else // receive
{
wncond_c(trim, 0.0, &testWindow);
testInterval = 0;
}
if (failed_c())
{
ConstSpiceChar option[] = "SHORT";
SpiceInt numChar = MAX_SHORT_MESSAGE_VALUE;
SpiceChar err[MAX_SHORT_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling wncond_c for ";
if (transmitDirection)
errmsg += "transmit!!! ";
else
errmsg += "receive!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c(); // reset SPICE error flags
throw SubscriberException(errmsg);
}
SPICE_CELL_GET_D(&testWindow, testInterval, &d);
spkpos_c(tID, d, "J2000", abcorrection, oID, pos, &lTime);
if (failed_c())
{
// Instead of throwing an error adjust the numbers if necessary
ConstSpiceChar option[] = "SHORT";
SpiceInt numChar = MAX_SHORT_MESSAGE_VALUE;
SpiceChar err[MAX_SHORT_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
// Search the message for "Insufficient ephemeris data" to indicate that
// specific error NOTE: this assumes that this error message text
// will not change in the future
if (eqstr_c(err, "SPICE(SPKINSUFFDATA)"))
{
trimB = trim;
trim = (trimA + trimB) / 2.0;
trimIter++;
// apply trim
if (transmitDirection) // transmit
{
wncond_c(0.0, trim, &testWindow);
testInterval = (Integer) card_c(&testWindow) - 1;
}
else // receive
{
wncond_c(trim, 0.0, &testWindow);
testInterval = 0;
}
reset_c(); // reset SPICE error flags
}
else
{
std::string errStr(err);
std::string errmsg = "Error calling spkpos_c!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c(); // reset SPICE error flags
throw SubscriberException(errmsg);
}
}
else
{
if (trimErr <= trimErrTol)
{
// Copy the test window to the window result that we want
copy_c(&testWindow, &window);
break;
}
trimA = trim;
trim = (trimA + trimB) / 2;
trimErr = GmatMathUtil::Abs(trimA - trimB);
}
}
scard_c(0, &testWindow); // reset (empty) the test window cell
}
else
{
copy_c(&cover, &window);
}
}
else // a window only over the specified time range - no light time etc.
{
// create a window of the specified time span - for
SpiceDouble s = spice->A1ToSpiceTime(s1);
SpiceDouble e = spice->A1ToSpiceTime(e1);
SPICEDOUBLE_CELL(timespan, 200000);
scard_c(0, ×pan); // reset (empty) the coverage cell
// Get the intersection of the timespan window and the coverage window
wninsd_c(s, e, ×pan);
wnintd_c(&cover, ×pan, &window);
scard_c(0, ×pan); // reset (empty) the timespan cell
if (failed_c())
{
ConstSpiceChar option[] = "LONG";
SpiceInt numChar = MAX_LONG_MESSAGE_VALUE;
SpiceChar err[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numChar, err);
std::string errStr(err);
std::string errmsg = "Error calling wninsd_c or wnintd_c!!! ";
errmsg += "Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
throw SubscriberException(errmsg);
}
}
scard_c(0, &cover); // reset (empty) the cover cell
#ifdef DEBUG_ECLIPSE_EVENTS
MessageInterface::ShowMessage("Number of intervals = %d\n", (Integer) numInt);
#endif
// Get the window start and stop times
SpiceInt szWin = wncard_c(&window);
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("----- number of intervals to check times for is %d\n",
szWin);
#endif
if (((Integer) szWin) > 0)
{
SpiceDouble s01, e01, s02, e02;
wnfetd_c(&window, 0, &s01, &e01);
wnfetd_c(&window, szWin-1, &s02, &e02);
intStart = spice->SpiceTimeToA1(s01);
intStop = spice->SpiceTimeToA1(e02);
}
#ifdef DEBUG_SPK_COVERAGE
MessageInterface::ShowMessage("----- intStart = %12.10f\n", intStart);
MessageInterface::ShowMessage("----- intStop = %12.10f\n", intStop);
#endif
copy_c(&window, w);
scard_c(0, &window); // reset (empty) the window cell
}
#endif //#ifdef __USE_SPICE__
//------------------------------------------------------------------------------
// SetObject()
//------------------------------------------------------------------------------
void EphemManager::SetObject(GmatBase *obj)
{
if (!obj->IsOfType("Spacecraft"))
{
throw SubscriberException("Object used for EphemManager must be a Spacecraft.\n");
}
theObj = obj;
theObjName = obj->GetName();
}
//------------------------------------------------------------------------------
// SetEphemType()
//------------------------------------------------------------------------------
void EphemManager::SetEphemType(ManagedEphemType eType)
{
if (eType != SPK)
{
throw SubscriberException("Type used for EphemManager must currently be SPK.\n");
}
theType = eType;
}
//------------------------------------------------------------------------------
// SetCoordinateSystem()
//------------------------------------------------------------------------------
void EphemManager::SetCoordinateSystem(CoordinateSystem *cs)
{
coordSys = cs;
coordSysName = cs->GetName();
}
void EphemManager::SetSolarSystem(SolarSystem *ss)
{
solarSys = ss;
}
//------------------------------------------------------------------------------
// protected methods
//------------------------------------------------------------------------------
// none
| 41.603562 | 116 | 0.534303 | [
"object",
"shape"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.