text
string
size
int64
token_count
int64
/* This file is a part of QVGE - Qt Visual Graph Editor (c) 2016-2019 Ars L. Masiuk (ars.masiuk@gmail.com) It can be used freely, maintaining the information above. */ #include <QInputDialog> #include <QMessageBox> #include "CAttributesEditorUI.h" #include "CPropertyEditorUIBase.h" #include "CNodeEdgePropertiesUI.h" #include "ui_CNodeEdgePropertiesUI.h" #include <qvge/CNodeEditorScene.h> #include <qvge/CNode.h> #include <qvge/CEdge.h> #include <qvge/CDirectEdge.h> #include <qvge/CAttribute.h> #include <qvge/CEditorSceneDefines.h> #include <Const.h> #include <qvge/currentvalues.h> CNodeEdgePropertiesUI::CNodeEdgePropertiesUI(QWidget *parent) : QWidget(parent), m_scene(NULL), m_updateLock(false), ui(new Ui::CNodeEdgePropertiesUI) { m_nodeFactory = new CNode; m_edgeFactory = new CDirectEdge; ui->setupUi(this); //WPaw - dodawanie ikon nodów ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/bankDanych.PNG"), cBankDanych, cBankDanych); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/harmonogram.PNG"), cHarmonogram, cHarmonogram); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/generatorZdarzen.PNG"), cGeneratorZdarzen, cGeneratorZdarzen); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/procedury.PNG"), cProcedury, cProcedury); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zasobStatyczny.PNG"), cZasobStatyczny, cZasobStatyczny); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zegar.PNG"), cZegar, cZegar); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompUniwersalny.PNG"), cKompUniwersalny, cKompUniwersalny); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzetwarzania.PNG"), cKompPrzetwarzania, cKompPrzetwarzania); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzeplywu.PNG"), cKompPrzeplywu, cKompPrzeplywu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompWymuszPrzeplyw.PNG"), cKompWymuszPrzeplywu, cKompWymuszPrzeplywu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/zrodloZasobu.PNG"), cZrodloZasobu, cZrodloZasobu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/celZasobu.PNG"), cCelZasobu, cCelZasobu); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Directed"), tr("Directed (one end)"), "directed"); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Mutual"), tr("Mutual (both ends)"), "mutual"); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Undirected"), tr("None (no ends)"), "undirected"); // ui->EdgeColor->setColorScheme(QSint::OpenOfficeColors()); //ui->EdgeStyle->setUsedRange(Qt::SolidLine, Qt::DashDotDotLine); ui->Edge->addAction (QIcon(cIkonaKanalZdarzen), cKanalZdarzen, cKanalZdarzen); ui->Edge->addAction (QIcon(cIkonaKanalZasobu), cKanalZasobu, cKanalZasobu); ui->Edge->addAction (QIcon(cIkonaKanalDanych), cKanalDanych, cKanalDanych); ui->Edge->addAction (QIcon(cIkonaKanalKomunikacyjny), cKanalKomunikacyjny, cKanalKomunikacyjny); ui->Edge->addAction (QIcon(cIkonaProceduryWbudowane), cProceduryWbudowane, cProceduryWbudowane); ui->Edge->addAction (QIcon(cIkonaDostepnoscZasobu), cDostepnoscZasobu, cDostepnoscZasobu); // font size QList<int> fontSizes = { 5,6,7,8,9,10,11,12,14,16,18,20,24,28,32,36,40,44,48,54,60,66,72,80,88,96 }; ui->LabelFontSize->setValueList(fontSizes); // node size QList<int> nodeSizes = { 5,10,15,20,30,40,50,75,100,150,200 }; ui->NodeSizeX->setValueList(nodeSizes); // update status & tooltips etc. ui->retranslateUi(this); } CNodeEdgePropertiesUI::~CNodeEdgePropertiesUI() { delete m_nodeFactory; delete ui; } void CNodeEdgePropertiesUI::doReadSettings(QSettings& settings) { int pos = settings.value("nodes/splitterPosition", -1).toInt(); /*int*/ pos = settings.value("edges/splitterPosition", -1).toInt(); } void CNodeEdgePropertiesUI::doWriteSettings(QSettings& settings) { } void CNodeEdgePropertiesUI::setScene(CNodeEditorScene* scene) { if (m_scene) onSceneDetached(m_scene); m_scene = scene; setEnabled(m_scene); if (m_scene) onSceneAttached(m_scene); } void CNodeEdgePropertiesUI::connectSignals(CEditorScene* scene) { connect(scene, SIGNAL(sceneChanged()), this, SLOT(onSceneChanged())); connect(scene, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged())); } void CNodeEdgePropertiesUI::updateFromScene(CEditorScene* scene) { // default attrs auto nodeAttrs = scene->getClassAttributes("node", false); ui->NodeFlowShape->selectAction(nodeAttrs["shape"].defaultValue); QSize size = nodeAttrs["size"].defaultValue.toSize(); ui->NodeSizeX->setValue(size.width()); auto edgeAttrs = scene->getClassAttributes("edge", false); // ui->EdgeColor->setColor(edgeAttrs["color"].defaultValue.value<QColor>()); // ui->EdgeWeight->setValue(edgeAttrs["weight"].defaultValue.toDouble()); // ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edgeAttrs["style"].defaultValue.toString())); //ui->EdgeDirection->selectAction(edgeAttrs["direction"].defaultValue); QFont f(edgeAttrs["label.font"].defaultValue.value<QFont>()); ui->LabelFont->setCurrentFont(f); ui->LabelFontSize->setValue(f.pointSize()); ui->LabelColor->setColor(edgeAttrs["label.color"].defaultValue.value<QColor>()); } void CNodeEdgePropertiesUI::onSceneAttached(CEditorScene* scene) { // factories for new items //scene->setActiveItemFactory(m_nodeFactory); //scene->setActiveItemFactory(m_edgeFactory); // default attrs updateFromScene(scene); // connect & go connectSignals(scene); onSceneChanged(); } void CNodeEdgePropertiesUI::onSceneDetached(CEditorScene* scene) { scene->disconnect(this); } void CNodeEdgePropertiesUI::onSceneChanged() { // update active selections if any onSelectionChanged(); } void CNodeEdgePropertiesUI::onSelectionChanged() { if (m_updateLock || m_scene == NULL) return; m_updateLock = true; QList<CEdge*> edges = m_scene->getSelectedEdges(); QList<CNode*> nodes = m_scene->getSelectedNodes(); // nodes ui->NodesBox->setTitle(tr("Selected components (%1)").arg(nodes.count())); if (nodes.count()) { auto node = nodes.first(); ui->NodeFlowShape->selectAction(node->getAttribute("shape")); QSize size = node->getAttribute("size").toSize(); ui->NodeSizeX->setValue(size.width()); } QList<CItem*> nodeItems; // edges ui->EdgesBox->setTitle(tr("Selected connections (%1)").arg(edges.count())); if (edges.count()) { auto edge = edges.first(); // ui->EdgeColor->setColor(edge->getAttribute("color").value<QColor>()); // ui->EdgeWeight->setValue(edge->getAttribute("weight").toDouble()); // ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edge->getAttribute("style").toString())); // ui->EdgeDirection->selectAction(edge->getAttribute("direction")); } QList<CItem*> edgeItems; for (auto item: edges) edgeItems << item; // labels QList<CItem*> itemList; for (auto edgeItem: edges) itemList << edgeItem; for (auto nodeItem: nodes) itemList << nodeItem; for (auto item: itemList) { QFont f(item->getAttribute("label.font").value<QFont>()); ui->LabelFont->setCurrentFont(f); ui->LabelFontSize->setValue(f.pointSize()); ui->LabelFontBold->setChecked(f.bold()); ui->LabelFontItalic->setChecked(f.italic()); ui->LabelFontUnderline->setChecked(f.underline()); ui->LabelColor->setColor(item->getAttribute("label.color").value<QColor>()); break; } // allow updates m_updateLock = false; } void CNodeEdgePropertiesUI::setNodesAttribute(const QByteArray& attrId, const QVariant& v) { QString s = QVariant(v).toString(); if (attrId == "shape") CurrentValues::instance().shape = s; if (m_nodeFactory) m_nodeFactory->setAttribute(attrId, v); if (m_updateLock || m_scene == NULL) return; QList<CNode*> nodes = m_scene->getSelectedNodes(); if (nodes.isEmpty()) return; //WPaw - tu ustawia się atrybut dla konkretnego noda for (auto node : nodes) node->setAttribute(attrId, v); m_scene->addUndoState(); } void CNodeEdgePropertiesUI::setEdgesAttribute(const QByteArray& attrId, const QVariant& v) { if (m_edgeFactory) m_edgeFactory->setAttribute(attrId, v); if (m_updateLock || m_scene == NULL) return; QList<CEdge*> edges = m_scene->getSelectedEdges(); if (edges.isEmpty()) return; for (auto edge : edges) edge->setAttribute(attrId, v); m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_NodeColor_activated(const QColor &color) { setNodesAttribute("color", color); } void CNodeEdgePropertiesUI::on_NodeFlowShape_activated(QVariant data) { setNodesAttribute("shape", data); ui->rButFlow->setChecked(1); // ui->rButFlow->clicked(true); // ui->rButProc->clicked(false); } void CNodeEdgePropertiesUI::on_NodeProcShape_activated(QVariant data) { setNodesAttribute("shape", data); ui->rButProc->setChecked(1); // ui->rButFlow->clicked(false); // ui->rButProc->clicked(true); } void CNodeEdgePropertiesUI::on_NodeSizeX_valueChanged(int /*value*/) { ui->NodeSizeX->blockSignals(true); QSize size(ui->NodeSizeX->value(), ui->NodeSizeX->value()); setNodesAttribute("size", size); ui->NodeSizeX->blockSignals(false); } void CNodeEdgePropertiesUI::on_StrokeColor_activated(const QColor &color) { setNodesAttribute("stroke.color", color); } void CNodeEdgePropertiesUI::on_StrokeStyle_activated(QVariant data) { QString style = CUtils::penStyleToText(data.toInt()); setNodesAttribute("stroke.style", style); } void CNodeEdgePropertiesUI::on_StrokeSize_valueChanged(double value) { setNodesAttribute("stroke.size", value); } void CNodeEdgePropertiesUI::on_EdgeColor_activated(const QColor &color) { setEdgesAttribute("color", color); } void CNodeEdgePropertiesUI::on_EdgeWeight_valueChanged(double value) { setEdgesAttribute("weight", value); } void CNodeEdgePropertiesUI::on_EdgeStyle_activated(QVariant data) { QString style = CUtils::penStyleToText(data.toInt()); setEdgesAttribute("style", style); } void CNodeEdgePropertiesUI::on_Edge_activated(QVariant data) { QString s = QVariant(data).toString(); CurrentValues::instance().connection = s; setEdgesAttribute("style", data); } void CNodeEdgePropertiesUI::on_EdgeDirection_activated(QVariant data) { setEdgesAttribute("direction", data); } void CNodeEdgePropertiesUI::on_LabelFont_activated(const QFont &font) { ui->LabelFontSize->blockSignals(true); ui->LabelFontSize->setValue(font.pointSize()); ui->LabelFontSize->blockSignals(false); if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; for (auto item : items) { item->setAttribute(attr_label_font, font); } m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelColor_activated(const QColor &color) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; for (auto item : items) { item->setAttribute(attr_label_color, color); } m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontSize_valueChanged(int value) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.pointSize() != value) { font.setPointSize(value); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontBold_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.bold() != on) { font.setBold(on); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontItalic_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.italic() != on) { font.setItalic(on); item->setAttribute(attr_label_font, font); item->updateLabelContent(); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontUnderline_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.underline() != on) { font.setUnderline(on); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_NodeFlowShape_windowIconChanged(const QIcon &icon) { QMessageBox qmb; qmb.setText( " duuuap"); qmb.exec(); }
13,463
5,101
#include <iostream> #include <vector> using namespace std; int main() { { vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto elem1 = vec.begin() + 2, elem2 = vec.begin() + 2; elem1 = vec.erase(elem1, elem2); for (auto &v: vec) { cout << v << " "; } cout << "\n"; } { vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto elem1 = vec.end(), elem2 = vec.end(); elem1 = vec.erase(elem1, elem2); for (auto &v: vec) { cout << v << " "; } cout << "\n"; } return 0; }
606
252
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #include "ComponentRosJoystick.hh" #include "smartTimedTaskTrigger.h" //FIXME: implement logging //#include "smartGlobalLogger.hh" // the ace port-factory is used as a default port-mapping #include "ComponentRosJoystickAcePortFactory.hh" // initialize static singleton pointer to zero ComponentRosJoystick* ComponentRosJoystick::_componentRosJoystick = 0; // constructor ComponentRosJoystick::ComponentRosJoystick() { std::cout << "constructor of ComponentRosJoystick\n"; // set all pointer members to NULL joystickActivity = NULL; joystickActivityTrigger = NULL; joystickServiceOut = NULL; //_joy = NULL; stateChangeHandler = NULL; stateSlave = NULL; wiringSlave = NULL; // set default ini parameter values connections.component.name = "ComponentRosJoystick"; connections.component.initialComponentMode = "Neutral"; connections.component.defaultScheduler = "DEFAULT"; connections.component.useLogger = false; connections.joystickServiceOut.serviceName = "JoystickServiceOut"; connections.joystickServiceOut.roboticMiddleware = "ACE_SmartSoft"; connections.joystickActivity.minActFreq = 0.0; connections.joystickActivity.maxActFreq = 0.0; connections.joystickActivity.trigger = "PeriodicTimer"; connections.joystickActivity.periodicActFreq = 10.0; // scheduling default parameters connections.joystickActivity.scheduler = "DEFAULT"; connections.joystickActivity.priority = -1; connections.joystickActivity.cpuAffinity = -1; // initialize members of ComponentRosJoystickROSExtension rosPorts = 0; // initialize members of OpcUaBackendComponentGeneratorExtension // initialize members of PlainOpcUaComponentRosJoystickExtension } void ComponentRosJoystick::addPortFactory(const std::string &name, ComponentRosJoystickPortFactoryInterface *portFactory) { portFactoryRegistry[name] = portFactory; } void ComponentRosJoystick::addExtension(ComponentRosJoystickExtension *extension) { componentExtensionRegistry[extension->getName()] = extension; } SmartACE::SmartComponent* ComponentRosJoystick::getComponentImpl() { return dynamic_cast<ComponentRosJoystickAcePortFactory*>(portFactoryRegistry["ACE_SmartSoft"])->getComponentImpl(); } /** * Notify the component that setup/initialization is finished. * You may call this function from anywhere in the component. * * Set component's internal lifecycle state automaton (if any) into * Alive mode (from here on the component is ready to provide its services) */ void ComponentRosJoystick::setStartupFinished() { stateSlave->setWaitState("Alive"); std::cout << "ComponentDefinition initialization/startup finished." << std::endl; } /** * First connect ALL client ports contained in this component, then start all services: * activate state, push, etc... */ Smart::StatusCode ComponentRosJoystick::connectAndStartAllServices() { Smart::StatusCode status = Smart::SMART_OK; return status; } /** * Start all tasks contained in this component. */ void ComponentRosJoystick::startAllTasks() { // start task JoystickActivity if(connections.joystickActivity.scheduler != "DEFAULT") { ACE_Sched_Params joystickActivity_SchedParams(ACE_SCHED_OTHER, ACE_THR_PRI_OTHER_DEF); if(connections.joystickActivity.scheduler == "FIFO") { joystickActivity_SchedParams.policy(ACE_SCHED_FIFO); joystickActivity_SchedParams.priority(ACE_THR_PRI_FIFO_MIN); } else if(connections.joystickActivity.scheduler == "RR") { joystickActivity_SchedParams.policy(ACE_SCHED_RR); joystickActivity_SchedParams.priority(ACE_THR_PRI_RR_MIN); } joystickActivity->start(joystickActivity_SchedParams, connections.joystickActivity.cpuAffinity); } else { joystickActivity->start(); } } /** * Start all timers contained in this component */ void ComponentRosJoystick::startAllTimers() { } Smart::TaskTriggerSubject* ComponentRosJoystick::getInputTaskTriggerFromString(const std::string &client) { return NULL; } void ComponentRosJoystick::init(int argc, char *argv[]) { try { Smart::StatusCode status; // load initial parameters from ini-file (if found) loadParameter(argc, argv); // initializations of ComponentRosJoystickROSExtension // initializations of OpcUaBackendComponentGeneratorExtension // initializations of PlainOpcUaComponentRosJoystickExtension // initialize all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->initialize(this, argc, argv); } // initialize all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->initialize(this, argc, argv); } ComponentRosJoystickPortFactoryInterface *acePortFactory = portFactoryRegistry["ACE_SmartSoft"]; if(acePortFactory == 0) { std::cerr << "ERROR: acePortFactory NOT instantiated -> exit(-1)" << std::endl; exit(-1); } // this pointer is used for backwards compatibility (deprecated: should be removed as soon as all patterns, including coordination, are moved to port-factory) SmartACE::SmartComponent *component = dynamic_cast<ComponentRosJoystickAcePortFactory*>(acePortFactory)->getComponentImpl(); std::cout << "ComponentDefinition ComponentRosJoystick is named " << connections.component.name << std::endl; if(connections.component.useLogger == true) { //FIXME: use logging //Smart::LOGGER->openLogFileInFolder("data/"+connections.component.name); //Smart::LOGGER->startLogging(); } // create event-test handlers (if needed) // create server ports // TODO: set minCycleTime from Ini-file joystickServiceOut = portFactoryRegistry[connections.joystickServiceOut.roboticMiddleware]->createJoystickServiceOut(connections.joystickServiceOut.serviceName); // create client ports // create InputTaskTriggers and UpcallManagers // create input-handler // create request-handlers // create state pattern stateChangeHandler = new SmartStateChangeHandler(); stateSlave = new SmartACE::StateSlave(component, stateChangeHandler); status = stateSlave->setUpInitialState(connections.component.initialComponentMode); if (status != Smart::SMART_OK) std::cerr << status << "; failed setting initial ComponentMode: " << connections.component.initialComponentMode << std::endl; // activate state slave status = stateSlave->activate(); if(status != Smart::SMART_OK) std::cerr << "ERROR: activate state" << std::endl; wiringSlave = new SmartACE::WiringSlave(component); // add client port to wiring slave // create Task JoystickActivity joystickActivity = new JoystickActivity(component); // configure input-links // configure task-trigger (if task is configurable) if(connections.joystickActivity.trigger == "PeriodicTimer") { // create PeriodicTimerTrigger int microseconds = 1000*1000 / connections.joystickActivity.periodicActFreq; if(microseconds > 0) { Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger(); triggerPtr->attach(joystickActivity); component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds)); // store trigger in class member joystickActivityTrigger = triggerPtr; } else { std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl; } } else if(connections.joystickActivity.trigger == "DataTriggered") { joystickActivityTrigger = getInputTaskTriggerFromString(connections.joystickActivity.inPortRef); if(joystickActivityTrigger != NULL) { joystickActivityTrigger->attach(joystickActivity, connections.joystickActivity.prescale); } else { std::cerr << "ERROR: could not set-up InPort " << connections.joystickActivity.inPortRef << " as activation source for Task JoystickActivity" << std::endl; } } else { // setup default task-trigger as PeriodicTimer Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger(); int microseconds = 1000*1000 / 10.0; if(microseconds > 0) { component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds)); triggerPtr->attach(joystickActivity); // store trigger in class member joystickActivityTrigger = triggerPtr; } else { std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl; } } // link observers with subjects } catch (const std::exception &ex) { std::cerr << "Uncaught std exception" << ex.what() << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } } // run the component void ComponentRosJoystick::run() { stateSlave->acquire("init"); // startup all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->onStartup(); } // startup all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->onStartup(); } stateSlave->release("init"); // do not call this handler within the init state (see above) as this handler internally calls setStartupFinished() (this should be fixed in future) compHandler.onStartup(); // this call blocks until the component is commanded to shutdown stateSlave->acquire("shutdown"); // shutdown all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->onShutdown(); } // shutdown all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->onShutdown(); } if(connections.component.useLogger == true) { //FIXME: use logging //Smart::LOGGER->stopLogging(); } compHandler.onShutdown(); stateSlave->release("shutdown"); } // clean-up component's resources void ComponentRosJoystick::fini() { // unlink all observers // destroy all task instances // unlink all UpcallManagers // unlink the TaskTrigger if(joystickActivityTrigger != NULL){ joystickActivityTrigger->detach(joystickActivity); delete joystickActivity; } // destroy all input-handler // destroy InputTaskTriggers and UpcallManagers // destroy client ports // destroy server ports delete joystickServiceOut; // destroy event-test handlers (if needed) // destroy request-handlers delete stateSlave; // destroy state-change-handler delete stateChangeHandler; // destroy all master/slave ports delete wiringSlave; // destroy all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->destroy(); } // destroy all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->destroy(); } // destruction of ComponentRosJoystickROSExtension // destruction of OpcUaBackendComponentGeneratorExtension // destruction of PlainOpcUaComponentRosJoystickExtension } void ComponentRosJoystick::loadParameter(int argc, char *argv[]) { /* Parameters can be specified via command line --filename=<filename> or -f <filename> With this parameter present: - The component will look for the file in the current working directory, a path relative to the current directory or any absolute path - The component will use the default values if the file cannot be found With this parameter absent: - <Name of Component>.ini will be read from current working directory, if found there - $SMART_ROOT/etc/<Name of Component>.ini will be read otherwise - Default values will be used if neither found in working directory or /etc */ SmartACE::SmartIniParameter parameter; std::ifstream parameterfile; bool parameterFileFound = false; // load parameters try { // if paramfile is given as argument if(parameter.tryAddFileFromArgs(argc,argv,"filename", 'f')) { parameterFileFound = true; std::cout << "parameter file is loaded from an argv argument \n"; } else if(parameter.searchFile("ComponentRosJoystick.ini", parameterfile)) { parameterFileFound = true; std::cout << "load ComponentRosJoystick.ini parameter file\n"; parameter.addFile(parameterfile); } else { std::cout << "WARNING: ComponentRosJoystick.ini parameter file not found! (using default values or command line arguments)\n"; } // add command line arguments to allow overwriting of parameters // from file parameter.addCommandLineArgs(argc,argv,"component"); // initialize the naming service using the command line parameters parsed in the // SmartIniParameter class. The naming service parameters are expected to be in // the "component" parameter group. SmartACE::NAMING::instance()->checkForHelpArg(argc,argv); if(parameterFileFound) { if(SmartACE::NAMING::instance()->init(parameter.getAllParametersFromGroup("component")) != 0) { // initialization of naming service failed throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" ); } } else { if(SmartACE::NAMING::instance()->init(argc, argv) != 0) { // initialization of naming service failed throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" ); } } // print all known parameters // parameter.print(); //--- server port // client port // other parameter --- // load parameter parameter.getString("component", "name", connections.component.name); parameter.getString("component", "initialComponentMode", connections.component.initialComponentMode); if(parameter.checkIfParameterExists("component", "defaultScheduler")) { parameter.getString("component", "defaultScheduler", connections.component.defaultScheduler); } if(parameter.checkIfParameterExists("component", "useLogger")) { parameter.getBoolean("component", "useLogger", connections.component.useLogger); } // load parameters for server JoystickServiceOut parameter.getString("JoystickServiceOut", "serviceName", connections.joystickServiceOut.serviceName); if(parameter.checkIfParameterExists("JoystickServiceOut", "roboticMiddleware")) { parameter.getString("JoystickServiceOut", "roboticMiddleware", connections.joystickServiceOut.roboticMiddleware); } // load parameters for task JoystickActivity parameter.getDouble("JoystickActivity", "minActFreqHz", connections.joystickActivity.minActFreq); parameter.getDouble("JoystickActivity", "maxActFreqHz", connections.joystickActivity.maxActFreq); parameter.getString("JoystickActivity", "triggerType", connections.joystickActivity.trigger); if(connections.joystickActivity.trigger == "PeriodicTimer") { parameter.getDouble("JoystickActivity", "periodicActFreqHz", connections.joystickActivity.periodicActFreq); } else if(connections.joystickActivity.trigger == "DataTriggered") { parameter.getString("JoystickActivity", "inPortRef", connections.joystickActivity.inPortRef); parameter.getInteger("JoystickActivity", "prescale", connections.joystickActivity.prescale); } if(parameter.checkIfParameterExists("JoystickActivity", "scheduler")) { parameter.getString("JoystickActivity", "scheduler", connections.joystickActivity.scheduler); } if(parameter.checkIfParameterExists("JoystickActivity", "priority")) { parameter.getInteger("JoystickActivity", "priority", connections.joystickActivity.priority); } if(parameter.checkIfParameterExists("JoystickActivity", "cpuAffinity")) { parameter.getInteger("JoystickActivity", "cpuAffinity", connections.joystickActivity.cpuAffinity); } // load parameters for ComponentRosJoystickROSExtension // load parameters for OpcUaBackendComponentGeneratorExtension // load parameters for PlainOpcUaComponentRosJoystickExtension // load parameters for all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->loadParameters(parameter); } } catch (const SmartACE::IniParameterError & e) { std::cerr << e.what() << std::endl; } catch (const std::exception &ex) { std::cerr << "Uncaught std::exception: " << ex.what() << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } }
17,596
5,523
// ===================================================================================== // m a p c o n v . c p p // conver a MAPI message to and from an RFC 822/RFC 1521 (mime) internet message // ===================================================================================== #include "pch.hxx" #include "Imnapi.h" #include "Exchrep.h" #include "Mapiconv.h" #include "Error.h" HRESULT HrCopyStream (LPSTREAM lpstmIn, LPSTREAM lpstmOut, ULONG *pcb); // ===================================================================================== // MAPI Message Properties that I want // ===================================================================================== enum { colSenderAddrType, colSenderName, colSenderEMail, colSubject, colDeliverTime, colBody, colPriority, colLast1 }; SizedSPropTagArray (colLast1, sptMessageProps) = { colLast1, { PR_SENDER_ADDRTYPE, PR_SENDER_NAME, PR_SENDER_EMAIL_ADDRESS, PR_SUBJECT, PR_MESSAGE_DELIVERY_TIME, PR_BODY, PR_PRIORITY } }; // ===================================================================================== // MAPI Recip Props // ===================================================================================== enum { colRecipAddrType, colRecipName, colRecipAddress, colRecipType, colLast2 }; SizedSPropTagArray (colLast2, sptRecipProps) = { colLast2, { PR_ADDRTYPE, PR_DISPLAY_NAME, PR_EMAIL_ADDRESS, PR_RECIPIENT_TYPE } }; // ===================================================================================== // MAPI Attachment Props // ===================================================================================== enum { colAttMethod, colAttNum, colAttLongFilename, colAttLongPathname, colAttPathname, colAttTag, colAttFilename, colAttExtension, colAttSize, colLast3 }; SizedSPropTagArray (colLast3, sptAttProps) = { colLast3, { PR_ATTACH_METHOD, PR_ATTACH_NUM, PR_ATTACH_LONG_FILENAME, PR_ATTACH_LONG_PATHNAME, PR_ATTACH_PATHNAME, PR_ATTACH_TAG, PR_ATTACH_FILENAME, PR_ATTACH_EXTENSION, PR_ATTACH_SIZE } }; // ============================================================================================= // StringDup - duplicates a string // ============================================================================================= LPTSTR StringDup (LPCTSTR lpcsz) { // Locals LPTSTR lpszDup; if (lpcsz == NULL) return NULL; INT nLen = lstrlen (lpcsz) + 1; lpszDup = (LPTSTR)malloc (nLen * sizeof (TCHAR)); if (lpszDup) CopyMemory (lpszDup, lpcsz, nLen); return lpszDup; } // ===================================================================================== // HrMapiToImsg // ===================================================================================== HRESULT HrMapiToImsg (LPMESSAGE lpMessage, LPIMSG lpImsg) { // Locals HRESULT hr = S_OK; ULONG cProp, i; LPSPropValue lpMsgPropValue = NULL; LPSRowSet lpRecipRows = NULL, lpAttRows = NULL; LPMAPITABLE lptblRecip = NULL, lptblAtt = NULL; LPATTACH lpAttach = NULL; LPMESSAGE lpMsgAtt = NULL; LPSTREAM lpstmRtfComp = NULL, lpstmRtf = NULL; // Zero init ZeroMemory (lpImsg, sizeof (IMSG)); // Get the propsw hr = lpMessage->GetProps ((LPSPropTagArray)&sptMessageProps, 0, &cProp, &lpMsgPropValue); if (FAILED (hr)) goto exit; // Subject if (PROP_TYPE(lpMsgPropValue[colSubject].ulPropTag) != PT_ERROR) lpImsg->lpszSubject = StringDup (lpMsgPropValue[colSubject].Value.lpszA); // Body if (PROP_TYPE(lpMsgPropValue[colBody].ulPropTag) != PT_ERROR) lpImsg->lpszBody = StringDup (lpMsgPropValue[colBody].Value.lpszA); // RTF if (!FAILED (lpMessage->OpenProperty (PR_RTF_COMPRESSED, (LPIID)&IID_IStream, 0, 0, (LPUNKNOWN *)&lpstmRtfComp))) if (!FAILED (WrapCompressedRTFStream (lpstmRtfComp, 0, &lpstmRtf))) if (!FAILED (CreateStreamOnHFile (NULL, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL, &lpImsg->lpstmRtf))) HrCopyStream (lpstmRtf, lpImsg->lpstmRtf, NULL); // Delivery Time if (PROP_TYPE(lpMsgPropValue[colDeliverTime].ulPropTag) != PT_ERROR) CopyMemory (&lpImsg->ftDelivery, &lpMsgPropValue[colDeliverTime].Value.ft, sizeof (FILETIME)); // Priority lpImsg->wPriority = PRI_NORMAL; if (PROP_TYPE(lpMsgPropValue[colPriority].ulPropTag) != PT_ERROR) { switch (lpMsgPropValue[colPriority].Value.l) { case PRIO_NORMAL: lpImsg->wPriority = PRI_NORMAL; break; case PRIO_URGENT: lpImsg->wPriority = PRI_HIGH; break; case PRIO_NONURGENT: default: lpImsg->wPriority = PRI_LOW; break; } } // Get the recipient table hr = lpMessage->GetRecipientTable (0, &lptblRecip); if (FAILED (hr)) goto exit; // Get all the rows of the recipient table hr = HrQueryAllRows (lptblRecip, (LPSPropTagArray)&sptRecipProps, NULL, NULL, 0, &lpRecipRows); if (FAILED (hr)) goto exit; // Allocate Recipient Array lpImsg->cAddress = lpRecipRows->cRows + 1; lpImsg->lpIaddr = (LPIADDRINFO)malloc (sizeof (IADDRINFO) * lpImsg->cAddress); if (lpImsg->lpIaddr == NULL) goto exit; // Originator of the message "From: " lpImsg->lpIaddr[0].dwType = IADDR_FROM; if (PROP_TYPE(lpMsgPropValue[colSenderName].ulPropTag) != PT_ERROR) { lpImsg->lpIaddr[0].lpszDisplay = StringDup (lpMsgPropValue[colSenderName].Value.lpszA); lpImsg->lpIaddr[0].lpszAddress = StringDup (lpMsgPropValue[colSenderName].Value.lpszA); } if (PROP_TYPE(lpMsgPropValue[colSenderEMail].ulPropTag) != PT_ERROR && PROP_TYPE(lpMsgPropValue[colSenderAddrType].ulPropTag) != PT_ERROR && lstrcmpi (lpMsgPropValue[colSenderAddrType].Value.lpszA, "SMTP") == 0) { lpImsg->lpIaddr[0].lpszAddress = StringDup (lpMsgPropValue[colSenderEMail].Value.lpszA); } // Add in the rest of the recipients for (i=0; i<lpRecipRows->cRows; i++) { assert (i+1 < lpImsg->cAddress); if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipType].ulPropTag) != PT_ERROR) { switch (lpRecipRows->aRow[i].lpProps[colRecipType].Value.ul) { case MAPI_TO: lpImsg->lpIaddr[i+1].dwType = IADDR_TO; break; case MAPI_ORIG: lpImsg->lpIaddr[i+1].dwType = IADDR_FROM; break; case MAPI_CC: lpImsg->lpIaddr[i+1].dwType = IADDR_CC; break; case MAPI_BCC: lpImsg->lpIaddr[i+1].dwType = IADDR_BCC; break; default: Assert (FALSE); lpImsg->lpIaddr[i+1].dwType = IADDR_TO; break; } } else lpImsg->lpIaddr[i+1].dwType = IADDR_TO; if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipName].ulPropTag) != PT_ERROR) { lpImsg->lpIaddr[i+1].lpszDisplay = StringDup (lpRecipRows->aRow[i].lpProps[colRecipName].Value.lpszA); lpImsg->lpIaddr[i+1].lpszAddress = StringDup (lpRecipRows->aRow[i].lpProps[colRecipName].Value.lpszA); } if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipName].ulPropTag) != PT_ERROR && PROP_TYPE(lpMsgPropValue[colRecipAddrType].ulPropTag) != PT_ERROR && lstrcmpi (lpMsgPropValue[colRecipAddrType].Value.lpszA, "SMTP") == 0) { lpImsg->lpIaddr[i+1].lpszAddress = StringDup (lpRecipRows->aRow[i].lpProps[colRecipAddress].Value.lpszA); } } // Free Rows if (lpRecipRows) FreeProws (lpRecipRows); lpRecipRows = NULL; // Attachments hr = lpMessage->GetAttachmentTable (0, &lptblAtt); if (FAILED (hr)) goto exit; // Get all the rows of the recipient table hr = HrQueryAllRows (lptblAtt, (LPSPropTagArray)&sptAttProps, NULL, NULL, 0, &lpAttRows); if (FAILED (hr)) goto exit; // Allocate files list if (lpAttRows->cRows == 0) goto exit; // Allocate memory lpImsg->cAttach = lpAttRows->cRows; lpImsg->lpIatt = (LPIATTINFO)malloc (sizeof (IATTINFO) * lpImsg->cAttach); if (lpImsg->lpIatt == NULL) goto exit; // Zero init ZeroMemory (lpImsg->lpIatt, sizeof (IATTINFO) * lpImsg->cAttach); // Walk the rows for (i=0; i<lpAttRows->cRows; i++) { if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttMethod].ulPropTag) != PT_ERROR && PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttNum].ulPropTag) != PT_ERROR) { // Basic Properties if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttPathname].ulPropTag) != PT_ERROR) lpImsg->lpIatt[i].lpszPathName = StringDup (lpAttRows->aRow[i].lpProps[colAttPathname].Value.lpszA); if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttFilename].ulPropTag) != PT_ERROR) lpImsg->lpIatt[i].lpszFileName = StringDup (lpAttRows->aRow[i].lpProps[colAttFilename].Value.lpszA); if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttExtension].ulPropTag) != PT_ERROR) lpImsg->lpIatt[i].lpszExt = StringDup (lpAttRows->aRow[i].lpProps[colAttExtension].Value.lpszA); // Open the attachment hr = lpMessage->OpenAttach (lpAttRows->aRow[i].lpProps[colAttNum].Value.l, NULL, MAPI_BEST_ACCESS, &lpAttach); if (FAILED (hr)) { lpImsg->lpIatt[i].fError = TRUE; continue; } // Handle the attachment method switch (lpAttRows->aRow[i].lpProps[colAttMethod].Value.ul) { case NO_ATTACHMENT: lpImsg->lpIatt[i].dwType = 0; lpImsg->lpIatt[i].fError = TRUE; break; case ATTACH_BY_REF_RESOLVE: case ATTACH_BY_VALUE: lpImsg->lpIatt[i].dwType = IATT_FILE; hr = lpAttach->OpenProperty (PR_ATTACH_DATA_BIN, (LPIID)&IID_IStream, 0, 0, (LPUNKNOWN *)&lpImsg->lpIatt[i].lpstmAtt); if (FAILED (hr)) lpImsg->lpIatt[i].fError = TRUE; break; case ATTACH_BY_REF_ONLY: case ATTACH_BY_REFERENCE: lpImsg->lpIatt[i].dwType = IATT_FILE; hr = CreateStreamOnHFile (lpImsg->lpIatt[i].lpszPathName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL, &lpImsg->lpIatt[i].lpstmAtt); if (FAILED (hr)) lpImsg->lpIatt[i].fError = TRUE; break; case ATTACH_EMBEDDED_MSG: lpImsg->lpIatt[i].dwType = IATT_MSG; hr = lpAttach->OpenProperty (PR_ATTACH_DATA_OBJ, (LPIID)&IID_IMessage, 0, 0, (LPUNKNOWN *)&lpMsgAtt); if (FAILED (hr) || lpMsgAtt == NULL) lpImsg->lpIatt[i].fError = TRUE; else { lpImsg->lpIatt[i].lpImsg = (LPIMSG)malloc (sizeof (IMSG)); if (lpImsg->lpIatt[i].lpImsg == NULL) lpImsg->lpIatt[i].fError = TRUE; else { hr = HrMapiToImsg (lpMsgAtt, lpImsg->lpIatt[i].lpImsg); if (FAILED (hr)) lpImsg->lpIatt[i].fError = TRUE; } lpMsgAtt->Release (); lpMsgAtt = NULL; } break; case ATTACH_OLE: default: lpImsg->lpIatt[i].dwType = IATT_OLE; lpImsg->lpIatt[i].fError = TRUE; break; } // Free Attachment if (lpAttach) lpAttach->Release (); lpAttach = NULL; } } exit: // Cleanup if (lpAttach) lpAttach->Release (); if (lptblAtt) lptblAtt->Release (); if (lpAttRows) FreeProws (lpAttRows); if (lpRecipRows) FreeProws (lpRecipRows); if (lpMsgPropValue) MAPIFreeBuffer (lpMsgPropValue); if (lptblRecip) lptblRecip->Release (); if (lpMsgAtt) lpMsgAtt->Release (); if (lpstmRtfComp) lpstmRtfComp->Release (); if (lpstmRtf) lpstmRtf->Release (); // Done return hr; } void AssertSzFn(LPSTR szMsg, LPSTR szFile, int nLine) { static const char rgch1[] = "File %s, line %d:"; static const char rgch2[] = "Unknown file:"; static const char szAssert[] = "Assert Failure"; char rgch[512]; char *lpsz; int ret, cch; if (szFile) wnsprintf(rgch, ARRAYSIZE(rgch),rgch1, szFile, nLine); else StrCpyN(rgch, rgch2,ARRAYSIZE(rgch)); cch = lstrlen(rgch); Assert(lstrlen(szMsg)<(512-cch-3)); lpsz = &rgch[cch]; *lpsz++ = '\n'; *lpsz++ = '\n'; StrCpyN(lpsz, szMsg, (ARRAYSIZE(rgch)-cch-2)); ret = MessageBox(GetActiveWindow(), rgch, szAssert, MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SYSTEMMODAL|MB_SETFOREGROUND); if (ret != IDIGNORE) DebugBreak(); /* Force a hard exit w/ a GP-fault so that Dr. Watson generates a nice stack trace log. */ if (ret == IDABORT) *(LPBYTE)0 = 1; // write to address 0 causes GP-fault } // ===================================================================================== // HrCopyStream - caller must do the commit // ===================================================================================== HRESULT HrCopyStream (LPSTREAM lpstmIn, LPSTREAM lpstmOut, ULONG *pcb) { // Locals HRESULT hr = S_OK; BYTE buf[4096]; ULONG cbRead = 0, cbTotal = 0; do { hr = lpstmIn->Read (buf, sizeof (buf), &cbRead); if (FAILED (hr)) goto exit; if (cbRead == 0) break; hr = lpstmOut->Write (buf, cbRead, NULL); if (FAILED (hr)) goto exit; cbTotal += cbRead; } while (cbRead == sizeof (buf)); exit: if (pcb) *pcb = cbTotal; return hr; }
15,092
5,489
/* * Copyright 2011, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: * Oliver Tappe <zooey@hirschkaefer.de> */ #include <package/ActivateRepositoryCacheJob.h> #include <File.h> #include <package/Context.h> namespace BPackageKit { namespace BPrivate { ActivateRepositoryCacheJob::ActivateRepositoryCacheJob(const BContext& context, const BString& title, const BEntry& fetchedRepoCacheEntry, const BString& repositoryName, const BDirectory& targetDirectory) : inherited(context, title), fFetchedRepoCacheEntry(fetchedRepoCacheEntry), fRepositoryName(repositoryName), fTargetDirectory(targetDirectory) { } ActivateRepositoryCacheJob::~ActivateRepositoryCacheJob() { } status_t ActivateRepositoryCacheJob::Execute() { status_t result = fFetchedRepoCacheEntry.MoveTo(&fTargetDirectory, fRepositoryName.String(), true); if (result != B_OK) return result; // TODO: propagate some repository attributes to file attributes return B_OK; } } // namespace BPrivate } // namespace BPackageKit
1,068
353
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorCubeFilter.h" #include "SkColorPriv.h" #include "SkOnce.h" #include "SkOpts.h" #include "SkReadBuffer.h" #include "SkUnPreMultiply.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrCoordTransform.h" #include "GrInvariantOutput.h" #include "GrTexturePriv.h" #include "SkGr.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramDataManager.h" #include "glsl/GrGLSLUniformHandler.h" #endif /////////////////////////////////////////////////////////////////////////////// namespace { int32_t SkNextColorCubeUniqueID() { static int32_t gColorCubeUniqueID; // do a loop in case our global wraps around, as we never want to return a 0 int32_t genID; do { genID = sk_atomic_inc(&gColorCubeUniqueID) + 1; } while (0 == genID); return genID; } } // end namespace static const int MIN_CUBE_SIZE = 4; static const int MAX_CUBE_SIZE = 64; static bool is_valid_3D_lut(SkData* cubeData, int cubeDimension) { size_t minMemorySize = sizeof(uint8_t) * 4 * cubeDimension * cubeDimension * cubeDimension; return (cubeDimension >= MIN_CUBE_SIZE) && (cubeDimension <= MAX_CUBE_SIZE) && (nullptr != cubeData) && (cubeData->size() >= minMemorySize); } sk_sp<SkColorFilter> SkColorCubeFilter::Make(sk_sp<SkData> cubeData, int cubeDimension) { if (!is_valid_3D_lut(cubeData.get(), cubeDimension)) { return nullptr; } return sk_sp<SkColorFilter>(new SkColorCubeFilter(std::move(cubeData), cubeDimension)); } SkColorCubeFilter::SkColorCubeFilter(sk_sp<SkData> cubeData, int cubeDimension) : fCubeData(std::move(cubeData)) , fUniqueID(SkNextColorCubeUniqueID()) , fCache(cubeDimension) {} uint32_t SkColorCubeFilter::getFlags() const { return this->INHERITED::getFlags() | kAlphaUnchanged_Flag; } SkColorCubeFilter::ColorCubeProcesingCache::ColorCubeProcesingCache(int cubeDimension) : fCubeDimension(cubeDimension) { fColorToIndex[0] = fColorToIndex[1] = nullptr; fColorToFactors[0] = fColorToFactors[1] = nullptr; fColorToScalar = nullptr; } void SkColorCubeFilter::ColorCubeProcesingCache::getProcessingLuts( const int* (*colorToIndex)[2], const SkScalar* (*colorToFactors)[2], const SkScalar** colorToScalar) { fLutsInitOnce(SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts, this); SkASSERT((fColorToIndex[0] != nullptr) && (fColorToIndex[1] != nullptr) && (fColorToFactors[0] != nullptr) && (fColorToFactors[1] != nullptr) && (fColorToScalar != nullptr)); (*colorToIndex)[0] = fColorToIndex[0]; (*colorToIndex)[1] = fColorToIndex[1]; (*colorToFactors)[0] = fColorToFactors[0]; (*colorToFactors)[1] = fColorToFactors[1]; (*colorToScalar) = fColorToScalar; } void SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts( SkColorCubeFilter::ColorCubeProcesingCache* cache) { static const SkScalar inv8bit = SkScalarInvert(SkIntToScalar(255)); // We need 256 int * 2 for fColorToIndex, so a total of 512 int. // We need 256 SkScalar * 2 for fColorToFactors and 256 SkScalar // for fColorToScalar, so a total of 768 SkScalar. cache->fLutStorage.reset(512 * sizeof(int) + 768 * sizeof(SkScalar)); uint8_t* storage = cache->fLutStorage.get(); cache->fColorToIndex[0] = (int*)storage; cache->fColorToIndex[1] = cache->fColorToIndex[0] + 256; cache->fColorToFactors[0] = (SkScalar*)(storage + (512 * sizeof(int))); cache->fColorToFactors[1] = cache->fColorToFactors[0] + 256; cache->fColorToScalar = cache->fColorToFactors[1] + 256; SkScalar size = SkIntToScalar(cache->fCubeDimension); SkScalar scale = (size - SK_Scalar1) * inv8bit; for (int i = 0; i < 256; ++i) { SkScalar index = scale * i; cache->fColorToIndex[0][i] = SkScalarFloorToInt(index); cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i] + 1; cache->fColorToScalar[i] = inv8bit * i; if (cache->fColorToIndex[1][i] < cache->fCubeDimension) { cache->fColorToFactors[1][i] = index - SkIntToScalar(cache->fColorToIndex[0][i]); cache->fColorToFactors[0][i] = SK_Scalar1 - cache->fColorToFactors[1][i]; } else { cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i]; cache->fColorToFactors[0][i] = SK_Scalar1; cache->fColorToFactors[1][i] = 0; } } } void SkColorCubeFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const { const int* colorToIndex[2]; const SkScalar* colorToFactors[2]; const SkScalar* colorToScalar; fCache.getProcessingLuts(&colorToIndex, &colorToFactors, &colorToScalar); SkOpts::color_cube_filter_span(src, count, dst, colorToIndex, colorToFactors, fCache.cubeDimension(), (const SkColor*)fCubeData->data()); } sk_sp<SkFlattenable> SkColorCubeFilter::CreateProc(SkReadBuffer& buffer) { int cubeDimension = buffer.readInt(); auto cubeData(buffer.readByteArrayAsData()); if (!buffer.validate(is_valid_3D_lut(cubeData.get(), cubeDimension))) { return nullptr; } return Make(std::move(cubeData), cubeDimension); } void SkColorCubeFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeInt(fCache.cubeDimension()); buffer.writeDataAsByteArray(fCubeData.get()); } #ifndef SK_IGNORE_TO_STRING void SkColorCubeFilter::toString(SkString* str) const { str->append("SkColorCubeFilter "); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU class GrColorCubeEffect : public GrFragmentProcessor { public: static const GrFragmentProcessor* Create(GrTexture* colorCube) { return (nullptr != colorCube) ? new GrColorCubeEffect(colorCube) : nullptr; } virtual ~GrColorCubeEffect(); const char* name() const override { return "ColorCube"; } int colorCubeSize() const { return fColorCubeAccess.getTexture()->width(); } void onComputeInvariantOutput(GrInvariantOutput*) const override; class GLSLProcessor : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs&) override; static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*); protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: GrGLSLProgramDataManager::UniformHandle fColorCubeSizeUni; GrGLSLProgramDataManager::UniformHandle fColorCubeInvSizeUni; typedef GrGLSLFragmentProcessor INHERITED; }; private: virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override; GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; bool onIsEqual(const GrFragmentProcessor&) const override { return true; } GrColorCubeEffect(GrTexture* colorCube); GrTextureAccess fColorCubeAccess; typedef GrFragmentProcessor INHERITED; }; /////////////////////////////////////////////////////////////////////////////// GrColorCubeEffect::GrColorCubeEffect(GrTexture* colorCube) : fColorCubeAccess(colorCube, GrTextureParams::kBilerp_FilterMode) { this->initClassID<GrColorCubeEffect>(); this->addTextureAccess(&fColorCubeAccess); } GrColorCubeEffect::~GrColorCubeEffect() { } void GrColorCubeEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GLSLProcessor::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrColorCubeEffect::onCreateGLSLInstance() const { return new GLSLProcessor; } void GrColorCubeEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const { inout->setToUnknown(GrInvariantOutput::kWill_ReadInput); } /////////////////////////////////////////////////////////////////////////////// void GrColorCubeEffect::GLSLProcessor::emitCode(EmitArgs& args) { if (nullptr == args.fInputColor) { args.fInputColor = "vec4(1)"; } GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; fColorCubeSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat_GrSLType, kDefault_GrSLPrecision, "Size"); const char* colorCubeSizeUni = uniformHandler->getUniformCStr(fColorCubeSizeUni); fColorCubeInvSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat_GrSLType, kDefault_GrSLPrecision, "InvSize"); const char* colorCubeInvSizeUni = uniformHandler->getUniformCStr(fColorCubeInvSizeUni); const char* nonZeroAlpha = "nonZeroAlpha"; const char* unPMColor = "unPMColor"; const char* cubeIdx = "cubeIdx"; const char* cCoords1 = "cCoords1"; const char* cCoords2 = "cCoords2"; // Note: if implemented using texture3D in OpenGL ES older than OpenGL ES 3.0, // the shader might need "#extension GL_OES_texture_3D : enable". GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; // Unpremultiply color fragBuilder->codeAppendf("\tfloat %s = max(%s.a, 0.00001);\n", nonZeroAlpha, args.fInputColor); fragBuilder->codeAppendf("\tvec4 %s = vec4(%s.rgb / %s, %s);\n", unPMColor, args.fInputColor, nonZeroAlpha, nonZeroAlpha); // Fit input color into the cube. fragBuilder->codeAppendf( "vec3 %s = vec3(%s.rg * vec2((%s - 1.0) * %s) + vec2(0.5 * %s), %s.b * (%s - 1.0));\n", cubeIdx, unPMColor, colorCubeSizeUni, colorCubeInvSizeUni, colorCubeInvSizeUni, unPMColor, colorCubeSizeUni); // Compute y coord for for texture fetches. fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (floor(%s.b) + %s.g) * %s);\n", cCoords1, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (ceil(%s.b) + %s.g) * %s);\n", cCoords2, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); // Apply the cube. fragBuilder->codeAppendf("%s = vec4(mix(", args.fOutputColor); fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords1); fragBuilder->codeAppend(".bgr, "); fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords2); // Premultiply color by alpha. Note that the input alpha is not modified by this shader. fragBuilder->codeAppendf(".bgr, fract(%s.b)) * vec3(%s), %s.a);\n", cubeIdx, nonZeroAlpha, args.fInputColor); } void GrColorCubeEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { const GrColorCubeEffect& colorCube = proc.cast<GrColorCubeEffect>(); SkScalar size = SkIntToScalar(colorCube.colorCubeSize()); pdman.set1f(fColorCubeSizeUni, SkScalarToFloat(size)); pdman.set1f(fColorCubeInvSizeUni, SkScalarToFloat(SkScalarInvert(size))); } void GrColorCubeEffect::GLSLProcessor::GenKey(const GrProcessor& proc, const GrGLSLCaps&, GrProcessorKeyBuilder* b) { } const GrFragmentProcessor* SkColorCubeFilter::asFragmentProcessor(GrContext* context) const { static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; GrUniqueKey::Builder builder(&key, kDomain, 2); builder[0] = fUniqueID; builder[1] = fCache.cubeDimension(); builder.finish(); GrSurfaceDesc desc; desc.fWidth = fCache.cubeDimension(); desc.fHeight = fCache.cubeDimension() * fCache.cubeDimension(); desc.fConfig = kRGBA_8888_GrPixelConfig; desc.fIsMipMapped = false; SkAutoTUnref<GrTexture> textureCube( context->textureProvider()->findAndRefTextureByUniqueKey(key)); if (!textureCube) { textureCube.reset(context->textureProvider()->createTexture( desc, SkBudgeted::kYes, fCubeData->data(), 0)); if (textureCube) { context->textureProvider()->assignUniqueKeyToTexture(key, textureCube); } else { return nullptr; } } return GrColorCubeEffect::Create(textureCube); } #endif
12,639
4,267
/**************************************************** * Template for coding contests * * Author : Sanjeev Sharma * * Email : thedevelopersanjeev@gmail.com * *****************************************************/ #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("fast-math") #pragma GCC target("sse4") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define deb(x) cout << #x << " is " << x << "\n" #define int long long #define mod 1000000007 const double PI = 2 * acos(0.0); const long long INF = 1e18L + 5; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class... Args> auto create(size_t n, Args&&... args) { if constexpr (sizeof...(args) == 1) return vector(n, args...); else return vector(n, create(args...)); } template <typename... T> void read(T&... args) { ((cin >> args), ...); } template <typename... T> void write(T&&... args) { ((cout << args), ...); } struct segtree { int size; vector<int> tree; void init(int n) { size = 1; while (size < n) size *= 2; tree.assign(2 * size, 0LL); } void set(int i, int v, int x, int lx, int rx) { if (rx - lx == 1) { tree[x] = v; return; } int mx = lx + (rx - lx) / 2; if (i < mx) { set(i, v, 2 * x + 1, lx, mx); } else { set(i, v, 2 * x + 2, mx, rx); } tree[x] = tree[2 * x + 1] + tree[2 * x + 2]; } int sum(int l, int r, int x, int lx, int rx) { if (lx >= r || rx <= l) return 0; if (lx >= l && rx <= r) return tree[x]; int mx = lx + (rx - lx) / 2; return sum(l, r, 2 * x + 1, lx, mx) + sum(l, r, 2 * x + 2, mx, rx); } int sum(int l, int r) { return sum(l, r, 0, 0, size); } void set(int i, int v) { set(i, v, 0, 0, size); } }; void solve() { int n, m, a, b, c; read(n, m); segtree st; st.init(n); vector<int> arr(n); for (int i = 0; i < n; i++) { read(arr[i]); st.set(i, arr[i]); } while (m--) { read(a, b, c); if (a == 1) { st.set(b, c); } else { write(st.sum(b, c), "\n"); } } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif solve(); return 0; }
2,802
1,104
#include "Enemy.hpp" namespace OgrO // Namespace com o nome do jogo. { namespace PhysicalEntities // Namespace do Pacote Entities. { namespace Characters // Namespace do Pacote Personagens. { namespace Enemies // Namespace do Pacote Enemies. { // Construtora da classe Enemy. Enemy::Enemy(Utilities::gameVector2F pos, Utilities::gameVector2F s, const char *tPath, unsigned int life) : Character(pos, s, tPath, life), timeReference(0), projectileInterval(0) { } Enemy::Enemy(nlohmann::json source) : Enemy(Utilities::gameVector2F{static_cast<float>(source["position x"]), static_cast<float>(source["position y"])}, Utilities::gameVector2F{static_cast<float>(source["speed x"]), static_cast<float>(source["speed y"])}, "", static_cast<unsigned int>(source["life"])) { } // Destrutora da classe Enemy. Enemy::~Enemy() { } // Método carrega a textura do enemy na window e inicializa gerenciadores do mesmo. void Enemy::initialize() { // Carrega textura no player. pGraphicManager->loadAsset(texturePath); // Retorna dimensão da imagem. dimension = pGraphicManager->getDimensionsOfAsset(texturePath); // Adiciona enemy na lista de entidades físicas colidiveis. pCollisionManager->addToLCollidablesPhysicalEntities((this)); } void Enemy::update(float t) { } // Método verifica colisão entre dois objetos da classe Entidade Física. void Enemy::collided(int idOther, Utilities::gameVector2F positionOther, Utilities::gameVector2F dimensionOther) { // Caso colida com Enemy. if ((idOther == 102) || (idOther == 103)) { // Cálculo da distância entre os enemy no momento da colisão. Utilities::gameVector2F distance = position - positionOther; // Medida para não manter um enemy preso dentro do outro. position += distance * (1 / 2); // std::cout << "OBJETO ENEMY >>> COLISAO COM OBJETO ENEMY." << std::endl; // Muda o sentido da velocidade em x. speed.coordX *= -1; // Muda o sentido da velocidade em y. speed.coordY *= -1; } } } } } }
3,018
746
/* Copyright (c) 2017-2022, Hans Erik Thrane */ #pragma once #include <arpa/inet.h> #include "roq/api.hpp" #include "roq/client.hpp" // note! thin wrappers around libzmq #include "roq/samples/zeromq/zmq/context.hpp" #include "roq/samples/zeromq/zmq/socket.hpp" namespace roq { namespace samples { namespace zeromq { // strategy implementation class Strategy final : public client::Handler { public: explicit Strategy(client::Dispatcher &); Strategy(Strategy &&) = default; Strategy(const Strategy &) = delete; protected: void operator()(const Event<TopOfBook> &) override; private: client::Dispatcher &dispatcher_; zmq::Context context_; zmq::Socket socket_; }; } // namespace zeromq } // namespace samples } // namespace roq
757
264
/* * Copyright 2014-2019 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <functional> #include <limits.h> #include <gtest/gtest.h> extern "C" { #include "util/aeron_prop_util.h" } class PropTest : public testing::Test { public: PropTest() { } virtual ~PropTest() { } }; TEST_F(PropTest, shouldNotParseInvalidNumber) { uint64_t value = 0; EXPECT_EQ(aeron_parse_size64(nullptr, &value), -1); EXPECT_EQ(aeron_parse_size64("", &value), -1); EXPECT_EQ(aeron_parse_size64("rubbish", &value), -1); EXPECT_EQ(aeron_parse_size64("-8", &value), -1); EXPECT_EQ(aeron_parse_size64("123Z", &value), -1); EXPECT_EQ(aeron_parse_size64("k", &value), -1); } TEST_F(PropTest, shouldParseValidNumber) { uint64_t value = 0; EXPECT_EQ(aeron_parse_size64("0", &value), 0); EXPECT_EQ(value, (uint64_t)0); EXPECT_EQ(aeron_parse_size64("1", &value), 0); EXPECT_EQ(value, (uint64_t)1); EXPECT_EQ(aeron_parse_size64("77777777", &value), 0); EXPECT_EQ(value, (uint64_t)77777777); } TEST_F(PropTest, shouldParseValidQualifiedNumber) { uint64_t value = 0; EXPECT_EQ(aeron_parse_size64("0k", &value), 0); EXPECT_EQ(value, (uint64_t)0); EXPECT_EQ(aeron_parse_size64("1k", &value), 0); EXPECT_EQ(value, (uint64_t)1024); EXPECT_EQ(aeron_parse_size64("64k", &value), 0); EXPECT_EQ(value, (uint64_t)64 * 1024); EXPECT_EQ(aeron_parse_size64("0m", &value), 0); EXPECT_EQ(value, (uint64_t)0); EXPECT_EQ(aeron_parse_size64("1m", &value), 0); EXPECT_EQ(value, (uint64_t)1024 * 1024); EXPECT_EQ(aeron_parse_size64("64m", &value), 0); EXPECT_EQ(value, (uint64_t)64 * 1024 * 1024); EXPECT_EQ(aeron_parse_size64("0g", &value), 0); EXPECT_EQ(value, (uint64_t)0); EXPECT_EQ(aeron_parse_size64("1g", &value), 0); EXPECT_EQ(value, (uint64_t)1024 * 1024 * 1024); EXPECT_EQ(aeron_parse_size64("64g", &value), 0); EXPECT_EQ(value, (uint64_t)64 * 1024 * 1024 * 1024); } TEST_F(PropTest, shouldNotParseInvalidDuration) { uint64_t duration_ns = 0; EXPECT_EQ(aeron_parse_duration_ns(nullptr, &duration_ns), -1); EXPECT_EQ(aeron_parse_duration_ns("", &duration_ns), -1); EXPECT_EQ(aeron_parse_duration_ns("rubbish", &duration_ns), -1); EXPECT_EQ(aeron_parse_duration_ns("-8", &duration_ns), -1); EXPECT_EQ(aeron_parse_duration_ns("123ps", &duration_ns), -1); EXPECT_EQ(aeron_parse_duration_ns("s", &duration_ns), -1); } TEST_F(PropTest, shouldParseValidDuration) { uint64_t duration_ns = 0; EXPECT_EQ(aeron_parse_duration_ns("0", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)0); EXPECT_EQ(aeron_parse_duration_ns("1", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)1); EXPECT_EQ(aeron_parse_duration_ns("77777777", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)77777777); } TEST_F(PropTest, shouldParseValidQualifiedDuration) { uint64_t duration_ns = 0; EXPECT_EQ(aeron_parse_duration_ns("0ns", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)0); EXPECT_EQ(aeron_parse_duration_ns("1ns", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)1); EXPECT_EQ(aeron_parse_duration_ns("64ns", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)64); EXPECT_EQ(aeron_parse_duration_ns("0us", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)0); EXPECT_EQ(aeron_parse_duration_ns("1us", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)1000); EXPECT_EQ(aeron_parse_duration_ns("7us", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)7 * 1000); EXPECT_EQ(aeron_parse_duration_ns("7000us", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)7000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("0ms", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)0); EXPECT_EQ(aeron_parse_duration_ns("1ms", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)1000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("7ms", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)7000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("7000ms", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)7000 * 1000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("0s", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)0); EXPECT_EQ(aeron_parse_duration_ns("1s", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)1000 * 1000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("7s", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)7000 * 1000 * 1000); EXPECT_EQ(aeron_parse_duration_ns("700s", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)700 * 1000 * 1000 * 1000); } TEST_F(PropTest, shouldParseMaxQualifiedDuration) { uint64_t duration_ns = 0; EXPECT_EQ(aeron_parse_duration_ns("70000000000s", &duration_ns), 0); EXPECT_EQ(duration_ns, (uint64_t)LLONG_MAX); }
5,414
2,589
/* 引用元:https://atcoder.jp/contests/dp/tasks/dp_h H - Grid 1Editorial // ソースコードの引用元 : https://atcoder.jp/contests/dp/submissions/6221550 // 提出ID : 6221550 // 問題ID : dp_h // コンテストID : dp // ユーザID : xryuseix // コード長 : 2238 // 実行時間 : 19 */ #include <algorithm> #include <bitset> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<ll> vi; typedef vector<char> vc; typedef vector<string> vs; typedef vector<pair<ll, ll>> vpii; typedef vector<vector<ll>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; #define rep(i, n) for (ll i = 0; i < (n); ++i) #define rrep(i, n) for (ll i = 1; i <= (n); ++i) #define drep(i, n) for (ll i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << endl #define P 1000000007 int main(void) { ll h, w; cin >> h >> w; char grid[h][w]; ll path[h][w]; rep(i, h) rep(j, w) cin >> grid[i][j]; for (ll i = 0; i < h; i++) { for (ll j = 0; j < w; j++) { path[i][j] = 0; } } for (ll i = 0; i < w; i++) { if (grid[0][i] == '.') path[0][i] = 1; else break; } for (ll i = 0; i < h; i++) { if (grid[i][0] == '.') path[i][0] = 1; else break; } for (ll i = 1; i < h; i++) { for (ll j = 1; j < w; j++) { if (grid[i][j] == '#') path[i][j] = 0; else { path[i][j] = max(path[i][j], path[i - 1][j] + path[i][j - 1]); path[i][j] %= P; } } } cout << path[h - 1][w - 1] << endl; }
1,860
835
/* Copyright 2021 The Many as One 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 <stdexcept> #include <utility> #include <random> template <typename T> Simplenet<T>::Simplenet(size_t width, size_t height) : mWidth(width) , mHeight(height) { mCells.resize(mWidth); for (auto& column : mCells) { column.resize(mHeight); } } template <typename T> void randomize() { random_device seeder; const auto seed = seeder.entropy() ? seeder() : time(nullptr); mt19937 eng(static_cast<mt19937::result_type>(seed)); normal_distribution<T> dist(0.0, 1.0); auto gen = bind(dist, eng); // for (auto& column : mCells) { // for (auto& row : column) { // row = gen(); // std::cout << ' ' << row << std::end; // } // std::cout << std::end; // } } template <typename T> void Simplenet<T>::verifyCoordinate(size_t x, size_t y) const { if (x >= mWidth || y >= mHeight) { throw std::out_of_range(""); } } template <typename T> const std::optional<T>& Simplenet<T>::at(size_t x, size_t y) const { verifyCoordinate(x, y); return mCells[x][y]; } template <typename T> std::optional<T>& Simplenet<T>::at(size_t x, size_t y) { return const_cast<std::optional<T>&>(std::as_const(*this).at(x, y)); }
1,903
648
class Solution { public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { //A[i][j] -> A[j][n-1-i] -> A[n-1-i][n-1-j] -> A[n-1-j][i] -> A[i][j] int temp = matrix[j][n-i-1]; matrix[j][n-i-1] = matrix[i][j]; matrix[i][j] = matrix[n-j-1][i]; matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = temp; } } } };
581
242
#include "Model.h" #include "OpenGL.h" #include "model_generated.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "utils/Texture.h" #include "utils/Shader.h" #include "Common.h" #include "CommonProject.h" #include "TextureManager.h" glm::mat4 Convert(const ModelData::Mat4 & m) { return glm::mat4{ { m.a1(), m.b1(), m.c1(), m.d1() }, { m.a2(), m.b2(), m.c2(), m.d2() }, { m.a3(), m.b3(), m.c3(), m.d3() }, { m.a4(), m.b4(), m.c4(), m.d4() } }; } Mesh::Mesh(const ModelData::MeshT & mesh, std::vector<std::unique_ptr<ModelMaterial>> & materials) { uint32_t materialIndex = mesh.material; if (materialIndex >= materials.size()) { printf("Error loading model, mesh has invalid material index (%d)", materialIndex); throw std::runtime_error("Error loading model."); } m_material = materials[materialIndex].get(); InitBuffers(mesh.positions, mesh.normals, mesh.texCoords, mesh.tangents, mesh.bitangents, mesh.indices); } Mesh::~Mesh() { glDeleteBuffers(1, &m_positions); glDeleteBuffers(1, &m_vboIndices); glDeleteBuffers(1, &m_normals); if (m_material->shader->GetConfig().GetUVChannelsCount()) glDeleteBuffers(m_texCoords.size(), m_texCoords.data()); if (m_material->shader->GetConfig().textures.normal.size()) { glDeleteBuffers(1, &m_tangents); glDeleteBuffers(1, &m_bitangents); } if (IsVAOSupported()) glDeleteVertexArrays(1, &m_vao); } void Mesh::BindUniforms(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { glm::mat4 MVP = projection * view * model; m_material->shader->GetShader().SetUniform(MVP, "MVP"); m_material->shader->GetShader().SetUniform(model, "M"); } void Mesh::BindBuffers() { if (IsVAOSupported()) { m_material->shader->GetShader().BindVAO(m_vao); } else { m_material->shader->GetShader().BindBuffer<glm::vec3>(m_positions, m_material->shader->GetLocations().buffers.positions); m_material->shader->GetShader().BindBuffer<glm::vec3>(m_normals, m_material->shader->GetLocations().buffers.normals); for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i) m_material->shader->GetShader().BindBuffer<glm::vec2>(m_texCoords[i], m_material->shader->GetLocations().buffers.texCoords[i]); if (m_material->shader->GetConfig().textures.normal.size()) { m_material->shader->GetShader().BindBuffer<glm::vec3>(m_tangents, m_material->shader->GetLocations().buffers.tangents); //m_material->shader->GetShader().BindBuffer<glm::vec3>(m_bitangents, m_shader->GetLocations().buffers.bitangents); } } // TODO can be bound to VAO ??? m_material->shader->GetShader().BindElementBuffer(m_vboIndices); } // render the mesh void Mesh::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { m_material->shader->BeginRender(); m_material->shader->BindTransform(model, view, projection); m_material->shader->BindTextures(m_material->textures); BindBuffers(); glDrawElements(GL_TRIANGLES, m_verticesCount, GL_UNSIGNED_SHORT, (void*)0); CheckGlError("glDrawElements"); m_material->shader->EndRender(); } template<class T, uint32_t N> GLuint CreateFloatVBO(GLuint index, const T * data, size_t size, bool isVaoBinded) { GLuint vbo; glGenBuffers(1, &vbo); CheckGlError("glGenBuffers"); glBindBuffer(GL_ARRAY_BUFFER, vbo); CheckGlError("glBindBuffer"); glBufferData(GL_ARRAY_BUFFER, size*sizeof(T), data, GL_STATIC_DRAW); CheckGlError("glBufferData"); if (isVaoBinded) { glEnableVertexAttribArray(index); CheckGlError("glEnableVertexAttribArray"); glVertexAttribPointer(index, N, GL_FLOAT, GL_FALSE, 0, nullptr); CheckGlError("glVertexAttribPointer"); } return vbo; } template<class T, uint32_t N> GLuint CreateFloatVBO(GLuint index, const std::vector<T> & data, bool isVaoBinded) { return CreateFloatVBO<T, N>(index, &data[0], data.size(), isVaoBinded); } void Mesh::InitBuffers(const std::vector<ModelData::Vec3> & positions, const std::vector<ModelData::Vec3> & normals, const std::vector<ModelData::Vec2> & texCoords, const std::vector<ModelData::Vec3> & tangents, const std::vector<ModelData::Vec3> & bitangents, const std::vector<uint16_t> & indices) { bool bindVAO = IsVAOSupported(); // prepare and bind VAO if possible if (bindVAO) { glGenVertexArrays(1, &m_vao); CheckGlError("glGenVertexArrays"); glBindVertexArray(m_vao); CheckGlError("glBindVertexArray"); } m_positions = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("positionModelSpace", Shader::LocationType::Attrib), positions, bindVAO); m_normals = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("normalModelSpace", Shader::LocationType::Attrib), normals, bindVAO); if (m_material->shader->GetConfig().textures.normal.size()) { m_tangents = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("tangentModelSpace", Shader::LocationType::Attrib), tangents, bindVAO); //m_bitangents = CreateFloatVBO<ModelData::Vec3, 3>(m_shader->GetShader().GetLocation("bitangentModelSpace", Shader::LocationType::Attrib), bitangents, bindVAO); } for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i) { m_texCoords.push_back(CreateFloatVBO<ModelData::Vec2, 2>(m_material->shader->GetShader().GetLocation("vertexUV" + std::to_string(i), Shader::LocationType::Attrib), &texCoords[i * positions.size()], positions.size(), bindVAO)); } glBindVertexArray(0); // TODO can be element buffer binded to vao ??? glGenBuffers(1, &m_vboIndices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_vboIndices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(uint16_t), &indices[0], GL_STATIC_DRAW); m_verticesCount = indices.size(); } ModelShader::TextureStackEntry::Operation Convert(ModelData::TextureOperation operation) { switch (operation) { case ModelData::TextureOperation_Add: return ModelShader::TextureStackEntry::Operation::Add; case ModelData::TextureOperation_Multiply: return ModelShader::TextureStackEntry::Operation::Multiply; case ModelData::TextureOperation_Substract: return ModelShader::TextureStackEntry::Operation::Substract; case ModelData::TextureOperation_Divide: return ModelShader::TextureStackEntry::Operation::Divide; case ModelData::TextureOperation_SmoothAdd: return ModelShader::TextureStackEntry::Operation::SmoothAdd; case ModelData::TextureOperation_SignedAdd: return ModelShader::TextureStackEntry::Operation::SignedAdd; } return ModelShader::TextureStackEntry::Operation::Add; } bool ProcessTextures(const std::string & root, std::vector<std::unique_ptr<ModelData::TextureT>> & data, std::vector<ModelShader::TextureStackEntry> & stack, std::vector<GLuint> & textures) { for (size_t i = 0; i < data.size(); ++i) { ModelShader::TextureStackEntry entry; entry.factor = data[i]->blendFactor; entry.operation = Convert(data[i]->operation); entry.uvIndex = data[i]->uvIndex; auto texture = TextureManager::Instance().GetTexture((root + data[i]->path).c_str()); if (!texture) { printf("Error loading texture %s", (root + data[i]->path).c_str()); return false; } textures.push_back(*texture); stack.push_back(entry); } return true; } std::unique_ptr<ModelMaterial> Model::CreateMaterial(const std::string & root, ModelData::MaterialT & material) { ModelShader::Config config; std::unique_ptr<ModelMaterial> result = std::make_unique<ModelMaterial>(); config.light = m_configLight; memset(&config.material, 0, sizeof(config.material)); if (material.ambient) config.material.ambient = Convert(*material.ambient); if (material.diffuse) config.material.diffuse = Convert(*material.diffuse); if (material.specular) config.material.specular = Convert(*material.specular); config.material.shininess = material.shininess; config.material.shininessStrength = material.shininessStrength; if (!ProcessTextures(root, material.textureAmbient, config.textures.ambient, result->textures.ambient)) return nullptr; if (!ProcessTextures(root, material.textureDiffuse, config.textures.diffuse, result->textures.diffuse)) return nullptr; if (!ProcessTextures(root, material.textureSpecular, config.textures.specular, result->textures.specular)) return nullptr; if (!ProcessTextures(root, material.textureNormal, config.textures.normal, result->textures.normal)) return nullptr; if (!ProcessTextures(root, material.textureLightmap, config.textures.lightmap, result->textures.lightmap)) return nullptr; config.shading = ModelShader::ShadingModel::BlinnPhong; result->shader = std::make_unique<ModelShader>(config); if (!result->shader.get()) return nullptr; return result; } Model::Model(const char * path, Light::Config light) : m_configLight(light) { auto data = Common::ReadFile(path); auto model = ModelData::UnPackModel(data.data()); auto root = Common::GetDirectoryFromFilePath(path); // process materials ProcessMaterials(model.get(), root); // process meshes ProcessMeshes(model.get()); // recursively process tree m_tree = ProcessTree(*model->tree); } Model::~Model() { // clear meshes before materials m_meshes.clear(); } void Model::ProcessMaterials(ModelData::ModelT * model, const std::string & root) { for (size_t i = 0; i < model->materials.size(); ++i) { auto material = CreateMaterial(root, *model->materials[i].get()); if (!material) { printf("Error creating material."); throw std::runtime_error("Error creating material."); } m_materials.push_back(std::move(material)); } } void Model::ProcessMeshes(ModelData::ModelT * model) { for (size_t i = 0; i < model->meshes.size(); ++i) { // TODO check is mesh constructed successfully m_meshes.push_back(std::make_unique<Mesh>(*model->meshes[i].get(), m_materials)); } } Model::Tree Model::ProcessTree(ModelData::TreeT & node) { Model::Tree result; result.transform = Convert(*node.transform); result.meshes = node.meshes; for (auto & child : node.childs) result.childs.push_back(ProcessTree(*child)); return result; } void Model::Bind(const Data & data) { for (auto & material : m_materials) { material->shader->BeginRender(); material->shader->BindCamera(data.cameraWorldSpace); material->shader->BindLight(data.light); material->shader->BindMaterial(data.material); material->shader->EndRender(); } } void Model::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { DrawInternal(m_tree, model, view, projection); } void Model::DrawInternal(Tree & tree, const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { glm::mat4 nodeModel = model * tree.transform; //glm::mat4 nodeModel = model; for (uint32_t i : tree.meshes) m_meshes[i]->Draw(nodeModel, view, projection); for (Tree & child : tree.childs) DrawInternal(child, nodeModel, view, projection); }
11,888
3,992
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace game { enum class CityAreaType : uint32_t { Undefined = 0, PublicZone = 1, SafeZone = 2, RestrictedZone = 3, DangerousZone = 4, }; } // namespace game } // namespace RED4ext
317
116
// Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved. #pragma once #include <atomic> #include <condition_variable> #include <string> #include <thread> #include <vector> #include <frc/circular_buffer.h> #include "communications/PublishNodeBase.hpp" namespace frc3512 { /** * A communication layer that can pass messages between others who have * inherited it through a publish-subscribe architecture */ class PublishNode : public PublishNodeBase { public: /** * Construct a PublishNode. * * @param nodeName Name of node. */ explicit PublishNode(std::string nodeName = "Misc"); virtual ~PublishNode(); /** * Adds this object to the specified PublishNode's subscriber list. * * @param publisher The PublishNode that this instance wants to recieve * event from. */ void Subscribe(PublishNode& publisher); /** * Removes this object from the specified PublishNode's subscriber list. * * @param publisher The PublishNode that this instance wants to stop * recieving event from. */ void Unsubscribe(PublishNode& publisher); /** * Get the button value (starting at button 1). * * The buttons are returned in a single 16 bit value with one bit * representing the state of each button. The appropriate button is returned * as a boolean value. * * @param message The message whose member variables contain deserialized * data. * @param joystick The joystick number. * @param button The button number to be read (starting at 1). * @return The state of the button. */ static bool GetRawButton(const HIDPacket& msg, int joystick, int button); /** * Sends a packet to every subscriber. * * @param p Any packet with a Serialize() method. */ template <class P> void Publish(P p); /** * Sends a packet to the object it's called on. * * @param p Any packet with a Serialize() method. */ template <class P> void PushMessage(P p); private: static constexpr int kNodeQueueSize = 1024; std::string m_nodeName; std::vector<PublishNode*> m_subList; frc::circular_buffer<char> m_queue{kNodeQueueSize}; std::thread m_thread; std::atomic<bool> m_isRunning{true}; std::condition_variable m_ready; /** * Blocks the thread until the queue receives at least one set of characters * of a message or until the node deconstructs, then processes each message. */ void RunFramework(); }; } // namespace frc3512 #include "PublishNode.inc"
2,662
787
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "Runtime.hpp" #include <armnn/Version.hpp> #include <armnn/BackendRegistry.hpp> #include <armnn/BackendHelper.hpp> #include <armnn/Logging.hpp> #include <armnn/utility/Timer.hpp> #include <armnn/backends/IBackendContext.hpp> #include <backendsCommon/DynamicBackendUtils.hpp> #include <backendsCommon/memoryOptimizerStrategyLibrary/MemoryOptimizerStrategyLibrary.hpp> #include <armnn/utility/PolymorphicDowncast.hpp> #include <common/include/LabelsAndEventClasses.hpp> #include <iostream> #include <backends/BackendProfiling.hpp> using namespace armnn; using namespace std; namespace armnn { IRuntime::IRuntime() : pRuntimeImpl( new RuntimeImpl(armnn::IRuntime::CreationOptions())) {} IRuntime::IRuntime(const IRuntime::CreationOptions& options) : pRuntimeImpl(new RuntimeImpl(options)) {} IRuntime::~IRuntime() = default; IRuntime* IRuntime::CreateRaw(const CreationOptions& options) { return new IRuntime(options); } IRuntimePtr IRuntime::Create(const CreationOptions& options) { return IRuntimePtr(CreateRaw(options), &IRuntime::Destroy); } void IRuntime::Destroy(IRuntime* runtime) { delete runtime; } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network)); } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network, std::string& errorMessage) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage); } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network, std::string& errorMessage, const INetworkProperties& networkProperties) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage, networkProperties); } armnn::TensorInfo IRuntime::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return pRuntimeImpl->GetInputTensorInfo(networkId, layerId); } armnn::TensorInfo IRuntime::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return pRuntimeImpl->GetOutputTensorInfo(networkId, layerId); } std::vector<ImportedInputId> IRuntime::ImportInputs(NetworkId networkId, const InputTensors& inputTensors, MemorySource forceImportMemorySource) { return pRuntimeImpl->ImportInputs(networkId, inputTensors, forceImportMemorySource); } std::vector<ImportedOutputId> IRuntime::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors, MemorySource forceImportMemorySource) { return pRuntimeImpl->ImportOutputs(networkId, outputTensors, forceImportMemorySource); } void IRuntime::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds) { return pRuntimeImpl->ClearImportedInputs(networkId, inputIds); } void IRuntime::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds) { return pRuntimeImpl->ClearImportedOutputs(networkId, outputIds); } Status IRuntime::EnqueueWorkload(NetworkId networkId, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputIds, std::vector<ImportedOutputId> preImportedOutputIds) { return pRuntimeImpl->EnqueueWorkload(networkId, inputTensors, outputTensors, preImportedInputIds, preImportedOutputIds); } Status IRuntime::Execute(IWorkingMemHandle& workingMemHandle, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputs, std::vector<ImportedOutputId> preImportedOutputs) { return pRuntimeImpl->Execute(workingMemHandle, inputTensors, outputTensors, preImportedInputs, preImportedOutputs); } Status IRuntime::UnloadNetwork(NetworkId networkId) { return pRuntimeImpl->UnloadNetwork(networkId); } const IDeviceSpec& IRuntime::GetDeviceSpec() const { return pRuntimeImpl->GetDeviceSpec(); } std::unique_ptr<IWorkingMemHandle> IRuntime::CreateWorkingMemHandle(NetworkId networkId) { return pRuntimeImpl->CreateWorkingMemHandle(networkId); } const std::shared_ptr<IProfiler> IRuntime::GetProfiler(NetworkId networkId) const { return pRuntimeImpl->GetProfiler(networkId); } void IRuntime::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func) { return pRuntimeImpl->RegisterDebugCallback(networkId, func); } int RuntimeImpl::GenerateNetworkId() { return m_NetworkIdCounter++; } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork) { std::string ignoredErrorMessage; return LoadNetwork(networkIdOut, std::move(inNetwork), ignoredErrorMessage); } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork, std::string& errorMessage) { INetworkProperties networkProperties( false, MemorySource::Undefined, MemorySource::Undefined); return LoadNetwork(networkIdOut, std::move(inNetwork), errorMessage, networkProperties); } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork, std::string& errorMessage, const INetworkProperties& networkProperties) { // Register the profiler auto profiler = inNetwork->GetProfiler(); ProfilerManager::GetInstance().RegisterProfiler(profiler.get()); IOptimizedNetwork* rawNetwork = inNetwork.release(); networkIdOut = GenerateNetworkId(); for (auto&& context : m_BackendContexts) { context.second->BeforeLoadNetwork(networkIdOut); } unique_ptr<LoadedNetwork> loadedNetwork = LoadedNetwork::MakeLoadedNetwork( std::unique_ptr<IOptimizedNetwork>(rawNetwork), errorMessage, networkProperties, m_ProfilingService); if (!loadedNetwork) { return Status::Failure; } { std::lock_guard<std::mutex> lockGuard(m_Mutex); // Stores the network m_LoadedNetworks[networkIdOut] = std::move(loadedNetwork); } for (auto&& context : m_BackendContexts) { context.second->AfterLoadNetwork(networkIdOut); } if (m_ProfilingService.IsProfilingEnabled()) { m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_LOADS); } return Status::Success; } Status RuntimeImpl::UnloadNetwork(NetworkId networkId) { bool unloadOk = true; for (auto&& context : m_BackendContexts) { unloadOk &= context.second->BeforeUnloadNetwork(networkId); } if (!unloadOk) { ARMNN_LOG(warning) << "RuntimeImpl::UnloadNetwork(): failed to unload " "network with ID:" << networkId << " because BeforeUnloadNetwork failed"; return Status::Failure; } std::unique_ptr<profiling::TimelineUtilityMethods> timelineUtils = profiling::TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); { std::lock_guard<std::mutex> lockGuard(m_Mutex); // If timeline recording is on mark the Network end of life if (timelineUtils) { auto search = m_LoadedNetworks.find(networkId); if (search != m_LoadedNetworks.end()) { profiling::ProfilingGuid networkGuid = search->second->GetNetworkGuid(); timelineUtils->RecordEvent(networkGuid, profiling::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS); } } if (m_LoadedNetworks.erase(networkId) == 0) { ARMNN_LOG(warning) << "WARNING: RuntimeImpl::UnloadNetwork(): " << networkId << " not found!"; return Status::Failure; } if (m_ProfilingService.IsProfilingEnabled()) { m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_UNLOADS); } } for (auto&& context : m_BackendContexts) { context.second->AfterUnloadNetwork(networkId); } // Unregister the profiler ProfilerManager::GetInstance().RegisterProfiler(nullptr); ARMNN_LOG(debug) << "RuntimeImpl::UnloadNetwork(): Unloaded network with ID: " << networkId; return Status::Success; } const std::shared_ptr<IProfiler> RuntimeImpl::GetProfiler(NetworkId networkId) const { auto it = m_LoadedNetworks.find(networkId); if (it != m_LoadedNetworks.end()) { auto& loadedNetwork = it->second; return loadedNetwork->GetProfiler(); } return nullptr; } void RuntimeImpl::ReportStructure() // armnn::profiling::IProfilingService& profilingService as param { // No-op for the time being, but this may be useful in future to have the profilingService available // if (profilingService.IsProfilingEnabled()){} LoadedNetworks::iterator it = m_LoadedNetworks.begin(); while (it != m_LoadedNetworks.end()) { auto& loadedNetwork = it->second; loadedNetwork->SendNetworkStructure(); // Increment the Iterator to point to next entry it++; } } RuntimeImpl::RuntimeImpl(const IRuntime::CreationOptions& options) : m_NetworkIdCounter(0), m_ProfilingService(*this) { const auto start_time = armnn::GetTimeNow(); ARMNN_LOG(info) << "ArmNN v" << ARMNN_VERSION; if ( options.m_ProfilingOptions.m_TimelineEnabled && !options.m_ProfilingOptions.m_EnableProfiling ) { throw RuntimeException( "It is not possible to enable timeline reporting without profiling being enabled"); } // Load any available/compatible dynamic backend before the runtime // goes through the backend registry LoadDynamicBackends(options.m_DynamicBackendsPath); BackendIdSet supportedBackends; for (const auto& id : BackendRegistryInstance().GetBackendIds()) { // Store backend contexts for the supported ones try { auto factoryFun = BackendRegistryInstance().GetFactory(id); ARMNN_ASSERT(factoryFun != nullptr); auto backend = factoryFun(); ARMNN_ASSERT(backend != nullptr); ARMNN_ASSERT(backend.get() != nullptr); auto customAllocatorMapIterator = options.m_CustomAllocatorMap.find(id); if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end() && customAllocatorMapIterator->second == nullptr) { // We need to manually clean up the dynamic backends before throwing an exception. DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends()); m_DeviceSpec.ClearDynamicBackends(); throw armnn::Exception("Allocator associated with id " + id.Get() + " is null"); } // If the runtime is created in protected mode only add backends that support this mode if (options.m_ProtectedMode) { // check if backend supports ProtectedMode using BackendCapability = BackendOptions::BackendOption; BackendCapability protectedContentCapability {"ProtectedContentAllocation", true}; if (!HasCapability(protectedContentCapability, id)) { // Protected Content Allocation is not supported by the backend // backend should not be registered ARMNN_LOG(warning) << "Backend " << id << " is not registered as does not support protected content allocation."; continue; } // The user is responsible to provide a custom memory allocator which allows to allocate // protected memory if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end()) { std::string err; if (customAllocatorMapIterator->second->GetMemorySourceType() == armnn::MemorySource::DmaBufProtected) { if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err)) { ARMNN_LOG(error) << "The backend " << id << " reported an error when entering protected mode. Backend won't be" << " used. ErrorMsg: " << err; continue; } // No errors so register the Custom Allocator with the BackendRegistry BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second); } else { ARMNN_LOG(error) << "The CustomAllocator provided with the runtime options doesn't support " "protected memory. Protected mode can't be activated. The backend " << id << " is not going to be used. MemorySource must be MemorySource::DmaBufProtected"; continue; } } else { ARMNN_LOG(error) << "Protected mode can't be activated for backend: " << id << " no custom allocator was provided to the runtime options."; continue; } } else { // If a custom memory allocator is provided make the backend use that instead of the default if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end()) { std::string err; if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err)) { ARMNN_LOG(error) << "The backend " << id << " reported an error when trying to use the provided custom allocator." " Backend won't be used." << " ErrorMsg: " << err; continue; } // No errors so register the Custom Allocator with the BackendRegistry BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second); } } // check if custom memory optimizer strategy map is set if (!options.m_MemoryOptimizerStrategyMap.empty()) { auto customMemoryOptimizerStrategyMapIterator = options.m_MemoryOptimizerStrategyMap.find(id); // if a memory optimizer strategy is provided make the backend use that instead of the default if (customMemoryOptimizerStrategyMapIterator != options.m_MemoryOptimizerStrategyMap.end()) { // no errors.. register the memory optimizer strategy with the BackendRegistry BackendRegistryInstance().RegisterMemoryOptimizerStrategy( id, customMemoryOptimizerStrategyMapIterator->second); ARMNN_LOG(info) << "MemoryOptimizerStrategy " << customMemoryOptimizerStrategyMapIterator->second->GetName() << " set for the backend " << id << "."; } } else { // check if to use one of the existing memory optimizer strategies is set std::string memoryOptimizerStrategyName = ""; ParseOptions(options.m_BackendOptions, id, [&](std::string name, const BackendOptions::Var& value) { if (name == "MemoryOptimizerStrategy") { memoryOptimizerStrategyName = ParseStringBackendOption(value, ""); } }); if (memoryOptimizerStrategyName != "") { std::shared_ptr<IMemoryOptimizerStrategy> strategy = GetMemoryOptimizerStrategy(memoryOptimizerStrategyName); if (!strategy) { ARMNN_LOG(warning) << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << " was not found."; } else { using BackendCapability = BackendOptions::BackendOption; auto strategyType = GetMemBlockStrategyTypeName(strategy->GetMemBlockStrategyType()); BackendCapability memOptimizeStrategyCapability {strategyType, true}; if (HasCapability(memOptimizeStrategyCapability, id)) { BackendRegistryInstance().RegisterMemoryOptimizerStrategy(id, strategy); ARMNN_LOG(info) << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << " set for the backend " << id << "."; } else { ARMNN_LOG(warning) << "Backend " << id << " does not have multi-axis packing capability and cannot support" << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << "."; } } } } auto context = backend->CreateBackendContext(options); // backends are allowed to return nullptrs if they // don't wish to create a backend specific context if (context) { m_BackendContexts.emplace(std::make_pair(id, std::move(context))); } supportedBackends.emplace(id); unique_ptr<armnn::profiling::IBackendProfiling> profilingIface = std::make_unique<armnn::profiling::BackendProfiling>(armnn::profiling::BackendProfiling( options, m_ProfilingService, id)); // Backends may also provide a profiling context. Ask for it now. auto profilingContext = backend->CreateBackendProfilingContext(options, profilingIface); // Backends that don't support profiling will return a null profiling context. if (profilingContext) { // Pass the context onto the profiling service. m_ProfilingService.AddBackendProfilingContext(id, profilingContext); } } catch (const BackendUnavailableException&) { // Ignore backends which are unavailable } } BackendRegistryInstance().SetProfilingService(m_ProfilingService); // pass configuration info to the profiling service m_ProfilingService.ConfigureProfilingService(options.m_ProfilingOptions); if (options.m_ProfilingOptions.m_EnableProfiling) { // try to wait for the profiling service to initialise m_ProfilingService.WaitForProfilingServiceActivation(3000); } m_DeviceSpec.AddSupportedBackends(supportedBackends); ARMNN_LOG(info) << "Initialization time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(start_time).count() << " ms."; } RuntimeImpl::~RuntimeImpl() { const auto startTime = armnn::GetTimeNow(); std::vector<int> networkIDs; try { // Coverity fix: The following code may throw an exception of type std::length_error. std::transform(m_LoadedNetworks.begin(), m_LoadedNetworks.end(), std::back_inserter(networkIDs), [](const auto &pair) { return pair.first; }); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: An error has occurred when getting the IDs of the networks to unload: " << e.what() << "\nSome of the loaded networks may not be unloaded" << std::endl; } // We then proceed to unload all the networks which IDs have been appended to the list // up to the point the exception was thrown (if any). for (auto networkID : networkIDs) { try { // Coverity fix: UnloadNetwork() may throw an exception of type std::length_error, // boost::log::v2s_mt_posix::odr_violation or boost::log::v2s_mt_posix::system_error UnloadNetwork(networkID); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: An error has occurred when unloading network " << networkID << ": " << e.what() << std::endl; } } // Clear all dynamic backends. DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends()); m_DeviceSpec.ClearDynamicBackends(); m_BackendContexts.clear(); BackendRegistryInstance().SetProfilingService(armnn::EmptyOptional()); ARMNN_LOG(info) << "Shutdown time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; } LoadedNetwork* RuntimeImpl::GetLoadedNetworkPtr(NetworkId networkId) const { std::lock_guard<std::mutex> lockGuard(m_Mutex); return m_LoadedNetworks.at(networkId).get(); } TensorInfo RuntimeImpl::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return GetLoadedNetworkPtr(networkId)->GetInputTensorInfo(layerId); } TensorInfo RuntimeImpl::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return GetLoadedNetworkPtr(networkId)->GetOutputTensorInfo(layerId); } std::vector<ImportedInputId> RuntimeImpl::ImportInputs(NetworkId networkId, const InputTensors& inputTensors, MemorySource forceImportMemorySource) { return GetLoadedNetworkPtr(networkId)->ImportInputs(inputTensors, forceImportMemorySource); } std::vector<ImportedOutputId> RuntimeImpl::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors, MemorySource forceImportMemorySource) { return GetLoadedNetworkPtr(networkId)->ImportOutputs(outputTensors, forceImportMemorySource); } void RuntimeImpl::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds) { return GetLoadedNetworkPtr(networkId)->ClearImportedInputs(inputIds); } void RuntimeImpl::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds) { return GetLoadedNetworkPtr(networkId)->ClearImportedOutputs(outputIds); } Status RuntimeImpl::EnqueueWorkload(NetworkId networkId, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputIds, std::vector<ImportedOutputId> preImportedOutputIds) { const auto startTime = armnn::GetTimeNow(); LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return Status::Failure; } if (loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Network " << networkId << " is async enabled."; return Status::Failure; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "EnqueueWorkload"); static thread_local NetworkId lastId = networkId; if (lastId != networkId) { LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network) { network->FreeWorkingMemory(); }); } lastId=networkId; auto status = loadedNetwork->EnqueueWorkload(inputTensors, outputTensors, preImportedInputIds, preImportedOutputIds); // Check if we imported, if not there's no need to call the After EnqueueWorkload events if (!preImportedInputIds.empty() || !preImportedOutputIds.empty()) { // Call After EnqueueWorkload events for (auto&& context : m_BackendContexts) { context.second->AfterEnqueueWorkload(networkId); } } ARMNN_LOG(info) << "Execution time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; return status; } Status RuntimeImpl::Execute(IWorkingMemHandle& iWorkingMemHandle, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputs, std::vector<ImportedOutputId> preImportedOutputs) { const auto startTime = armnn::GetTimeNow(); NetworkId networkId = iWorkingMemHandle.GetNetworkId(); LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return Status::Failure; } if (!loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Attempting execute " << networkId << " when it is not async enabled."; return Status::Failure; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "Execute"); auto status = loadedNetwork->Execute(inputTensors, outputTensors, iWorkingMemHandle, preImportedInputs, preImportedOutputs); ARMNN_LOG(info) << "Execution time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; return status; } /// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have /// overlapped Execution by calling this function from different threads. std::unique_ptr<IWorkingMemHandle> RuntimeImpl::CreateWorkingMemHandle(NetworkId networkId) { LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return nullptr; } if (!loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Network " << networkId << " is not async enabled."; return nullptr; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "CreateWorkingMemHandle"); static thread_local NetworkId lastId = networkId; if (lastId != networkId) { LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network) { network->FreeWorkingMemory(); }); } lastId=networkId; return loadedNetwork->CreateWorkingMemHandle(networkId); } void RuntimeImpl::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func) { LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); loadedNetwork->RegisterDebugCallback(func); } void RuntimeImpl::LoadDynamicBackends(const std::string& overrideBackendPath) { // Get the paths where to load the dynamic backends from std::vector<std::string> backendPaths = DynamicBackendUtils::GetBackendPaths(overrideBackendPath); // Get the shared objects to try to load as dynamic backends std::vector<std::string> sharedObjects = DynamicBackendUtils::GetSharedObjects(backendPaths); // Create a list of dynamic backends m_DynamicBackends = DynamicBackendUtils::CreateDynamicBackends(sharedObjects); // Register the dynamic backends in the backend registry BackendIdSet registeredBackendIds = DynamicBackendUtils::RegisterDynamicBackends(m_DynamicBackends); // Add the registered dynamic backend ids to the list of supported backends m_DeviceSpec.AddSupportedBackends(registeredBackendIds, true); } } // namespace armnn
29,900
7,839
//$Id$ //------------------------------------------------------------------------------ // TimeSystemConverter //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2017 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 Thinking Systems, Inc. under contract // number S-67573-G // // Author: Allison Greene // Created: 2005/02/03 // /** * Definition of the TimeSystemConverter class */ //------------------------------------------------------------------------------ #ifndef TimeSystemConverter_hpp #define TimeSystemConverter_hpp //#include <iostream> //#include <iomanip> //#include <sstream> //#include "BaseException.hpp" #include "EopFile.hpp" #include "LeapSecsFileReader.hpp" //#include "GmatConstants.hpp" // struct TimeSystemConverterExceptions // { class GMAT_API UnimplementedException : public BaseException { public: UnimplementedException(const std::string &message = "TimeSystemConverter: Conversion not implemented: ") : BaseException(message) {}; }; class GMAT_API TimeFileException : public BaseException { public: TimeFileException(const std::string &message = "TimeSystemConverter: File is unknown: ") : BaseException(message) {}; }; class GMAT_API TimeFormatException : public BaseException { public: TimeFormatException(const std::string &message = "TimeSystemConverter: Requested format not implemented: ") : BaseException(message) {}; }; class GMAT_API InvalidTimeException : public BaseException { public: InvalidTimeException(const std::string &message = "TimeSystemConverter: Requested time is invalid: ") : BaseException(message) {}; }; // }; namespace TimeConverterUtil { // Specified in Math Spec section 2.3 static const Real TDB_COEFF1 = 0.001658; static const Real TDB_COEFF2 = 0.00001385; static const Real M_E_OFFSET = 357.5277233; static const Real M_E_COEFF1 = 35999.05034; static const Real T_TT_OFFSET = GmatTimeConstants::JD_OF_J2000; static const Real T_TT_COEFF1 = GmatTimeConstants::DAYS_PER_JULIAN_CENTURY; static const Real L_B = 1.550505e-8; static const Real NUM_SECS = GmatTimeConstants::SECS_PER_DAY; enum TimeSystemTypes { A1MJD = 0, TAIMJD, UTCMJD, UT1MJD, TDBMJD, TTMJD, A1, TAI, UTC, UT1, TDB, TT, TimeSystemCount }; static const std::string TIME_SYSTEM_TEXT[TimeSystemCount] = { "A1Mjd", "TaiMjd", "UtcMjd", "Ut1Mjd", "TdbMjd", "TtMjd", // New entries added by DJC "A1", "TAI", "UTC", "UT1", "TDB", "TT", }; /* Real Convert(const Real origValue, const std::string &fromType, const std::string &toType, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real ConvertToTaiMjd(std::string fromType, Real origValue, Real refJd= GmatTimeConstants::JD_NOV_17_1858); Real ConvertFromTaiMjd(std::string toType, Real origValue, Real refJd= GmatTimeConstants::JD_NOV_17_1858); */ Integer GMAT_API GetTimeTypeID(std::string &str); Real GMAT_API Convert(const Real origValue, const Integer fromType, const Integer toType, Real refJd = GmatTimeConstants::JD_JAN_5_1941); Real GMAT_API ConvertToTaiMjd(Integer fromType, Real origValue, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real GMAT_API ConvertFromTaiMjd(Integer toType, Real origValue, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real GMAT_API NumberOfLeapSecondsFrom(Real utcMjd, Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941); Real GMAT_API GetFirstLeapSecondMJD(Real fromUtcMjd, Real toUtcMjd, Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941); void GMAT_API SetEopFile(EopFile *eopFile); void GMAT_API SetLeapSecsFileReader(LeapSecsFileReader *leapSecsFileReader); void GMAT_API GetTimeSystemAndFormat(const std::string &type, std::string &system, std::string &format); std::string GMAT_API ConvertMjdToGregorian(const Real mjd, bool handleLeapSecond = false, Integer format = 1); Real GMAT_API ConvertGregorianToMjd(const std::string &greg); void GMAT_API Convert(const char *fromType, Real fromMjd, const char *fromStr, const char *toType, Real &toMjd, std::string &toStr, Integer format = 1); void GMAT_API Convert(const char *fromType, Real fromMjd, const std::string &fromStr, const std::string &toType, Real &toMjd, std::string &toStr, Integer format = 1); void GMAT_API Convert(const std::string &fromType, Real fromMjd, const std::string &fromStr, const std::string &toType, Real &toMjd, std::string &toStr, Integer format = 1); bool GMAT_API ValidateTimeSystem(std::string sys); bool GMAT_API ValidateTimeFormat(const std::string &format, const std::string &value, bool checkValue = true); StringArray GMAT_API GetValidTimeRepresentations(); bool GMAT_API IsValidTimeSystem(const std::string& system); bool GMAT_API IsInLeapSecond(Real theTaiMjd); bool GMAT_API HandleLeapSecond(); static bool isInLeapSecond; } #endif // TimeSystemConverter_hpp
6,670
2,092
#include "validator_test.h" #include "kernels/kernel.h" #include "kernels/kernel_factory.h" #include "matrix.h" #include "validator.h" void ValidationTest::ValidateAddition() { CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 0, 0 ), Matrix_t( 0, 0 ) ) ); CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 1, 1 ), Matrix_t( 1, 1 ) ) ); CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 16, 16 ) ) ); CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 234, 1234 ), Matrix_t( 234, 1234 ) ) ); CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 13, 1 ), Matrix_t( 13, 1 ) ) ); CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 15, 16 ), Matrix_t( 16, 16 ) ) ); CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 15 ), Matrix_t( 16, 16 ) ) ); CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 15, 16 ) ) ); CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 16, 15 ) ) ); } void ValidationTest::ValidateMultiplication() { CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 4 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 0, 0 ), Matrix_t( 0, 0 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 1, 1 ), Matrix_t( 1, 1 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 3 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 5 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 1 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 1, 4 ), Matrix_t( 4, 4 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 3, 4 ), Matrix_t( 4, 3 ) ) ); CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 5, 4 ), Matrix_t( 4, 5 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 3 ), Matrix_t( 4, 3 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 5 ), Matrix_t( 4, 5 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 1, 4 ), Matrix_t( 3, 4 ) ) ); CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 3, 4 ), Matrix_t( 5, 3 ) ) ); } void ValidationTest::ValidateMultiplicationKernels() { const Matrix_t expected( 0, 0 ); auto kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_DEFAULT ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_CPU ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_CUDA ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); } void ValidationTest::ValidateAdditionKernels() { const Matrix_t expected( 0, 0 ); auto kernel = KernelFactory( OPERATION_ADDITION, KERNEL_DEFAULT ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); kernel = KernelFactory( OPERATION_ADDITION, KERNEL_CPU ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); kernel = KernelFactory( OPERATION_ADDITION, KERNEL_CUDA ).GetKernel(); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected ); CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected ); }
5,342
2,287
#include <iostream> #include <thread> #include "Util/Timer.cpp" #include "Contract/SimpleAuctionSCV.cpp" #include "Util/FILEOPR.cpp" #include <unistd.h> #include <list> #include <vector> #include <atomic> #include <condition_variable> #include <set> #include <algorithm> #define maxThreads 128 #define maxBObj 5000 #define maxbEndT 5000 //millseconds #define funInContract 6 #define pl "===================================================\n" #define MValidation true //! true or false #define malMiner true //! set the flag to make miner malicious. #define NumOfDoubleSTx 2 //! # double-spending Tx for malicious final state by Miner. using namespace std; using namespace std::chrono; int NumBlock = 26; //! at least two blocks, the first run is warmup run. int numValidator = 50; int beneficiary = 0; //! fixed beneficiary id to 0, it can be any unique address/id. int nBidder = 2; //! nBidder: number of bidder shared objects. default is 2. int nThread = 1; //! nThread: total number of concurrent threads; default is 1. int numAUs; //! numAUs: total number of Atomic Unites to be executed. double lemda; //! λ: random delay seed. int bidEndT; //! time duration for auction. double tTime[2]; //! total time taken by miner and validator algorithm respectively. SimpleAuction *auction; //! smart contract for miner. int *aCount = NULL; //! aborted transaction count. float_t *mTTime = NULL; //! time taken by each miner Thread to execute AUs (Transactions). float_t *vTTime = NULL; //! time taken by each validator Thread to execute AUs (Transactions). float_t *gTtime = NULL; //! time taken by each miner Thread to add edges and nodes in the conflict graph. vector<string>listAUs; //! holds AUs to be executed on smart contract: "listAUs" index+1 represents AU_ID. vector<string>seqBin; //! holds sequential Bin AUs. vector<string>concBin; //! holds concurrent Bin AUs. vector<int>ccSet; //! Set holds the IDs of the shared objects accessed by concurrent Bin Tx. std::atomic<int>currAU; //! used by miner-thread to get index of Atomic Unit to execute. std::atomic<int>vCount; //! # of valid AU node added in graph (invalid AUs will not be part of the graph & conflict list). std::atomic<int>eAUCount; //! used by validator threads to keep track of how many valid AUs executed by validator threads. mutex concLock, seqLock; //! Lock used to access seq and conc bin. float_t seqTime[3]; //! Used to store seq exe time. std::atomic<bool>mm; //! miner is malicious, this is used by validators. //! STATE DATA int mHBidder; int mHBid; int vHBidder; int vHBid; int *mPendingRet; int *vPendingRet; /*************************BARRIER CODE BEGINS****************************/ std::mutex mtx; std::mutex pmtx; // to print in concurrent scene std::condition_variable cv; bool launch = false; void wait_for_launch() { std::unique_lock<std::mutex> lck(mtx); while (!launch) cv.wait(lck); } void shoot() { std::unique_lock<std::mutex> lck(mtx); launch = true; cv.notify_all(); } /*************************BARRIER CODE ENDS*****************************/ /*************************MINER CODE BEGINS*****************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! Class "Miner" create & run "n" miner-thread concurrently ! !"concMiner()" called by miner-thread to perfrom oprs of respective AUs ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ class Miner { public: Miner( ) { //! initialize the counter used to execute the numAUs currAU = 0; vCount = 0; //! index location represents respective thread id. mTTime = new float_t [nThread]; gTtime = new float_t [nThread]; aCount = new int [nThread]; for(int i = 0; i < nThread; i++) { mTTime[i] = 0; gTtime[i] = 0; aCount[i] = 0; } auction = new SimpleAuction(bidEndT, beneficiary, nBidder); } //!-------------------------------------------- //!!!!!! MAIN MINER:: CREATE MINER THREADS !!!! //!-------------------------------------------- void mainMiner() { Timer mTimer; thread T[nThread]; // seqTime[0] = 0; Timer staticTimer; //! start timer to get time taken by static analysis. auto start = staticTimer._timeStart(); staticAnalysis(); seqTime[0] += staticTimer._timeStop( start ); //!--------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //!!!!!!!!!! Create 'nThread' Miner threads !!!!!!!!!! //!--------------------------------------------------------- double s = mTimer.timeReq(); for(int i = 0; i < nThread; i++) T[i] = thread(concMiner, i, concBin.size()); for(auto& th : T) th.join(); tTime[0] = mTimer.timeReq() - s; //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ // seqTime[1] = 0; Timer SeqTimer; //! start timer to get time taken by this thread. start = SeqTimer._timeStart(); seqBinExe(); seqTime[1] += SeqTimer._timeStop( start ); //! print the final state of the shared objects. finalState(); } //! returns the sObj accessed by AU. void getSobjId(vector<int> &sObj, string AU) { istringstream ss(AU); string tmp; ss >> tmp; //! AU_ID to Execute. ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID sObj.push_back(bID); return; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID sObj.push_back(bID); return; } } //!----------------------------------------------------------- //! Performs the static analysis based on set Operations. ! //!----------------------------------------------------------- void staticAnalysis() { //holds the IDs of the shared object accessed by an AU. vector<int> sObj; if(numAUs != 0) { //! Add first AU to concBin and Add Sobj accessed by it to ccSet. concBin.push_back(listAUs[0]); getSobjId(sObj, listAUs[0]); auto it = sObj.begin(); for( ; it != sObj.end(); ++it) { ccSet.push_back(*it); } } int index = 1; while( index < numAUs ) { sObj.clear(); getSobjId(sObj, listAUs[index]); sort (ccSet.begin(), ccSet.end()); sort (sObj.begin(), sObj.end()); vector<int> intersect(ccSet.size() + sObj.size()); vector<int>:: iterator it; it = set_intersection( ccSet.begin(), ccSet.end(), sObj.begin(), sObj.end(), intersect.begin()); intersect.resize(it-intersect.begin()); if(intersect.size() == 0 ) { auto it = sObj.begin(); for(; it != sObj.end(); ++it) ccSet.push_back(*it); concBin.push_back(listAUs[index]); } else { seqBin.push_back(listAUs[index]); } index++; } } //!----------------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //! The function to be executed by all the miner threads. Thread ! //! executes the transaction concurrently from Concurrent Bin ! //!----------------------------------------------------------------- static void concMiner(int t_ID, int numAUs) { Timer thTimer; //! get the current index, and increment it. int curInd = currAU++; //! statrt clock to get time taken by this.AU auto start = thTimer._timeStart(); while(curInd < concBin.size()) { //!get the AU to execute, which is of string type. istringstream ss(concBin[curInd]); string tmp; ss >> tmp; int AU_ID = stoi(tmp); ss >> tmp; if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } //! get the current index to execute, and increment it. curInd = currAU++; } mTTime[t_ID] += thTimer._timeStop(start); } //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ void seqBinExe( ) { int t_ID = 0; int count = 0; while(count < seqBin.size()) { //! get the AU to execute, which is of string type. istringstream ss(seqBin[count]); string tmp; ss >> tmp; int AU_ID = stoi(tmp); ss >> tmp; if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } count++; } } //!------------------------------------------------- //!Final state of all the shared object. Once all | //!AUs executed. We are geting this using state_m()| //!------------------------------------------------- void finalState() { auction->state(&mHBidder, &mHBid, mPendingRet); } ~Miner() { }; }; /********************MINER CODE ENDS*********************************/ /********************VALIDATOR CODE BEGINS***************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! Class "Validator" create & run "n" validator-Thread concurrently ! ! based on CONC and SEQ BIN given by miner operations of respective ! ! AUs. Thread 0 is considered as smart contract deployer. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ class Validator { public: Validator() { //! int the execution counter used by validator threads. eAUCount = 0; //! array index location represents respective thread id. vTTime = new float_t [nThread]; for(int i = 0; i < nThread; i++) vTTime[i] = 0; }; //!---------------------------------------- //! create n concurrent validator threads | //! to execute valid AUs. | //!---------------------------------------- void mainValidator() { for(int i = 0; i < nThread; i++) vTTime[i] = 0; eAUCount = 0; Timer vTimer; thread T[nThread]; auction->reset(bidEndT); //!--------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //!!!!!!!!!! Create 'nThread' Validator threads !!!!!!!!!! //!--------------------------------------------------------- double s = vTimer.timeReq(); for(int i = 0; i<nThread; i++) T[i] = thread(concValidator, i); shoot(); for(auto& th : T) th.join( ); tTime[1] = vTimer.timeReq() - s; //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ // seqTime[2] = 0; Timer SeqTimer; auto start = SeqTimer._timeStart(); seqBinExe(); seqTime[2] += SeqTimer._timeStop( start ); //!print the final state of the shared objects by validator. finalState(); // auction->AuctionEnded( ); } //!------------------------------------------------------------ //!!!!!!! Concurrent Phase !!!!!!!! //!!!!!! 'nThread' Validator threads Executes this Fun !!!!!!! //!------------------------------------------------------------ static void concValidator( int t_ID ) { //barrier to synchronise all threads for a coherent launch wait_for_launch(); Timer Ttimer; //!statrt clock to get time taken by this thread. auto start = Ttimer._timeStart(); int curInd = eAUCount++; while( curInd< concBin.size() && mm == false) { //! get the AU to execute, which is of string type. istringstream ss(concBin[curInd]); string tmp; ss >> tmp; //! AU_ID to Execute. int AU_ID = stoi(tmp); ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); if(v == -1) mm = true; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); if(v == -1) mm = true; } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } curInd = eAUCount++; } //!stop timer to get time taken by this thread vTTime[t_ID] += Ttimer._timeStop( start ); } //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ void seqBinExe( ) { int t_ID = 0; int count = 0; while(count < seqBin.size() && mm == false) { //! get the AU to execute, which is of string type. istringstream ss(seqBin[count]); string tmp; ss >> tmp; //! AU_ID to Execute. int AU_ID = stoi(tmp); ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); if(v == -1) mm = true; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); if(v == -1) mm = true; } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } count++; } } //!------------------------------------------------- //!Final state of all the shared object. Once all | //!AUs executed. We are geting this using state() | //!------------------------------------------------- void finalState() { //state auction->state(&vHBidder, &vHBid, vPendingRet); } ~Validator() { }; }; /**********************VALIDATOR CODE ENDS***************************/ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //! atPoss:: from which double-spending Tx to be stored at begining ! //! of the list. Add malicious final state with double-spending Tx ! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool addMFS(int atPoss) { istringstream ss(listAUs[atPoss-2]); string trns1; ss >> trns1; //! AU_ID to Execute. int AU_ID1 = stoi(trns1); ss >> trns1;//function name ss >> trns1; //! payable. int payable = stoi(trns1); ss >> trns1; //! bidder ID. int bidderID = stoi(trns1); ss >> trns1; //! Ammount to bid. int bidValue = stoi(trns1); istringstream ss1(listAUs[atPoss-1]); string trns2; ss1 >> trns1; //! AU_ID to Execute. int AU_ID2 = stoi(trns1); ss1 >> trns1;//function name ss1 >> trns1; //! payable. int payable1 = stoi(trns1); ss1 >> trns1; //! bidderID. int bidderID1 = stoi(trns1); ss1 >> trns1; //! Ammount to bid. int bidValue1 = stoi(trns1); bidValue = 999; trns1 = to_string(AU_ID1)+" bid "+to_string(payable)+" " +to_string(bidderID)+" "+to_string(bidValue); listAUs[AU_ID1-1] = trns1; bidValue1 = 1000; trns2 = to_string(AU_ID2)+" bid "+to_string(payable1)+" " +to_string(bidderID1)+" "+to_string(bidValue1); listAUs[AU_ID2-1] = trns1; mHBidder = bidderID1; mHBid = bidValue; //! add the confliciting AUs in conc bin and remove them from seq bin. Add //! one of the AU from seq bin to conc Bin and remove that AU from seq bin. auto it = concBin.begin(); concBin.erase(it); concBin.insert(concBin.begin(), trns1); concBin.insert(concBin.begin()+1, trns2); it = seqBin.begin(); seqBin.erase(it); return true; } void printBins( ) { int concCount = 0, seqCount = 0; cout<<endl<<"=====================\n" <<"Concurrent Bin AUs\n====================="; for(int i = 0; i < concBin.size(); i++) { cout<<"\n"<<concBin[i]; concCount++; } cout<<endl; cout<<endl<<"=====================\n" <<"Sequential Bin AUs\n====================="; for(int i = 0; i < seqBin.size(); i++) { cout<<"\n"<<seqBin[i]; seqCount++; } cout<<"\n=====================\n" <<"Conc AU Count "<< concCount <<"\nSeq AU Count "<<seqCount <<"\n=====================\n"; } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /*!!!!!!!! State Validation !!!!!!!!!!*/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ bool stateVal() { //State Validation bool flag = false; if(mHBidder != vHBidder || mHBid != vHBid) flag = true; // cout<<"\n============================================" // <<"\n Miner Auction Winer "<<mHBidder // <<" | Amount "<<mHBid; // cout<<"\n Validator Auction Winer "<<to_string(vHBidder) // <<" | Amount "<<to_string(vHBid); // cout<<"\n============================================\n"; return flag; } /**********************MAIN FUN CODE BEGINS***************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /*!!!!!!!! main() !!!!!!!!!!*/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ int main(int argc, char *argv[]) { cout<<pl<<"Static Bin Miner and Smart Concurrent Validator\n"; cout<<"--------------------------------\n"; if(argc<3) cout<<"\nPlease Enter Command Line Argument as follows:" <<"\n\t./a.out <num Blocks> <num Validator> <num Iteration>\n"; NumBlock = atoi(argv[1]); numValidator = atoi(argv[2]); int nItertion = atoi(argv[3]); if(NumBlock < 2) cout<<"\nNumber of Blocks should be >= 2\n"; if(numValidator < 1)cout<<"\nNumber of Validators should be >= 1\n"; if(nItertion < 1)cout<<"\nNumber of Iterations should be >= 1\n"; float tMiner = 0, tVal = 0; int tReject = 0, tMaxAcc = 0; float tStatT = 0, tSeqMT = 0; float tSeqVT = 0; //! list holds the avg time taken by miner and Validator //! thread s for multiple consecutive runs. list<float>mItrT; list<float>vItrT; int totalRejCont = 0; //number of validator rejected the blocks; int maxAccepted = 0; int totalRun = NumBlock; //at least 2 FILEOPR file_opr; //! read from input file:: nBidder = #nBidder; nThread = #threads; //! numAUs = #AUs; λ = random delay seed. file_opr.getInp(&nBidder, &bidEndT, &nThread, &numAUs, &lemda); if(nBidder > maxBObj) { nBidder = maxBObj; cout<<"Max number Bidder Shared Object can be "<<maxBObj<<"\n"; } float valTime; for(int itr = 0; itr < nItertion; itr++) { seqTime[0] = seqTime[1] = seqTime[2] = 0; totalRejCont = 0; maxAccepted = 0; valTime = 0; float Blockvalt; for(int nBlock = 0; nBlock < NumBlock; nBlock++) { file_opr.genAUs(numAUs, nBidder, funInContract, listAUs); tTime[0] = 0, tTime[1] = 0; Blockvalt = 0; mPendingRet = new int [nBidder+1]; vPendingRet = new int [nBidder+1]; mm = new std::atomic<bool>; mm = false; Timer mTimer; mTimer.start(); //MINER Miner *miner = new Miner(); miner ->mainMiner(); if(lemda != 0) bool rv = addMFS(NumOfDoubleSTx); // printBins(); //VALIDATOR float valt = 0; int acceptCount = 0, rejectCount = 0; for(int nval = 0; nval < numValidator; nval++) { valt = 0; Validator *validator = new Validator(); validator ->mainValidator(); bool flag = stateVal(); if(flag == true) rejectCount++; else acceptCount++; mm = false; int counterv = 0; for( int x = 0; x < nThread; x++ ){ if(vTTime[x] != 0) { valt += vTTime[x]; counterv++; } } if(nBlock > 0) Blockvalt += valt/counterv; } if(nBlock > 0 && malMiner == true) { totalRejCont += rejectCount; if(maxAccepted < acceptCount ) maxAccepted = acceptCount; } //! total valid AUs among total AUs executed //! by miner and varified by Validator. int vAUs = seqBin.size() + concBin.size(); if(nBlock > 0) file_opr.writeOpt(nBidder, nThread, numAUs, tTime, mTTime, vTTime, aCount, vAUs, mItrT, vItrT, 1); ccSet.clear(); concBin.clear(); seqBin.clear(); listAUs.clear(); delete miner; miner = NULL; valTime += Blockvalt/numValidator; } //to get total avg miner and validator //time after number of totalRun runs. float tAvgMinerT = 0, tAvgValidT = 0; int cnt = 0; auto mit = mItrT.begin(); auto vit = vItrT.begin(); for(int j = 1; j < totalRun; j++){ tAvgMinerT = tAvgMinerT + *mit; if(*vit != 0){ tAvgValidT = tAvgValidT + *vit; cnt++; } mit++; vit++; } tMiner += tAvgMinerT/(NumBlock-1); tVal += valTime/(NumBlock-1); tReject += totalRejCont /(NumBlock-1); tStatT += seqTime[0]; tSeqMT += seqTime[1]; tSeqVT += seqTime[2]; if(tMaxAcc < maxAccepted) tMaxAcc = maxAccepted; mItrT.clear(); vItrT.clear(); } //Static Analysis Time float avgMAtime = tStatT/(NumBlock*nItertion); //Miner Sequential Phase Time float avgMStime = tSeqMT/(NumBlock*nItertion); //Validator Sequential Phase Time float avgVStime = tSeqVT/(nItertion*NumBlock*numValidator); cout<< "Avg Miner Time in microseconds = " <<(tMiner/nItertion)+avgMStime+avgMAtime; cout<<"\nAvg Validator Time in microseconds = " <<(tVal/nItertion)+avgVStime; cout<<"\n-----------------------------"; cout<<"\nStaic Analysis Time in microseconds = "<<avgMAtime; cout<<"\nMiner Seq Time in microseconds = "<<avgMStime <<"\nValidator Seq Time in microseconds = "<<avgVStime; cout<<"\n-----------------------------"; cout<<"\nAvg Validator Accepted a Block = " <<(numValidator-(tReject/nItertion)); cout<<"\nAvg Validator Rejcted a Block = " <<tReject/nItertion; cout<<"\nMax Validator Accepted any Block = "<<tMaxAcc; cout<<"\n"<<endl; mItrT.clear(); vItrT.clear(); delete mTTime; delete vTTime; return 0; } /*********************MAIN FUN CODE ENDS***********************/
22,130
8,901
#include "uml/signal.h" #include "uml/interface.h" #include "uml/operation.h" #include "uml/manifestation.h" #include "uml/stereotype.h" #include "uml/behavior.h" #include "uml/dataType.h" #include "uml/association.h" #include "uml/deployment.h" using namespace UML; Set<Property, Signal>& Signal::getOwnedAttributesSet() { return m_ownedAttributes; } void Signal::init() { m_ownedAttributes.subsets(m_attributes); m_ownedAttributes.subsets(m_ownedMembers); m_ownedAttributes.m_signature = &Signal::getOwnedAttributesSet; } Signal::Signal() : Element(ElementType::SIGNAL) { init(); } Signal::~Signal() { mountAndRelease(); } OrderedSet<Property, Signal>& Signal::getOwnedAttributes() { return m_ownedAttributes; } bool Signal::isSubClassOf(ElementType eType) const { bool ret = Classifier::isSubClassOf(eType); if (!ret) { ret = eType == ElementType::SIGNAL; } return ret; }
939
350
#include "NeuronInitializer.h" void Initializators::ConstantInitializer(double *weigths, unsigned int n_values, double value) { for(unsigned int i=0; i<n_values; i++) { weigths[i] = value; } } void Initializators::NormalDistributionInitializer(double *weights, unsigned int n_values, default_random_engine &randEngine, double mean, double dev) { normal_distribution<double> dist(mean,dev); for(unsigned int i=0; i<n_values; i++) { double val = dist(randEngine); //std::cout << "Value: " << val << std::endl; weights[i] = val; } } void** Initializators::ConstantParamsGen(double value) { void **vals; double* val = new double; *val = value; vals = new void*[1]; vals[0] = (void*)val; return vals; } void** Initializators::GaussParamsGen(default_random_engine &randEngine, double mean, double dev) { void **vals; double* val_mean = new double; double* val_dev = new double; *val_mean = mean; *val_dev = dev; vals = new void*[3]; vals[0] = (void*)&randEngine; vals[1] = (void*)val_mean; vals[2] = (void*)val_dev; return vals; } Initializer NeuronInitializer::ConstantInitializer(double value) { Initializer initer; initer.init = Initializators::Constant; initer.initializatorFunction = (void*)&Initializators::ConstantInitializer; initer.vals = Initializators::ConstantParamsGen(value); return initer; } Initializer NeuronInitializer::NormalInitializer(default_random_engine& randEngine, double mean, double deviation) { Initializer initer; initer.init = Initializators::Gauss; initer.initializatorFunction = (void*)&Initializators::NormalDistributionInitializer; initer.vals = Initializators::GaussParamsGen(randEngine, mean, deviation); return initer; }
1,857
613
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_PROCESS_HPP__ #define __STOUT_OS_PROCESS_HPP__ #include <sys/types.h> // For pid_t. #include <list> #include <ostream> #include <sstream> #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/none.hpp> #include <stout/option.hpp> #include <stout/strings.hpp> namespace os { struct Process { Process(pid_t _pid, pid_t _parent, pid_t _group, const Option<pid_t>& _session, const Option<Bytes>& _rss, const Option<Duration>& _utime, const Option<Duration>& _stime, const std::string& _command, bool _zombie) : pid(_pid), parent(_parent), group(_group), session(_session), rss(_rss), utime(_utime), stime(_stime), command(_command), zombie(_zombie) {} const pid_t pid; const pid_t parent; const pid_t group; const Option<pid_t> session; const Option<Bytes> rss; const Option<Duration> utime; const Option<Duration> stime; const std::string command; const bool zombie; // TODO(bmahler): Add additional data as needed. bool operator<(const Process& p) const { return pid < p.pid; } bool operator<=(const Process& p) const { return pid <= p.pid; } bool operator>(const Process& p) const { return pid > p.pid; } bool operator>=(const Process& p) const { return pid >= p.pid; } bool operator==(const Process& p) const { return pid == p.pid; } bool operator!=(const Process& p) const { return pid != p.pid; } }; class ProcessTree { public: // Returns a process subtree rooted at the specified PID, or none if // the specified pid could not be found in this process tree. Option<ProcessTree> find(pid_t pid) const { if (process.pid == pid) { return *this; } foreach (const ProcessTree& tree, children) { Option<ProcessTree> option = tree.find(pid); if (option.isSome()) { return option; } } return None(); } // Checks if the specified pid is contained in this process tree. bool contains(pid_t pid) const { return find(pid).isSome(); } operator Process() const { return process; } operator pid_t() const { return process.pid; } const Process process; const std::list<ProcessTree> children; private: friend struct Fork; friend Try<ProcessTree> pstree(pid_t, const std::list<Process>&); ProcessTree( const Process& _process, const std::list<ProcessTree>& _children) : process(_process), children(_children) {} }; inline std::ostream& operator<<(std::ostream& stream, const ProcessTree& tree) { if (tree.children.empty()) { stream << "--- " << tree.process.pid << " "; if (tree.process.zombie) { stream << "(" << tree.process.command << ")"; } else { stream << tree.process.command; } } else { stream << "-+- " << tree.process.pid << " "; if (tree.process.zombie) { stream << "(" << tree.process.command << ")"; } else { stream << tree.process.command; } size_t size = tree.children.size(); foreach (const ProcessTree& child, tree.children) { std::ostringstream out; out << child; stream << "\n"; if (--size != 0) { stream << " |" << strings::replace(out.str(), "\n", "\n |"); } else { stream << " \\" << strings::replace(out.str(), "\n", "\n "); } } } return stream; } } // namespace os { // An overload of stringify for printing a list of process trees // (since printing a process tree is rather particular). inline std::string stringify(const std::list<os::ProcessTree>& list) { std::ostringstream out; out << "[ " << std::endl; std::list<os::ProcessTree>::const_iterator iterator = list.begin(); while (iterator != list.end()) { out << stringify(*iterator); if (++iterator != list.end()) { out << std::endl << std::endl; } } out << std::endl << "]"; return out.str(); } #endif // __STOUT_OS_PROCESS_HPP__
4,583
1,482
// // Part of Metta OS. Check https://atta-metta.net for latest version. // // Copyright 2007 - 2017, Stanislav Karchebnyy <berkus@atta-metta.net> // // Distributed under the Boost Software License, Version 1.0. // (See file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt) // #include "parser.h" #include "logger.h" #include <iostream> #include <sstream> #include <fstream> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/CommandLine.h> using namespace llvm; using namespace std; static cl::opt<string> inputFilename(cl::Positional, cl::desc("<input .if file>"), cl::init("-")); static cl::list<string> includeDirectories("I", cl::Prefix, cl::desc("Include path"), cl::value_desc("directory"), cl::ZeroOrMore); static cl::opt<bool> verbose("v", cl::desc("Increase verbosity level."), cl::ZeroOrMore); static cl::opt<string> outputDirectory("o", cl::Prefix, cl::desc("Output path"), cl::value_desc("directory"), cl::init(".")); class Meddler { llvm::SourceMgr sm; bool verbose; vector<parser_t*> parser_stack; vector<string> include_dirs; public: Meddler(bool verbose_) : sm(), verbose(verbose_) {} void set_include_dirs(vector<string> dirs) { include_dirs = dirs; sm.setIncludeDirs(include_dirs); } bool add_source(string file) { L(cout << "### Adding file " << file << endl); std::string full_path; unsigned bufn = sm.AddIncludeFile(file, llvm::SMLoc(), full_path); if (bufn == ~0U) { cerr << "*** Could not load file " << file << ". Please check that you have spelled the interface name correctly and specified all include paths." << endl; return false; } L(cout << "### Parsing file " << file << endl); parser_t* parser = new parser_t(sm, verbose); L(cout << "### Initing parser" << endl); parser->init(sm.getMemoryBuffer(bufn)); L(cout << "### Adding parser to stack" << endl); parser_stack.push_back(parser); return true; } bool parse() { assert(parser_stack.size() > 0); bool res = true; do { L(cout << "### Running parse" << endl); res &= parser_stack.at(parser_stack.size()-1)->run(); // Since parent interfaces can only "extend" current interface, we put them into parent interfaces list of current interface // after parsing and consult them during emit phase for matching types, exceptions and methods - they are considered LOCAL to this // interface. if (parser_stack.size() > 1) { L(cout << "### Linking interface to parent" << endl); parser_stack.at(parser_stack.size()-2)->link_to_parent(parser_stack.at(parser_stack.size()-1)); } if (res && (parser_stack.at(parser_stack.size()-1)->parent_interface() != "")) { L(cout << "### Adding another interface file" << endl); add_source(parser_stack.at(parser_stack.size()-1)->parent_interface() + ".if"); } L(cout << "### Running another round" << endl); } while (res && (parser_stack.at(parser_stack.size()-1)->parent_interface() != "")); L(cout << "### Finished parsing!" << endl); return res; } bool emit(const string& output_dir) { ostringstream boilerplate_header; ostringstream impl_h, interface_h, interface_cpp, typedefs_cpp, filename; parser_t& parser = *parser_stack[0]; char* user_name = getenv("USER"); char* host_name = getenv("HOSTNAME"); time_t now; time(&now); struct tm *current; current = localtime(&now); L(cout << "### Generating boilerplate header" << endl); boilerplate_header << "/*" << endl << " * " << parser.parse_tree->name() << " generated"; if (user_name) boilerplate_header << " by " << user_name; if (host_name) boilerplate_header << " at " << host_name; boilerplate_header << " on " << (1900 + current->tm_year) << "." << (1 + current->tm_mon) << "." << current->tm_mday << "T" << current->tm_hour << ":" << current->tm_min << ":" << current->tm_sec << endl; boilerplate_header << " * AUTOMATICALLY GENERATED FILE, DO NOT EDIT!" << endl << " */" << endl << endl; L(cout << "### Emitting impl_h" << endl); parser.parse_tree->emit_impl_h(impl_h, ""); L(cout << "### Emitting interface_h" << endl); parser.parse_tree->emit_interface_h(interface_h, ""); L(cout << "### Emitting interface_cpp" << endl); parser.parse_tree->emit_interface_cpp(interface_cpp, ""); L(cout << "### Emitting type definitions cpp" << endl); parser.parse_tree->renumber_methods(); parser.parse_tree->emit_typedef_cpp(typedefs_cpp, ""); // todo: boost.filesystem for paths filename << output_dir << "/" << parser.parse_tree->name() << "_impl.h"; ofstream of(filename.str().c_str(), ios::out|ios::trunc); of << boilerplate_header.str() << impl_h.str(); of.close(); filename.str(""); filename << output_dir << "/" << parser.parse_tree->name() << "_interface.h"; of.open(filename.str().c_str(), ios::out|ios::trunc); of << boilerplate_header.str() << interface_h.str(); of.close(); filename.str(""); filename << output_dir << "/" << parser.parse_tree->name() << "_interface.cpp"; of.open(filename.str().c_str(), ios::out|ios::trunc); of << boilerplate_header.str() << interface_cpp.str(); of.close(); filename.str(""); filename << output_dir << "/" << parser.parse_tree->name() << "_typedefs.cpp"; of.open(filename.str().c_str(), ios::out|ios::trunc); of << boilerplate_header.str() << typedefs_cpp.str(); of.close(); return true; } }; int main(int argc, char** argv) { cl::ParseCommandLineOptions(argc, argv, "Meddler - Metta IDL parser.\n"); Meddler m(verbose); m.set_include_dirs(includeDirectories); if (!m.add_source(inputFilename)) { cerr << "Could not open input file " << inputFilename << endl; return -1; } if (m.parse()) { m.emit(outputDirectory); } else return -1; return 0; }
6,578
2,081
/* * IVTEntry.cpp * * Created on: Sep 13, 2020 * Author: OS1 */ #include "IVTEntry.h" #include "Kernel.h" #include "KernelEv.h" IVTEntry* IVTEntry::ivtEntires[] = { 0 }; IVTEntry* IVTEntry::getEntry(IVTNo ivtNo) { return ivtEntires[ivtNo]; } IVTEntry::IVTEntry(IVTNo ivtNo, InterruptRoutine newRoutine) : ivtNo(ivtNo), event(0), oldRoutine(newRoutine) { ivtEntires[ivtNo] = this; } IVTEntry::~IVTEntry() { ivtEntires[ivtNo] = 0; } void IVTEntry::signal() { if(event) { event->signal(); } } void IVTEntry::callOldRoutine() { if(oldRoutine) { lock(); oldRoutine(); unlock(); } }
612
292
#include <iostream> #include <map> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; int T, lenJ, lenS; string s, j; int main(void) { cin >> T; while(T--) { cin >> j >> s; map<char, int> ct; for(int i = 0; i < j.size(); i++) { ct[j[i]] += 1; } int ans = 0; for(int i = 0; i < s.size(); i++) { if(ct[s[i]] > 0) { ans += 1; } } cout << ans << endl; } return 0; }
555
214
/* Copyright 2012-2018 Sumandeep Banerjee, sumandeep.banerjee@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <opencv2\opencv.hpp> //OpenCV library of IP functions void sobel_edge_demo () { //declare image buffer pointers IplImage *pImage, *pSobelXImage, *pSobelYImage, *pOutXImage, *pOutYImage; // create display windows cvNamedWindow ("Input"); cvNamedWindow ("Sobel X"); cvNamedWindow ("Sobel Y"); // load image as grayscale pImage = cvLoadImage ("input/lena_grey.bmp", CV_LOAD_IMAGE_GRAYSCALE); cvShowImage ("Input", pImage); // allocate memory buffer for output of same size as input pOutXImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels); pOutYImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels); // sobel operator may produce -ve pixel values, therefore it requires 32bit floating images for temporary storage pSobelXImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels); pSobelYImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels); // perform sobel edge detection cvSobel (pImage, pSobelXImage, 1, 0); cvSobel (pImage, pSobelYImage, 0, 1); // convert sobel output back to 8bit grayscale image cvConvert (pSobelXImage, pOutXImage); cvConvert (pSobelYImage, pOutYImage); // show output cvShowImage ("Sobel X", pOutXImage); cvShowImage ("Sobel Y", pOutYImage); // save output cvSaveImage ("output/sobelx.bmp", pOutXImage); cvSaveImage ("output/sobely.bmp", pOutYImage); // wait till key press cvWaitKey (0); // release memory cvReleaseImage (&pImage); cvReleaseImage (&pOutXImage); cvReleaseImage (&pOutYImage); cvReleaseImage (&pSobelXImage); cvReleaseImage (&pSobelYImage); // destroy gui windows cvDestroyAllWindows (); }
2,395
867
//********************************************************* // Read_Activity.cpp - Read the Activity File //********************************************************* #include "TripPrep.hpp" //--------------------------------------------------------- // Read_Activity //--------------------------------------------------------- bool TripPrep::Read_Activity (int file_num) { int last_hhold, last_person, hhold, person, purpose, mode, start, end, origin, destination; int time1, time2, num_kept, num_out, count, vehicle, *parking, nparking, pass; int next_in, next_merge, replace_id, last_keep; bool flag, read_merge, read_in, save_merge, keep; Activity_File *activity_file, *new_file; Trip_File *trip_file, *in_file; Vehicle_File *veh_file; Vehicle_Data *veh_ptr; Location_Data *loc_ptr; Access_Data *acc_ptr; activity_file = (Activity_File *) Demand_Db_Base (ACTIVITY); in_file = (Trip_File *) Demand_Db_Base (TRIP); nparking = 0; parking = 0; if (file_num > 0) { if (!split_flag) { if (!activity_file->Open (file_num)) return (false); } else { activity_file->Rewind (); } if (hhlist_flag && hhlist_file.Extend ()) { if (!Household_List (file_num)) { if (split_flag) return (false); Error ("Opening %s", hhlist_file.File_Type ()); } } } if (output_flag) { new_file = (Activity_File *) Demand_Db_Base (NEW_ACTIVITY); if (file_num > 0) { if (new_file->Extend ()) { if (!new_file->Open (file_num)) { Error ("Creating %s", new_file->File_Type ()); } } if (prob_flag && newhh_flag && newhh_file.Extend ()) { if (!newhh_file.Open (file_num)) { Error ("Opening %s", newhh_file.File_Type ()); } } if (merge_act_flag && merge_act_file.Extend ()) { if (!merge_act_file.Open (file_num)) { Error ("Opening %s", merge_act_file.File_Type ()); } } } } if (create_flag || convert_flag) { trip_file = (Trip_File *) Demand_Db_Base (NEW_TRIP); if (file_num > 0 && trip_file->Extend ()) { if (!trip_file->Open (file_num)) { Error ("Creating %s", trip_file->File_Type ()); } } if (create_flag) { veh_file = (Vehicle_File *) Demand_Db_Base (NEW_VEHICLE); if (file_num > 0) { if (newhh_flag && newhh_file.Extend ()) { if (!newhh_file.Open (file_num)) { Error ("Opening %s", newhh_file.File_Type ()); } fprintf (newhh_file.File (), "HHOLD\tOLDHH\n"); } } else if (newhh_flag) { fprintf (newhh_file.File (), "HHOLD\tOLDHH\n"); } //---- build the parking map ---- loc_ptr = location_data.Last (); nparking = loc_ptr->Location () + 1; parking = new int [nparking]; memset (parking, '\0', nparking * sizeof (int)); for (acc_ptr = access_data.First (); acc_ptr; acc_ptr = access_data.Next ()) { if (acc_ptr->From_Type () == LOCATION_ID && acc_ptr->To_Type () == PARKING_ID) { parking [acc_ptr->From_ID ()] = acc_ptr->To_ID (); } } } } //---- process each trip ---- if (merge_act_flag) { if (activity_file->Extend ()) { Show_Message ("Merging %s %s -- Record", activity_file->File_Type (), activity_file->Extension ()); } else { Show_Message ("Merging %s -- Record", activity_file->File_Type ()); } if (merge_act_file.Read ()) { next_merge = merge_act_file.Household (); } else { next_merge = MAX_INTEGER; } } else { if (activity_file->Extend ()) { Show_Message ("Reading %s %s -- Record", activity_file->File_Type (), activity_file->Extension ()); } else { Show_Message ("Reading %s -- Record", activity_file->File_Type ()); } next_merge = MAX_INTEGER; } Set_Progress (10000); last_hhold = last_person = num_kept = num_out = replace_id = last_keep = 0; read_merge = read_in = save_merge = false; count = 1; flag = true; if (activity_file->Read ()) { next_in = activity_file->Household (); } else { next_in = MAX_INTEGER; } //---- process each record ---- while (next_in != MAX_INTEGER || next_merge != MAX_INTEGER) { Show_Progress (); //---- set the processing flags ---- if (next_merge < next_in) { if (next_merge == replace_id) { save_merge = false; } else { save_merge = true; } read_merge = true; read_in = false; } else { hhold = activity_file->Household (); if (hhlist_flag && hhold_list.Get_Index (hhold) == 0) { if (all_flag) { new_file->Copy_Fields (activity_file); flag = false; if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; keep = true; replace_id = next_in; } else { keep = false; } } else { person = activity_file->Person (); purpose = activity_file->Purpose (); mode = activity_file->Mode (); vehicle = activity_file->Vehicle (); destination = activity_file->Location (); time1 = time_periods.Step (activity_file->Start_Min ()); time2 = time_periods.Step (activity_file->Start_Max ()); if (time1 < 0 || time2 < 0) { Error ("Converting Start Time for Household %d", hhold); } end = (time1 + time2 + 1) / 2; if (hhold == last_hhold && person == last_person) { flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle); if (flag) { if (create_flag) { trip_file->Household (hhold_id); trip_file->Person (person); trip_file->Trip (activity_file->Activity ()); trip_file->Purpose (purpose); pass = activity_file->Passengers (); if (mode == DRIVE_ALONE) { if (pass > 2) { mode = CARPOOL4; } else if (pass > 1) { mode = CARPOOL3; } else if (pass > 0) { mode = CARPOOL2; } } else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) { mode = MAGIC_MOVE; } trip_file->Mode (mode); trip_file->Start (time_periods.Format_Step (start)); trip_file->Origin (origin); trip_file->Arrive (time_periods.Format_Step (end)); trip_file->Destination (destination); trip_file->Constraint (activity_file->Constraint ()); if (vehicle > 0) { trip_file->Vehicle (veh_id); veh_ptr = vehicle_data.Get (vehicle); if (veh_ptr != NULL && origin < nparking) { veh_file->Vehicle (veh_id); veh_file->Household (hhold_id); veh_file->Location (parking [origin]); veh_file->Type (veh_ptr->Type ()); veh_file->Sub_Type (veh_ptr->Sub_Type ()); if (!veh_file->Write ()) { Error ("Writing %s", veh_file->File_Type ()); } } veh_id++; } else { trip_file->Vehicle (vehicle); } if (!trip_file->Write ()) { Error ("Writing %s", trip_file->File_Type ()); } if (newhh_flag) { fprintf (newhh_file.File (), "%d\t%d\n", hhold_id, hhold); } hhold_id++; } else if (convert_flag) { trip_file->Household (hhold); trip_file->Person (person); trip_file->Trip (activity_file->Activity ()); trip_file->Purpose (purpose); pass = activity_file->Passengers (); if (mode == DRIVE_ALONE) { if (pass > 2) { mode = CARPOOL4; } else if (pass > 1) { mode = CARPOOL3; } else if (pass > 0) { mode = CARPOOL2; } } else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) { mode = MAGIC_MOVE; } trip_file->Mode (mode); trip_file->Start (time_periods.Format_Step (start)); trip_file->Origin (origin); trip_file->Arrive (time_periods.Format_Step (end)); trip_file->Destination (destination); trip_file->Constraint (activity_file->Constraint ()); trip_file->Vehicle (vehicle); if (!trip_file->Write ()) { Error ("Writing %s", trip_file->File_Type ()); } } } } else { flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle); } origin = destination; time1 = time_periods.Step (activity_file->End_Min ()); time2 = time_periods.Step (activity_file->End_Max ()); if (time1 < 0 || time2 < 0) { Error ("Converting End Time for Household %d", hhold); } start = (time1 + time2 + 1) / 2; last_hhold = hhold; last_person = person; if ((flag || all_flag) && output_flag) { new_file->Copy_Fields (activity_file); if (script_flag) { if (trip_flag) { in_file->Reset_Record (); } keep = (program.Execute () != 0); } else { keep = flag; } if (keep || all_flag) { if (flag && keep) { num_kept++; if (newhh_flag && hhold != last_keep) { fprintf (newhh_file.File (), "%d\n", hhold); last_keep = hhold; } } if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; } } } if (next_merge == next_in) { if (flag) { replace_id = next_in; save_merge = false; } else { save_merge = true; } read_merge = read_in = true; } else { read_in = true; read_merge = save_merge = false; } } //---- write the merge activity to the output file ---- if (save_merge) { vehicle = merge_act_file.Vehicle (); if (vehicle_list.Get_Index (vehicle) == 0) { if (!vehicle_list.Add (vehicle)) { Error ("Adding Vehicle %d to the List", vehicle); } } if (output_flag) { new_file->Copy_Fields (&merge_act_file); if (script_flag) { if (trip_flag) { in_file->Reset_Record (); } keep = (program.Execute () != 0); } else { keep = true; } if (keep) { if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; } } } //---- get the next merge activity ---- if (read_merge) { if (merge_act_file.Read ()) { next_merge = merge_act_file.Household (); } else { next_merge = MAX_INTEGER; } } //---- get the next input activity ---- if (read_in) { if (activity_file->Read ()) { next_in = activity_file->Household (); } else { next_in = MAX_INTEGER; } } } End_Progress (); if (file_num == 0 || !split_flag) { total_in += Progress_Count (); } if (activity_file->Extend ()) { Print (2, "Number of Activity Records Read from %s = %d", activity_file->Extension (), Progress_Count ()); } else { Print (2, "Number of Activity Records Read = %d", Progress_Count ()); } if (output_flag) { total_out += num_out; if (new_file->Extend ()) { Print (1, "Number of Activity Records Written to %s = %d", new_file->Extension (), num_out); } else { Print (1, "Number of Activity Records Written = %d", num_out); } } total_used += num_kept; if (prob_flag) { Print (1, "Number of Activity Records Selected = %d", num_kept); if (num_out > 0) Print (0, " (%.1lf%%)", 100.0 * num_kept / num_out); } if (nparking > 0 && parking) { delete [] parking; } return (true); }
11,058
5,233
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ /// @file /// @author Don Gagne <don@thegagnes.com> #include "QmlObjectListModel.h" #include <QDebug> #include <QQmlEngine> const int QmlObjectListModel::ObjectRole = Qt::UserRole; const int QmlObjectListModel::TextRole = Qt::UserRole + 1; QmlObjectListModel::QmlObjectListModel(QObject* parent) : QAbstractListModel (parent) , _dirty (false) , _skipDirtyFirstItem (false) , _externalBeginResetModel (false) { } QmlObjectListModel::~QmlObjectListModel() { } QObject* QmlObjectListModel::get(int index) { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } int QmlObjectListModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return _objectList.count(); } QVariant QmlObjectListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (index.row() < 0 || index.row() >= _objectList.count()) { return QVariant(); } if (role == ObjectRole) { return QVariant::fromValue(_objectList[index.row()]); } else if (role == TextRole) { return QVariant::fromValue(_objectList[index.row()]->objectName()); } else { return QVariant(); } } QHash<int, QByteArray> QmlObjectListModel::roleNames(void) const { QHash<int, QByteArray> hash; hash[ObjectRole] = "object"; hash[TextRole] = "text"; return hash; } bool QmlObjectListModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (index.isValid() && role == ObjectRole) { _objectList.replace(index.row(), value.value<QObject*>()); emit dataChanged(index, index); return true; } return false; } bool QmlObjectListModel::insertRows(int position, int rows, const QModelIndex& parent) { Q_UNUSED(parent); if (position < 0 || position > _objectList.count() + 1) { qWarning() << "Invalid position position:count" << position << _objectList.count(); } beginInsertRows(QModelIndex(), position, position + rows - 1); endInsertRows(); emit countChanged(count()); return true; } bool QmlObjectListModel::removeRows(int position, int rows, const QModelIndex& parent) { Q_UNUSED(parent); if (position < 0 || position >= _objectList.count()) { qWarning() << "Invalid position position:count" << position << _objectList.count(); } else if (position + rows > _objectList.count()) { qWarning() << "Invalid rows position:rows:count" << position << rows << _objectList.count(); } beginRemoveRows(QModelIndex(), position, position + rows - 1); for (int row=0; row<rows; row++) { _objectList.removeAt(position); } endRemoveRows(); emit countChanged(count()); return true; } void QmlObjectListModel::move(int from, int to) { if(0 <= from && from < count() && 0 <= to && to < count() && from != to) { // Workaround to allow move item to the bottom. Done according to // beginMoveRows() documentation and implementation specificity: // https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows // (see 3rd picture explanation there) if(from == to - 1) { to = from++; } beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); _objectList.move(from, to); endMoveRows(); } } QObject* QmlObjectListModel::operator[](int index) { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } const QObject* QmlObjectListModel::operator[](int index) const { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } void QmlObjectListModel::clear() { if (!_externalBeginResetModel) { beginResetModel(); } _objectList.clear(); if (!_externalBeginResetModel) { endResetModel(); emit countChanged(count()); } } QObject* QmlObjectListModel::removeAt(int i) { QObject* removedObject = _objectList[i]; if(removedObject) { // Look for a dirtyChanged signal on the object if (_objectList[i]->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || i != 0) { QObject::disconnect(_objectList[i], SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } } removeRows(i, 1); setDirty(true); return removedObject; } void QmlObjectListModel::insert(int i, QObject* object) { if (i < 0 || i > _objectList.count()) { qWarning() << "Invalid index index:count" << i << _objectList.count(); } if(object) { QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); // Look for a dirtyChanged signal on the object if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || i != 0) { QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } } _objectList.insert(i, object); insertRows(i, 1); setDirty(true); } void QmlObjectListModel::insert(int i, QList<QObject*> objects) { if (i < 0 || i > _objectList.count()) { qWarning() << "Invalid index index:count" << i << _objectList.count(); } int j = i; for (QObject* object: objects) { QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); // Look for a dirtyChanged signal on the object if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || j != 0) { QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } j++; _objectList.insert(j, object); } insertRows(i, objects.count()); setDirty(true); } void QmlObjectListModel::append(QObject* object) { insert(_objectList.count(), object); } void QmlObjectListModel::append(QList<QObject*> objects) { insert(_objectList.count(), objects); } QObjectList QmlObjectListModel::swapObjectList(const QObjectList& newlist) { QObjectList oldlist(_objectList); if (!_externalBeginResetModel) { beginResetModel(); } _objectList = newlist; if (!_externalBeginResetModel) { endResetModel(); emit countChanged(count()); } return oldlist; } int QmlObjectListModel::count() const { return rowCount(); } void QmlObjectListModel::setDirty(bool dirty) { if (_dirty != dirty) { _dirty = dirty; if (!dirty) { // Need to clear dirty from all children for(QObject* object: _objectList) { if (object->property("dirty").isValid()) { object->setProperty("dirty", false); } } } emit dirtyChanged(_dirty); } } void QmlObjectListModel::_childDirtyChanged(bool dirty) { _dirty |= dirty; // We want to emit dirtyChanged even if the actual value of _dirty didn't change. It can be a useful // signal to know when a child has changed dirty state emit dirtyChanged(_dirty); } void QmlObjectListModel::deleteListAndContents() { for (int i=0; i<_objectList.count(); i++) { _objectList[i]->deleteLater(); } deleteLater(); } void QmlObjectListModel::clearAndDeleteContents() { beginResetModel(); for (int i=0; i<_objectList.count(); i++) { _objectList[i]->deleteLater(); } clear(); endResetModel(); } void QmlObjectListModel::beginReset() { if (_externalBeginResetModel) { qWarning() << "QmlObjectListModel::beginReset already set"; } _externalBeginResetModel = true; beginResetModel(); } void QmlObjectListModel::endReset() { if (!_externalBeginResetModel) { qWarning() << "QmlObjectListModel::endReset begin not set"; } _externalBeginResetModel = false; endResetModel(); }
8,628
2,715
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include <sol/sol.hpp> #include "tolua/LuaImGui.hpp" #include "imgui/ImGui.hpp" void tnt::lua::loadImGui(sol::state_view lua_) { auto imgui{lua_["imgui"].get_or_create<sol::table>()}; imgui.new_enum("win_flags", "colapsible", ImGui::WindowFlags::Collapsible, "closable", ImGui::WindowFlags::Closable, "resizable", ImGui::WindowFlags::Resizable, "movable", ImGui::WindowFlags::Movable, "with_titlebar", ImGui::WindowFlags::WithTitleBar, "opaque_bg", ImGui::WindowFlags::OpaqueBackground, "widget_first", ImGui::WindowFlags::WidgetThenText); imgui["init"] = &tnt_imgui_init; imgui["Begin"] = sol::overload( [](Window const &win, std::string_view name, int x, int y) -> bool { return ImGui::Begin(win, name, x, y); }, &ImGui::Begin); imgui["End"] = &ImGui::End; imgui["begin_section"] = &ImGui::BeginSection; imgui["end_section"] = &ImGui::EndSection; imgui["begin_list"] = &ImGui::BeginList; imgui["list_item"] = &ImGui::list_item; imgui["end_list"] = &ImGui::EndList; imgui["begin_menubar"] = &ImGui::BeginMenuBar; imgui["menu_button"] = &ImGui::menu_button; imgui["menu_item"] = &ImGui::menu_item; imgui["end_menubar"] = &ImGui::EndMenuBar; imgui["button"] = &ImGui::button; imgui["slider_int"] = &ImGui::slider_int; imgui["slider_float"] = &ImGui::slider_float; imgui["hslider_int"] = &ImGui::hslider_int; imgui["hslider_float"] = &ImGui::hslider_float; imgui["hslider_int2"] = &ImGui::hslider_int2; imgui["hslider_float2"] = &ImGui::hslider_float2; imgui["hslider_vec"] = &ImGui::hslider_vec; imgui["checkbox"] = &ImGui::checkbox; imgui["progress_bar"] = &ImGui::progress_bar; imgui["newline"] = &ImGui::newline; imgui["text"] = &ImGui::text; imgui["colored_text"] = &ImGui::colored_text; }
2,163
784
/* * @file core/dists/laplace_distribution.hpp * @author Zhihao Lou * @author Rohan Raj * * Laplace (double exponential) distribution used in SA. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP #define MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP namespace mlpack { namespace distribution { /** * The multivariate Laplace distribution centered at 0 has pdf * * \f[ * f(x|\theta) = \frac{1}{2 \theta}\exp\left(-\frac{\|x - \mu\|}{\theta}\right) * \f] * * given scale parameter \f$\theta\f$ and mean \f$\mu\f$. This implementation * assumes a diagonal covariance, but a rewrite to support arbitrary * covariances is possible. * * See the following paper for more information on the non-diagonal-covariance * Laplace distribution and estimation techniques: * * @code * @article{eltoft2006multivariate, * title={{On the Multivariate Laplace Distribution}}, * author={Eltoft, Torbj\orn and Kim, Taesu and Lee, Te-Won}, * journal={IEEE Signal Processing Letters}, * volume={13}, * number={5}, * pages={300--304}, * year={2006} * } * @endcode * * Note that because of the diagonal covariance restriction, much of the * algebra in the paper above becomes simplified, and the PDF takes roughly * the same form as the univariate case. */ class LaplaceDistribution { public: /** * Default constructor, which creates a Laplace distribution with zero * dimension and zero scale parameter. */ LaplaceDistribution() : scale(0) { } /** * Construct the Laplace distribution with the given scale and * dimensionality. The mean is initialized to zero. * * @param dimensionality Dimensionality of distribution. * @param scale Scale of distribution. */ LaplaceDistribution(const size_t dimensionality, const double scale) : mean(arma::zeros<arma::vec>(dimensionality)), scale(scale) { } /** * Construct the Laplace distribution with the given mean and scale * parameter. * * @param mean Mean of distribution. * @param scale Scale of distribution. */ LaplaceDistribution(const arma::vec& mean, const double scale) : mean(mean), scale(scale) { } //! Return the dimensionality of this distribution. size_t Dimensionality() const { return mean.n_elem; } /** * Return the probability of the given observation. * * @param observation Point to evaluate probability at. */ double Probability(const arma::vec& observation) const { return exp(LogProbability(observation)); } /** * Evaluate probability density function of given observation. * * @param x List of observations. * @param probabilities Output probabilities for each input observation. */ void Probability(const arma::mat& x, arma::vec& probabilities) const; /** * Return the log probability of the given observation. * * @param observation Point to evaluate logarithm of probability. */ double LogProbability(const arma::vec& observation) const; /** * Evaluate log probability density function of given observation. * * @param x List of observations. * @param logProbabilities Output probabilities for each input observation. */ void LogProbability(const arma::mat& x, arma::vec& logProbabilities) const { logProbabilities.set_size(x.n_cols); for (size_t i = 0; i < x.n_cols; i++) { logProbabilities(i) = LogProbability(x.unsafe_col(i)); } } /** * Return a randomly generated observation according to the probability * distribution defined by this object. This is inlined for speed. * * @return Random observation from this Laplace distribution. */ arma::vec Random() const { arma::vec result(mean.n_elem); result.randu(); // Convert from uniform distribution to Laplace distribution. // arma::sign() does not exist in Armadillo < 3.920 so we have to do this // elementwise. for (size_t i = 0; i < result.n_elem; ++i) { if (result[i] < 0.5) result[i] = mean[i] + scale * std::log(1 + 2.0 * (result[i] - 0.5)); else result[i] = mean[i] - scale * std::log(1 - 2.0 * (result[i] - 0.5)); } return result; } /** * Estimate the Laplace distribution directly from the given observations. * * @param observations List of observations. */ void Estimate(const arma::mat& observations); /** * Estimate the Laplace distribution from the given observations, taking into * account the probability of each observation actually being from this * distribution. */ void Estimate(const arma::mat& observations, const arma::vec& probabilities); //! Return the mean. const arma::vec& Mean() const { return mean; } //! Modify the mean. arma::vec& Mean() { return mean; } //! Return the scale parameter. double Scale() const { return scale; } //! Modify the scale parameter. double& Scale() { return scale; } /** * Serialize the distribution. */ template<typename Archive> void serialize(Archive& ar, const unsigned int /* version */) { ar & BOOST_SERIALIZATION_NVP(mean); ar & BOOST_SERIALIZATION_NVP(scale); } private: //! Mean of the distribution. arma::vec mean; //! Scale parameter of the distribution. double scale; }; } // namespace distribution } // namespace mlpack #endif
5,634
1,759
#include "idlecurrentpage.h" #include <QGridLayout> #include <QVBoxLayout> #include "testform.h" #include "currentform.h" #include "mainwindow.h" IdleCurrentPage::IdleCurrentPage(QWidget *parent) { currentForm=qobject_cast<TestForm*>(parent); // setTitle(QString::fromLocal8Bit("关机电流测试")); QFont font; font.setPointSize(11); QLabel *label = new QLabel(QString::fromLocal8Bit("二维码扫描操作完成了,现在请准备好关机电流测试,然后点击测试按钮,开始测试。")); label->setWordWrap(true); label->setFont(font); setButtonText(QWizard::NextButton,QString::fromLocal8Bit("测试")); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(label); setLayout(layout); } bool IdleCurrentPage::validatePage() { TestForm* pCurrentForm=static_cast<TestForm*>(currentForm); MainWindow *pMainWindow=MainWindow::getMainWindow(); string value; pCurrentForm->appendMessagebox(tr("The idle current test begin to test ......")); pMainWindow->m_niVisaGPIB.reset(); // pMainWindow->m_niVisaGPIB.autoZero(true); bool bGetCurrent=pMainWindow->m_niVisaGPIB.getCurrent(value); if(bGetCurrent){ bool bUpdate=pCurrentForm->updateIdleCurrent(true,value); if(bUpdate){ return true; } } return false; }
1,259
478
#include "../../../JString.hpp" #include "../../../JThrowable.hpp" #include "./XPathFactoryConfigurationException.hpp" namespace javax::xml::xpath { // Fields // QJniObject forward XPathFactoryConfigurationException::XPathFactoryConfigurationException(QJniObject obj) : javax::xml::xpath::XPathException(obj) {} // Constructors XPathFactoryConfigurationException::XPathFactoryConfigurationException(JString arg0) : javax::xml::xpath::XPathException( "javax.xml.xpath.XPathFactoryConfigurationException", "(Ljava/lang/String;)V", arg0.object<jstring>() ) {} XPathFactoryConfigurationException::XPathFactoryConfigurationException(JThrowable arg0) : javax::xml::xpath::XPathException( "javax.xml.xpath.XPathFactoryConfigurationException", "(Ljava/lang/Throwable;)V", arg0.object<jthrowable>() ) {} // Methods } // namespace javax::xml::xpath
880
290
/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "changed_props_set.hpp" #include <limits.h> #include "common/code_utils.hpp" namespace ot { namespace Ncp { // ---------------------------------------------------------------------------- // MARK: ChangedPropsSet class // ---------------------------------------------------------------------------- // Defines the list of properties that can support unsolicited update. // // Note that {`SPINEL_PROP_LAST_STATUS`, `SPINEL_STATUS_RESET_UNKNOWN`} should be first entry to ensure that RESET is // reported before any other property update. // // Since a `uint64_t` is used as bit-mask to track which entries are in the changed set, we should ensure that the // number of entries in the list is always less than or equal to 64. // const ChangedPropsSet::Entry ChangedPropsSet::mSupportedProps[] = { // Spinel property , Status (if prop is `LAST_STATUS`), IsFilterable? {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_RESET_UNKNOWN, false}, {SPINEL_PROP_STREAM_DEBUG, SPINEL_STATUS_OK, true}, {SPINEL_PROP_IPV6_LL_ADDR, SPINEL_STATUS_OK, true}, {SPINEL_PROP_IPV6_ML_ADDR, SPINEL_STATUS_OK, true}, {SPINEL_PROP_IPV6_ADDRESS_TABLE, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_ROLE, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_PARTITION_ID, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_KEY_SEQUENCE_COUNTER, SPINEL_STATUS_OK, true}, {SPINEL_PROP_THREAD_LEADER_NETWORK_DATA, SPINEL_STATUS_OK, true}, {SPINEL_PROP_THREAD_CHILD_TABLE, SPINEL_STATUS_OK, true}, {SPINEL_PROP_THREAD_ON_MESH_NETS, SPINEL_STATUS_OK, true}, {SPINEL_PROP_THREAD_OFF_MESH_ROUTES, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_STACK_UP, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_REQUIRE_JOIN_EXISTING, SPINEL_STATUS_OK, true}, {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_NOMEM, true}, {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_DROPPED, true}, #if OPENTHREAD_ENABLE_JAM_DETECTION {SPINEL_PROP_JAM_DETECTED, SPINEL_STATUS_OK, true}, #endif #if OPENTHREAD_ENABLE_LEGACY {SPINEL_PROP_NEST_LEGACY_ULA_PREFIX, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NEST_LEGACY_LAST_NODE_JOINED, SPINEL_STATUS_OK, true}, #endif {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_JOIN_FAILURE, false}, {SPINEL_PROP_MAC_SCAN_STATE, SPINEL_STATUS_OK, false}, {SPINEL_PROP_IPV6_MULTICAST_ADDRESS_TABLE, SPINEL_STATUS_OK, true}, {SPINEL_PROP_PHY_CHAN, SPINEL_STATUS_OK, true}, {SPINEL_PROP_MAC_15_4_PANID, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_NETWORK_NAME, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_XPANID, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_MASTER_KEY, SPINEL_STATUS_OK, true}, {SPINEL_PROP_NET_PSKC, SPINEL_STATUS_OK, true}, {SPINEL_PROP_PHY_CHAN_SUPPORTED, SPINEL_STATUS_OK, true}, #if OPENTHREAD_ENABLE_CHANNEL_MANAGER {SPINEL_PROP_CHANNEL_MANAGER_NEW_CHANNEL, SPINEL_STATUS_OK, true}, #endif #if OPENTHREAD_ENABLE_JOINER {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_JOIN_NO_PEERS, false}, {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_JOIN_SECURITY, false}, {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_JOIN_RSP_TIMEOUT, false}, {SPINEL_PROP_LAST_STATUS, SPINEL_STATUS_JOIN_SUCCESS, false}, #endif #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC {SPINEL_PROP_THREAD_NETWORK_TIME, SPINEL_STATUS_OK, false}, #endif {SPINEL_PROP_PARENT_RESPONSE_INFO, SPINEL_STATUS_OK, true}, }; uint8_t ChangedPropsSet::GetNumEntries(void) const { OT_STATIC_ASSERT(OT_ARRAY_LENGTH(mSupportedProps) <= sizeof(mChangedSet) * CHAR_BIT, "Changed set size is smaller than number of entries in `mSupportedProps[]` array"); return OT_ARRAY_LENGTH(mSupportedProps); } void ChangedPropsSet::Add(spinel_prop_key_t aPropKey, spinel_status_t aStatus) { uint8_t numEntries; const Entry *entry; entry = GetSupportedEntries(numEntries); for (uint8_t index = 0; index < numEntries; index++, entry++) { if ((entry->mPropKey == aPropKey) && (entry->mStatus == aStatus)) { if (!IsEntryFiltered(index)) { SetBit(mChangedSet, index); } break; } } } otError ChangedPropsSet::EnablePropertyFilter(spinel_prop_key_t aPropKey, bool aEnable) { uint8_t numEntries; const Entry *entry; bool didFind = false; entry = GetSupportedEntries(numEntries); for (uint8_t index = 0; index < numEntries; index++, entry++) { if (entry->mFilterable && (entry->mPropKey == aPropKey)) { if (aEnable) { SetBit(mFilterSet, index); // If filter is enabled for a property, the `mChangedSet` is cleared // for the same property so to ensure a pending update is also filtered. ClearBit(mChangedSet, index); } else { ClearBit(mFilterSet, index); } didFind = true; // Continue the search only if the prop key is `LAST_STATUS`, as // we have multiple filterable `LAST_STATUS` entries in the table // with different error status (DROPPED and NOMEM). if (aPropKey != SPINEL_PROP_LAST_STATUS) { break; } } } return didFind ? OT_ERROR_NONE : OT_ERROR_INVALID_ARGS; } bool ChangedPropsSet::IsPropertyFiltered(spinel_prop_key_t aPropKey) const { bool isFiltered = false; uint8_t numEntries; const Entry *entry; entry = GetSupportedEntries(numEntries); for (uint8_t index = 0; index < numEntries; index++, entry++) { if (entry->mFilterable && (entry->mPropKey == aPropKey)) { isFiltered = IsEntryFiltered(index); break; } } return isFiltered; } } // namespace Ncp } // namespace ot
7,495
2,753
#include "ros/ros.h" #include "std_msgs/Header.h" #include "sensor_msgs/Temperature.h" int main(int argc, char **argv) { // Initialize the ROS node ros::init(argc, argv, "TemperatureSensor", ros::init_options::AnonymousName); // Node handler ros::NodeHandle nodeHandler; // Publisher object ros::Publisher publisherObject = nodeHandler.advertise<sensor_msgs::Temperature>("temp_readings", 5); // Rate handler (5 Hz) ros::Rate rateHandler = ros::Rate(5); // Buffer variables float tempValue = 30.0; bool increment = true; // Publishing message sensor_msgs::Temperature msg; // Default properties msg.header.frame_id = "source"; msg.variance = 0.05; while(ros::ok()) { // Assign it time msg.header.stamp = ros::Time::now(); // Temperature value msg.temperature = tempValue; ROS_DEBUG("Temperature value : %f", tempValue); // Modify the temperature value tempValue += (increment) ? 0.1 : -0.1; if (tempValue >= 50 || tempValue <= 20) { increment = !increment; } // Publish the message publisherObject.publish(msg); // Increase sequence number msg.header.seq++; // Sleep for the rate satisfaction rateHandler.sleep(); } return 0; }
1,336
425
// Copyright 2021 - present, Mikhail Svetkin // All rights reserved. // // For the license information refer to LICENSE #ifndef ECORO_WHEN_ANY_HPP #define ECORO_WHEN_ANY_HPP #include "ecoro/awaitable_traits.hpp" #include "ecoro/detail/invoke_or_pass.hpp" #include "ecoro/task.hpp" #include <tuple> #include <variant> namespace ecoro { namespace detail { class when_any_observer { public: explicit when_any_observer(const std::size_t awaitables_count) noexcept : completed_index_(awaitables_count) {} bool set_continuation(std::coroutine_handle<> awaiting_coroutine) noexcept { awaiting_coroutine_ = awaiting_coroutine; return true; } void on_awaitable_completed(const std::size_t index) noexcept { completed_index_ = index; if (awaiting_coroutine_) { awaiting_coroutine_.resume(); return; } } std::size_t completed_index() const noexcept { return completed_index_; } private: std::size_t completed_index_; std::coroutine_handle<> awaiting_coroutine_; }; template<std::size_t Index, typename T> class when_any_task_promise : public task_promise<T> { struct final_awaiter { bool await_ready() const noexcept { return false; } template<typename Promise> void await_suspend( std::coroutine_handle<Promise> current_coroutine) noexcept { current_coroutine.promise().observer_->on_awaitable_completed(Index); } void await_resume() noexcept {} }; public: using task_promise<T>::task_promise; using value_type = std::conditional_t<std::is_void_v<T>, std::monostate, T>; final_awaiter final_suspend() noexcept { return {}; } value_type result() { if constexpr (std::is_void_v<T>) { return {}; } else { return task_promise<T>::result(); } } void set_observer(when_any_observer &observer) noexcept { observer_ = &observer; } private: when_any_observer *observer_{nullptr}; }; template<std::size_t Index, typename T> class when_any_task final : public task<T, when_any_task_promise<Index, T>> { public: using base = task<T, when_any_task_promise<Index, T>>; using base::base; when_any_task(base &&other) noexcept : base(std::move(other)) {} void resume(when_any_observer &observer) noexcept { base::handle().promise().set_observer(observer); base::resume(); } }; template<std::size_t Index, typename Awaitable> when_any_task<Index, awaitable_return_type<Awaitable>> make_when_any_task( Awaitable awaitable) { co_return co_await awaitable; } template<typename... Awaitables> class when_any_executor { using storage_type = std::tuple<Awaitables...>; struct result { std::size_t index{0}; storage_type awaitables; result(const std::size_t i, storage_type &&awaitables) : index(i), awaitables(std::move(awaitables)) {} result(result &&) noexcept = default; result &operator=(result &&) noexcept = default; result(result &) = delete; result operator=(result &) = delete; }; struct awaiter { bool await_ready() const noexcept { return false; } bool await_suspend(std::coroutine_handle<> awaiting_coroutine) noexcept { return executor_.start(awaiting_coroutine); } result await_resume() noexcept { return {executor_.observer_.completed_index(), std::move(executor_.awaitables_)}; } when_any_executor &executor_; }; public: explicit when_any_executor(Awaitables &&...awaitables) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) : awaitables_(std::forward<Awaitables>(awaitables)...) {} explicit when_any_executor(when_any_executor &&other) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) : observer_(std::move(other.observer_)), awaitables_(std::exchange(other.awaitables_, {})) {} when_any_executor &operator=(when_any_executor &&other) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) { if (std::addressof(other) != this) { observer_ = std::move(other.observer_); awaitables_ = std::move(other.awaitables_); } return *this; } auto operator co_await() noexcept { return awaiter{const_cast<when_any_executor &>(*this)}; } protected: bool start(std::coroutine_handle<> awaiting_coroutine) noexcept { std::apply([this](auto &&...args) { (start(args), ...); }, awaitables_); if (finished()) { return false; } observer_.set_continuation(awaiting_coroutine); return true; } template<typename Awaitable> void start(Awaitable &awaitable) noexcept { if (!finished()) awaitable.resume(observer_); } bool finished() const noexcept { return observer_.completed_index() < sizeof...(Awaitables); } private: when_any_observer observer_{sizeof...(Awaitables)}; storage_type awaitables_; }; template<typename... Awaitables> decltype(auto) make_when_any_executor(Awaitables &&...awaitables) { return when_any_executor<Awaitables...>( std::forward<Awaitables>(awaitables)...); } template<std::size_t... Indexes, typename... Awaitables> [[nodiscard]] decltype(auto) when_any(std::index_sequence<Indexes...>, Awaitables &&...awaitables) { return detail::make_when_any_executor( detail::make_when_any_task<Indexes, Awaitables>( detail::invoke_or_pass(std::forward<Awaitables>(awaitables)))...); } } // namespace detail template<typename... Awaitables> [[nodiscard]] decltype(auto) when_any(Awaitables &&...awaitables) { return detail::when_any(std::index_sequence_for<Awaitables...>{}, std::forward<Awaitables>(awaitables)...); } } // namespace ecoro #endif // ECORO_WHEN_ANY_HPP
5,810
2,000
#include <boost/mp11/mpl.hpp> #include <type_traits> template <int I> using int_ = std::integral_constant<int, I>; using namespace boost::mp11; template <typename Sequence, typename Value> struct index_of_impl { using index = mp_find<Sequence, Value>; using size = mp_size<Sequence>; using index_smaller_than_size = mp_less<index, size>; using type = mp_if<index_smaller_than_size, index, int_<-1>>; }; template <typename Sequence, typename Value> using index_of = typename index_of_impl<Sequence, Value>::type; int main() { using l = mp_list_c<int, 5, 2, 3, 1, 4>; constexpr int r1 = index_of<l, int_<3>>::value; static_assert(r1 == 2); constexpr int r2 = index_of<l, int_<6>>::value; static_assert(r2 == -1); }
729
290
#include "../benchmark/ArgParser.h" #include "ShapeTester.h" #include "VecGeom/volumes/GenTrap.h" typedef vecgeom::SimpleGenTrap GenTrap_t; int main(int argc, char *argv[]) { if (argc == 1) { std::cout << "Usage: shape_testGenTrap -test <#>:\n" " 0 - twisted\n" " 1 - planar\n" " 2 - one face triangle\n" " 3 - one face line\n" " 4 - one face point\n" " 5 - one face line, other triangle\n" " 6 - degenerated planar\n"; } OPTION_INT(npoints, 10000); OPTION_BOOL(debug, false); OPTION_BOOL(stat, false); OPTION_INT(type, 0); using namespace vecgeom; // 4 different vertices, twisted Precision verticesx0[8] = {-3, -2.5, 3, 2.5, -2, -2, 2, 2}; Precision verticesy0[8] = {-2.5, 3, 2.5, -3, -2, 2, 2, -2}; // 4 different vertices, planar Precision verticesx1[8] = {-3, -3, 3, 3, -2, -2, 2, 2}; Precision verticesy1[8] = {-3, 3, 3, -3, -2, 2, 2, -2}; // 3 different vertices Precision verticesx2[8] = {-3, -3, 3, 2.5, -2, -2, 2, 2}; Precision verticesy2[8] = {-2.5, -2.5, 2.5, -3, -2, 2, 2, -2}; // 2 different vertices Precision verticesx3[8] = {-3, -3, 2.5, 2.5, -2, -2, 2, 2}; Precision verticesy3[8] = {-2.5, -2.5, -3, -3, -2, 2, 2, -2}; // 1 vertex (pyramid) Precision verticesx4[8] = {-3, -3, -3, -3, -2, -2, 2, 2}; Precision verticesy4[8] = {-2.5, -2.5, -2.5, -2.5, -2, 2, 2, -2}; // 2 vertex bottom, 3 vertices top Precision verticesx5[8] = {-3, -3, 2.5, 2.5, -2, -2, 2, 2}; Precision verticesy5[8] = {-2.5, -2.5, -3, -3, -2, -2, 2, -2}; // Precision verticesx6[8] = {-0.507492, -0.507508, 1.522492, -0.507492, -0.507492, -0.507508, 1.522492, -0.507492}; Precision verticesy6[8] = {-3.634000, 3.63400, 3.634000, -3.634000, -3.634000, 3.634000, 3.634000, -3.634000}; GenTrap_t *solid = 0; switch (type) { case 0: // 4 different vertices, twisted std::cout << "Testing twisted trapezoid\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx0, verticesy0, 5); break; case 1: // 4 different vertices, planar std::cout << "Testing planar trapezoid\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx1, verticesy1, 5); break; case 2: // 3 different vertices std::cout << "Testing trapezoid with one face triangle\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx2, verticesy2, 5); break; case 3: // 2 different vertices std::cout << "Testing trapezoid with one face line degenerated\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx3, verticesy3, 5); break; case 4: // 1 vertex (pyramid) std::cout << "Testing trapezoid with one face point degenerated (pyramid)\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx4, verticesy4, 5); break; case 5: // 2 vertex bottom, 3 vertices top std::cout << "Testing trapezoid with line on one face and triangle on other\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx5, verticesy5, 5); break; case 6: // 3 vertexes top, 3 vertexes bottom std::cout << "Testing degenerated planar trapezoid\n"; solid = new GenTrap_t("test_VecGeomGenTrap", verticesx6, verticesy6, 5); break; default: std::cout << "Unknown test case.\n"; } solid->Print(); ShapeTester<vecgeom::VPlacedVolume> tester; tester.setDebug(debug); tester.setStat(stat); tester.SetMaxPoints(npoints); tester.SetSolidTolerance(1.e-7); tester.SetTestBoundaryErrors(true); int errCode = tester.Run(solid); std::cout << "Final Error count for Shape *** " << solid->GetName() << "*** = " << errCode << "\n"; std::cout << "=========================================================" << std::endl; if (solid) delete solid; return 0; }
3,862
1,704
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int mod = (int)1e9 + 7; string s; cin >> s; string t = "$chokudai"; map<char, int> ind; for ( int i = 0; i < (int)t.size(); i++ ) { ind[t[i]] = i; } map<char, int> cnt; cnt['$'] = 1; for (char x: s) { if (!ind.count(x)) continue; cnt[x] += cnt[t[ind[x]-1]]; cnt[x] %= mod; } cout << cnt['i'] << '\n'; }
472
235
// StartApp.cpp: implementation of the StartApp class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "commctrl.h" #include "DeskEditor1.h" #include "windowsx.h" #include "DeskEditor1.h" #include "StartApp.h" //#include "commctrl.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// StartApp::StartApp() { } StartApp::~StartApp() { } HWND StartApp::Run() { CDeskEditor *pD; pD = new CDeskEditor; pD->DoModal(::GetDesktopWindow()); return pD->m_hWnd ; }
693
225
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" #include <assert.h> //assert #include <string.h> //memset #include <algorithm> #include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h" #include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_impl.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { using namespace RTCPUtility; using namespace RTCPHelp; // The number of RTCP time intervals needed to trigger a timeout. const int kRrTimeoutIntervals = 3; RTCPReceiver::RTCPReceiver(const int32_t id, Clock* clock, ModuleRtpRtcpImpl* owner) : TMMBRHelp(), _id(id), _clock(clock), _method(kRtcpOff), _lastReceived(0), _rtpRtcp(*owner), _criticalSectionFeedbacks( CriticalSectionWrapper::CreateCriticalSection()), _cbRtcpFeedback(NULL), _cbRtcpBandwidthObserver(NULL), _cbRtcpIntraFrameObserver(NULL), _criticalSectionRTCPReceiver( CriticalSectionWrapper::CreateCriticalSection()), main_ssrc_(0), _remoteSSRC(0), _remoteSenderInfo(), _lastReceivedSRNTPsecs(0), _lastReceivedSRNTPfrac(0), _lastReceivedXRNTPsecs(0), _lastReceivedXRNTPfrac(0), xr_rr_rtt_ms_(0), _receivedInfoMap(), _packetTimeOutMS(0), _lastReceivedRrMs(0), _lastIncreasedSequenceNumberMs(0), stats_callback_(NULL) { memset(&_remoteSenderInfo, 0, sizeof(_remoteSenderInfo)); } RTCPReceiver::~RTCPReceiver() { delete _criticalSectionRTCPReceiver; delete _criticalSectionFeedbacks; while (!_receivedReportBlockMap.empty()) { std::map<uint32_t, RTCPReportBlockInformation*>::iterator first = _receivedReportBlockMap.begin(); delete first->second; _receivedReportBlockMap.erase(first); } while (!_receivedInfoMap.empty()) { std::map<uint32_t, RTCPReceiveInformation*>::iterator first = _receivedInfoMap.begin(); delete first->second; _receivedInfoMap.erase(first); } while (!_receivedCnameMap.empty()) { std::map<uint32_t, RTCPCnameInformation*>::iterator first = _receivedCnameMap.begin(); delete first->second; _receivedCnameMap.erase(first); } } void RTCPReceiver::ChangeUniqueId(const int32_t id) { _id = id; } RTCPMethod RTCPReceiver::Status() const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); return _method; } int32_t RTCPReceiver::SetRTCPStatus(const RTCPMethod method) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); _method = method; return 0; } int64_t RTCPReceiver::LastReceived() { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); return _lastReceived; } int64_t RTCPReceiver::LastReceivedReceiverReport() const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); int64_t last_received_rr = -1; for (ReceivedInfoMap::const_iterator it = _receivedInfoMap.begin(); it != _receivedInfoMap.end(); ++it) { if (it->second->lastTimeReceived > last_received_rr) { last_received_rr = it->second->lastTimeReceived; } } return last_received_rr; } int32_t RTCPReceiver::SetRemoteSSRC( const uint32_t ssrc) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); // new SSRC reset old reports memset(&_remoteSenderInfo, 0, sizeof(_remoteSenderInfo)); _lastReceivedSRNTPsecs = 0; _lastReceivedSRNTPfrac = 0; _remoteSSRC = ssrc; return 0; } uint32_t RTCPReceiver::RemoteSSRC() const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); return _remoteSSRC; } void RTCPReceiver::RegisterRtcpObservers( RtcpIntraFrameObserver* intra_frame_callback, RtcpBandwidthObserver* bandwidth_callback, RtcpFeedback* feedback_callback) { CriticalSectionScoped lock(_criticalSectionFeedbacks); _cbRtcpIntraFrameObserver = intra_frame_callback; _cbRtcpBandwidthObserver = bandwidth_callback; _cbRtcpFeedback = feedback_callback; } void RTCPReceiver::SetSsrcs(uint32_t main_ssrc, const std::set<uint32_t>& registered_ssrcs) { uint32_t old_ssrc = 0; { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); old_ssrc = main_ssrc_; main_ssrc_ = main_ssrc; registered_ssrcs_ = registered_ssrcs; } { CriticalSectionScoped lock(_criticalSectionFeedbacks); if (_cbRtcpIntraFrameObserver && old_ssrc != main_ssrc) { _cbRtcpIntraFrameObserver->OnLocalSsrcChanged(old_ssrc, main_ssrc); } } } int32_t RTCPReceiver::ResetRTT(const uint32_t remoteSSRC) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); RTCPReportBlockInformation* reportBlock = GetReportBlockInformation(remoteSSRC); if (reportBlock == NULL) { LOG(LS_WARNING) << "Failed to reset rtt for ssrc " << remoteSSRC; return -1; } reportBlock->RTT = 0; reportBlock->avgRTT = 0; reportBlock->minRTT = 0; reportBlock->maxRTT = 0; return 0; } int32_t RTCPReceiver::RTT(uint32_t remoteSSRC, uint16_t* RTT, uint16_t* avgRTT, uint16_t* minRTT, uint16_t* maxRTT) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); RTCPReportBlockInformation* reportBlock = GetReportBlockInformation(remoteSSRC); if (reportBlock == NULL) { return -1; } if (RTT) { *RTT = reportBlock->RTT; } if (avgRTT) { *avgRTT = reportBlock->avgRTT; } if (minRTT) { *minRTT = reportBlock->minRTT; } if (maxRTT) { *maxRTT = reportBlock->maxRTT; } return 0; } bool RTCPReceiver::GetAndResetXrRrRtt(uint16_t* rtt_ms) { assert(rtt_ms); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if (xr_rr_rtt_ms_ == 0) { return false; } *rtt_ms = xr_rr_rtt_ms_; xr_rr_rtt_ms_ = 0; return true; } // TODO(pbos): Make this fail when we haven't received NTP. bool RTCPReceiver::NTP(uint32_t* ReceivedNTPsecs, uint32_t* ReceivedNTPfrac, uint32_t* RTCPArrivalTimeSecs, uint32_t* RTCPArrivalTimeFrac, uint32_t* rtcp_timestamp) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if(ReceivedNTPsecs) { *ReceivedNTPsecs = _remoteSenderInfo.NTPseconds; // NTP from incoming SendReport } if(ReceivedNTPfrac) { *ReceivedNTPfrac = _remoteSenderInfo.NTPfraction; } if(RTCPArrivalTimeFrac) { *RTCPArrivalTimeFrac = _lastReceivedSRNTPfrac; // local NTP time when we received a RTCP packet with a send block } if(RTCPArrivalTimeSecs) { *RTCPArrivalTimeSecs = _lastReceivedSRNTPsecs; } if (rtcp_timestamp) { *rtcp_timestamp = _remoteSenderInfo.RTPtimeStamp; } return true; } bool RTCPReceiver::LastReceivedXrReferenceTimeInfo( RtcpReceiveTimeInfo* info) const { assert(info); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if (_lastReceivedXRNTPsecs == 0 && _lastReceivedXRNTPfrac == 0) { return false; } info->sourceSSRC = _remoteXRReceiveTimeInfo.sourceSSRC; info->lastRR = _remoteXRReceiveTimeInfo.lastRR; // Get the delay since last received report (RFC 3611). uint32_t receive_time = RTCPUtility::MidNtp(_lastReceivedXRNTPsecs, _lastReceivedXRNTPfrac); uint32_t ntp_sec = 0; uint32_t ntp_frac = 0; _clock->CurrentNtp(ntp_sec, ntp_frac); uint32_t now = RTCPUtility::MidNtp(ntp_sec, ntp_frac); info->delaySinceLastRR = now - receive_time; return true; } int32_t RTCPReceiver::SenderInfoReceived(RTCPSenderInfo* senderInfo) const { assert(senderInfo); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if (_lastReceivedSRNTPsecs == 0) { return -1; } memcpy(senderInfo, &(_remoteSenderInfo), sizeof(RTCPSenderInfo)); return 0; } // statistics // we can get multiple receive reports when we receive the report from a CE int32_t RTCPReceiver::StatisticsReceived( std::vector<RTCPReportBlock>* receiveBlocks) const { assert(receiveBlocks); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReportBlockInformation*>::const_iterator it = _receivedReportBlockMap.begin(); while (it != _receivedReportBlockMap.end()) { receiveBlocks->push_back(it->second->remoteReceiveBlock); it++; } return 0; } void RTCPReceiver::GetPacketTypeCounter( RtcpPacketTypeCounter* packet_counter) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); *packet_counter = packet_type_counter_; } int32_t RTCPReceiver::IncomingRTCPPacket(RTCPPacketInformation& rtcpPacketInformation, RTCPUtility::RTCPParserV2* rtcpParser) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); _lastReceived = _clock->TimeInMilliseconds(); RTCPUtility::RTCPPacketTypes pktType = rtcpParser->Begin(); while (pktType != RTCPUtility::kRtcpNotValidCode) { // Each "case" is responsible for iterate the parser to the // next top level packet. switch (pktType) { case RTCPUtility::kRtcpSrCode: case RTCPUtility::kRtcpRrCode: HandleSenderReceiverReport(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpSdesCode: HandleSDES(*rtcpParser); break; case RTCPUtility::kRtcpXrHeaderCode: HandleXrHeader(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpXrReceiverReferenceTimeCode: HandleXrReceiveReferenceTime(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpXrDlrrReportBlockCode: HandleXrDlrrReportBlock(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpXrVoipMetricCode: HandleXRVOIPMetric(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpByeCode: HandleBYE(*rtcpParser); break; case RTCPUtility::kRtcpRtpfbNackCode: HandleNACK(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpRtpfbTmmbrCode: HandleTMMBR(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpRtpfbTmmbnCode: HandleTMMBN(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpRtpfbSrReqCode: HandleSR_REQ(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpPsfbPliCode: HandlePLI(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpPsfbSliCode: HandleSLI(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpPsfbRpsiCode: HandleRPSI(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpExtendedIjCode: HandleIJ(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpPsfbFirCode: HandleFIR(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpPsfbAppCode: HandlePsfbApp(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpAppCode: // generic application messages HandleAPP(*rtcpParser, rtcpPacketInformation); break; case RTCPUtility::kRtcpAppItemCode: // generic application messages HandleAPPItem(*rtcpParser, rtcpPacketInformation); break; default: rtcpParser->Iterate(); break; } pktType = rtcpParser->PacketType(); } return 0; } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSenderReceiverReport(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { RTCPUtility::RTCPPacketTypes rtcpPacketType = rtcpParser.PacketType(); const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); assert((rtcpPacketType == RTCPUtility::kRtcpRrCode) || (rtcpPacketType == RTCPUtility::kRtcpSrCode)); // SR.SenderSSRC // The synchronization source identifier for the originator of this SR packet // rtcpPacket.RR.SenderSSRC // The source of the packet sender, same as of SR? or is this a CE? const uint32_t remoteSSRC = (rtcpPacketType == RTCPUtility::kRtcpRrCode) ? rtcpPacket.RR.SenderSSRC:rtcpPacket.SR.SenderSSRC; const uint8_t numberOfReportBlocks = (rtcpPacketType == RTCPUtility::kRtcpRrCode) ? rtcpPacket.RR.NumberOfReportBlocks:rtcpPacket.SR.NumberOfReportBlocks; rtcpPacketInformation.remoteSSRC = remoteSSRC; RTCPReceiveInformation* ptrReceiveInfo = CreateReceiveInformation(remoteSSRC); if (!ptrReceiveInfo) { rtcpParser.Iterate(); return; } if (rtcpPacketType == RTCPUtility::kRtcpSrCode) { TRACE_EVENT_INSTANT2("webrtc_rtp", "SR", "remote_ssrc", remoteSSRC, "ssrc", main_ssrc_); if (_remoteSSRC == remoteSSRC) // have I received RTP packets from this party { // only signal that we have received a SR when we accept one rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSr; rtcpPacketInformation.ntp_secs = rtcpPacket.SR.NTPMostSignificant; rtcpPacketInformation.ntp_frac = rtcpPacket.SR.NTPLeastSignificant; rtcpPacketInformation.rtp_timestamp = rtcpPacket.SR.RTPTimestamp; // We will only store the send report from one source, but // we will store all the receive block // Save the NTP time of this report _remoteSenderInfo.NTPseconds = rtcpPacket.SR.NTPMostSignificant; _remoteSenderInfo.NTPfraction = rtcpPacket.SR.NTPLeastSignificant; _remoteSenderInfo.RTPtimeStamp = rtcpPacket.SR.RTPTimestamp; _remoteSenderInfo.sendPacketCount = rtcpPacket.SR.SenderPacketCount; _remoteSenderInfo.sendOctetCount = rtcpPacket.SR.SenderOctetCount; _clock->CurrentNtp(_lastReceivedSRNTPsecs, _lastReceivedSRNTPfrac); } else { rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRr; } } else { TRACE_EVENT_INSTANT2("webrtc_rtp", "RR", "remote_ssrc", remoteSSRC, "ssrc", main_ssrc_); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRr; } UpdateReceiveInformation(*ptrReceiveInfo); rtcpPacketType = rtcpParser.Iterate(); while (rtcpPacketType == RTCPUtility::kRtcpReportBlockItemCode) { HandleReportBlock(rtcpPacket, rtcpPacketInformation, remoteSSRC, numberOfReportBlocks); rtcpPacketType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleReportBlock( const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation, const uint32_t remoteSSRC, const uint8_t numberOfReportBlocks) EXCLUSIVE_LOCKS_REQUIRED(_criticalSectionRTCPReceiver) { // This will be called once per report block in the RTCP packet. // We filter out all report blocks that are not for us. // Each packet has max 31 RR blocks. // // We can calc RTT if we send a send report and get a report block back. // |rtcpPacket.ReportBlockItem.SSRC| is the SSRC identifier of the source to // which the information in this reception report block pertains. // Filter out all report blocks that are not for us. if (registered_ssrcs_.find(rtcpPacket.ReportBlockItem.SSRC) == registered_ssrcs_.end()) { // This block is not for us ignore it. return; } // To avoid problem with acquiring _criticalSectionRTCPSender while holding // _criticalSectionRTCPReceiver. _criticalSectionRTCPReceiver->Leave(); uint32_t sendTimeMS = _rtpRtcp.SendTimeOfSendReport(rtcpPacket.ReportBlockItem.LastSR); _criticalSectionRTCPReceiver->Enter(); RTCPReportBlockInformation* reportBlock = CreateReportBlockInformation(remoteSSRC); if (reportBlock == NULL) { LOG(LS_WARNING) << "Failed to CreateReportBlockInformation(" << remoteSSRC << ")"; return; } _lastReceivedRrMs = _clock->TimeInMilliseconds(); const RTCPPacketReportBlockItem& rb = rtcpPacket.ReportBlockItem; reportBlock->remoteReceiveBlock.remoteSSRC = remoteSSRC; reportBlock->remoteReceiveBlock.sourceSSRC = rb.SSRC; reportBlock->remoteReceiveBlock.fractionLost = rb.FractionLost; reportBlock->remoteReceiveBlock.cumulativeLost = rb.CumulativeNumOfPacketsLost; if (rb.ExtendedHighestSequenceNumber > reportBlock->remoteReceiveBlock.extendedHighSeqNum) { // We have successfully delivered new RTP packets to the remote side after // the last RR was sent from the remote side. _lastIncreasedSequenceNumberMs = _lastReceivedRrMs; } reportBlock->remoteReceiveBlock.extendedHighSeqNum = rb.ExtendedHighestSequenceNumber; reportBlock->remoteReceiveBlock.jitter = rb.Jitter; reportBlock->remoteReceiveBlock.delaySinceLastSR = rb.DelayLastSR; reportBlock->remoteReceiveBlock.lastSR = rb.LastSR; if (rtcpPacket.ReportBlockItem.Jitter > reportBlock->remoteMaxJitter) { reportBlock->remoteMaxJitter = rtcpPacket.ReportBlockItem.Jitter; } uint32_t delaySinceLastSendReport = rtcpPacket.ReportBlockItem.DelayLastSR; // local NTP time when we received this uint32_t lastReceivedRRNTPsecs = 0; uint32_t lastReceivedRRNTPfrac = 0; _clock->CurrentNtp(lastReceivedRRNTPsecs, lastReceivedRRNTPfrac); // time when we received this in MS uint32_t receiveTimeMS = Clock::NtpToMs(lastReceivedRRNTPsecs, lastReceivedRRNTPfrac); // Estimate RTT uint32_t d = (delaySinceLastSendReport & 0x0000ffff) * 1000; d /= 65536; d += ((delaySinceLastSendReport & 0xffff0000) >> 16) * 1000; int32_t RTT = 0; if (sendTimeMS > 0) { RTT = receiveTimeMS - d - sendTimeMS; if (RTT <= 0) { RTT = 1; } if (RTT > reportBlock->maxRTT) { // store max RTT reportBlock->maxRTT = (uint16_t) RTT; } if (reportBlock->minRTT == 0) { // first RTT reportBlock->minRTT = (uint16_t) RTT; } else if (RTT < reportBlock->minRTT) { // Store min RTT reportBlock->minRTT = (uint16_t) RTT; } // store last RTT reportBlock->RTT = (uint16_t) RTT; // store average RTT if (reportBlock->numAverageCalcs != 0) { float ac = static_cast<float> (reportBlock->numAverageCalcs); float newAverage = ((ac / (ac + 1)) * reportBlock->avgRTT) + ((1 / (ac + 1)) * RTT); reportBlock->avgRTT = static_cast<int> (newAverage + 0.5f); } else { // first RTT reportBlock->avgRTT = (uint16_t) RTT; } reportBlock->numAverageCalcs++; } TRACE_COUNTER_ID1("webrtc_rtp", "RR_RTT", rb.SSRC, RTT); rtcpPacketInformation.AddReportInfo(*reportBlock); } RTCPReportBlockInformation* RTCPReceiver::CreateReportBlockInformation(uint32_t remoteSSRC) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReportBlockInformation*>::iterator it = _receivedReportBlockMap.find(remoteSSRC); RTCPReportBlockInformation* ptrReportBlockInfo = NULL; if (it != _receivedReportBlockMap.end()) { ptrReportBlockInfo = it->second; } else { ptrReportBlockInfo = new RTCPReportBlockInformation; _receivedReportBlockMap[remoteSSRC] = ptrReportBlockInfo; } return ptrReportBlockInfo; } RTCPReportBlockInformation* RTCPReceiver::GetReportBlockInformation(uint32_t remoteSSRC) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReportBlockInformation*>::const_iterator it = _receivedReportBlockMap.find(remoteSSRC); if (it == _receivedReportBlockMap.end()) { return NULL; } return it->second; } RTCPCnameInformation* RTCPReceiver::CreateCnameInformation(uint32_t remoteSSRC) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPCnameInformation*>::iterator it = _receivedCnameMap.find(remoteSSRC); if (it != _receivedCnameMap.end()) { return it->second; } RTCPCnameInformation* cnameInfo = new RTCPCnameInformation; memset(cnameInfo->name, 0, RTCP_CNAME_SIZE); _receivedCnameMap[remoteSSRC] = cnameInfo; return cnameInfo; } RTCPCnameInformation* RTCPReceiver::GetCnameInformation(uint32_t remoteSSRC) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPCnameInformation*>::const_iterator it = _receivedCnameMap.find(remoteSSRC); if (it == _receivedCnameMap.end()) { return NULL; } return it->second; } RTCPReceiveInformation* RTCPReceiver::CreateReceiveInformation(uint32_t remoteSSRC) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReceiveInformation*>::iterator it = _receivedInfoMap.find(remoteSSRC); if (it != _receivedInfoMap.end()) { return it->second; } RTCPReceiveInformation* receiveInfo = new RTCPReceiveInformation; _receivedInfoMap[remoteSSRC] = receiveInfo; return receiveInfo; } RTCPReceiveInformation* RTCPReceiver::GetReceiveInformation(uint32_t remoteSSRC) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReceiveInformation*>::iterator it = _receivedInfoMap.find(remoteSSRC); if (it == _receivedInfoMap.end()) { return NULL; } return it->second; } void RTCPReceiver::UpdateReceiveInformation( RTCPReceiveInformation& receiveInformation) { // Update that this remote is alive receiveInformation.lastTimeReceived = _clock->TimeInMilliseconds(); } bool RTCPReceiver::RtcpRrTimeout(int64_t rtcp_interval_ms) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if (_lastReceivedRrMs == 0) return false; int64_t time_out_ms = kRrTimeoutIntervals * rtcp_interval_ms; if (_clock->TimeInMilliseconds() > _lastReceivedRrMs + time_out_ms) { // Reset the timer to only trigger one log. _lastReceivedRrMs = 0; return true; } return false; } bool RTCPReceiver::RtcpRrSequenceNumberTimeout(int64_t rtcp_interval_ms) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if (_lastIncreasedSequenceNumberMs == 0) return false; int64_t time_out_ms = kRrTimeoutIntervals * rtcp_interval_ms; if (_clock->TimeInMilliseconds() > _lastIncreasedSequenceNumberMs + time_out_ms) { // Reset the timer to only trigger one log. _lastIncreasedSequenceNumberMs = 0; return true; } return false; } bool RTCPReceiver::UpdateRTCPReceiveInformationTimers() { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); bool updateBoundingSet = false; int64_t timeNow = _clock->TimeInMilliseconds(); std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt = _receivedInfoMap.begin(); while (receiveInfoIt != _receivedInfoMap.end()) { RTCPReceiveInformation* receiveInfo = receiveInfoIt->second; if (receiveInfo == NULL) { return updateBoundingSet; } // time since last received rtcp packet // when we dont have a lastTimeReceived and the object is marked // readyForDelete it's removed from the map if (receiveInfo->lastTimeReceived) { /// use audio define since we don't know what interval the remote peer is // using if ((timeNow - receiveInfo->lastTimeReceived) > 5 * RTCP_INTERVAL_AUDIO_MS) { // no rtcp packet for the last five regular intervals, reset limitations receiveInfo->TmmbrSet.clearSet(); // prevent that we call this over and over again receiveInfo->lastTimeReceived = 0; // send new TMMBN to all channels using the default codec updateBoundingSet = true; } receiveInfoIt++; } else if (receiveInfo->readyForDelete) { // store our current receiveInfoItem std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoItemToBeErased = receiveInfoIt; receiveInfoIt++; delete receiveInfoItemToBeErased->second; _receivedInfoMap.erase(receiveInfoItemToBeErased); } else { receiveInfoIt++; } } return updateBoundingSet; } int32_t RTCPReceiver::BoundingSet(bool &tmmbrOwner, TMMBRSet* boundingSetRec) { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt = _receivedInfoMap.find(_remoteSSRC); if (receiveInfoIt == _receivedInfoMap.end()) { return -1; } RTCPReceiveInformation* receiveInfo = receiveInfoIt->second; if (receiveInfo == NULL) { return -1; } if (receiveInfo->TmmbnBoundingSet.lengthOfSet() > 0) { boundingSetRec->VerifyAndAllocateSet( receiveInfo->TmmbnBoundingSet.lengthOfSet() + 1); for(uint32_t i=0; i< receiveInfo->TmmbnBoundingSet.lengthOfSet(); i++) { if(receiveInfo->TmmbnBoundingSet.Ssrc(i) == main_ssrc_) { // owner of bounding set tmmbrOwner = true; } boundingSetRec->SetEntry(i, receiveInfo->TmmbnBoundingSet.Tmmbr(i), receiveInfo->TmmbnBoundingSet.PacketOH(i), receiveInfo->TmmbnBoundingSet.Ssrc(i)); } } return receiveInfo->TmmbnBoundingSet.lengthOfSet(); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSDES(RTCPUtility::RTCPParserV2& rtcpParser) { RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpSdesChunkCode) { HandleSDESChunk(rtcpParser); pktType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSDESChunk(RTCPUtility::RTCPParserV2& rtcpParser) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPCnameInformation* cnameInfo = CreateCnameInformation(rtcpPacket.CName.SenderSSRC); assert(cnameInfo); cnameInfo->name[RTCP_CNAME_SIZE - 1] = 0; strncpy(cnameInfo->name, rtcpPacket.CName.CName, RTCP_CNAME_SIZE - 1); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleNACK(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); if (main_ssrc_ != rtcpPacket.NACK.MediaSSRC) { // Not to us. rtcpParser.Iterate(); return; } rtcpPacketInformation.ResetNACKPacketIdArray(); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpRtpfbNackItemCode) { HandleNACKItem(rtcpPacket, rtcpPacketInformation); pktType = rtcpParser.Iterate(); } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpNack) { ++packet_type_counter_.nack_packets; } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleNACKItem(const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation) { rtcpPacketInformation.AddNACKPacket(rtcpPacket.NACKItem.PacketID); uint16_t bitMask = rtcpPacket.NACKItem.BitMask; if(bitMask) { for(int i=1; i <= 16; ++i) { if(bitMask & 0x01) { rtcpPacketInformation.AddNACKPacket(rtcpPacket.NACKItem.PacketID + i); } bitMask = bitMask >>1; } } rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpNack; } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleBYE(RTCPUtility::RTCPParserV2& rtcpParser) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); // clear our lists CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReportBlockInformation*>::iterator reportBlockInfoIt = _receivedReportBlockMap.find( rtcpPacket.BYE.SenderSSRC); if (reportBlockInfoIt != _receivedReportBlockMap.end()) { delete reportBlockInfoIt->second; _receivedReportBlockMap.erase(reportBlockInfoIt); } // we can't delete it due to TMMBR std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt = _receivedInfoMap.find(rtcpPacket.BYE.SenderSSRC); if (receiveInfoIt != _receivedInfoMap.end()) { receiveInfoIt->second->readyForDelete = true; } std::map<uint32_t, RTCPCnameInformation*>::iterator cnameInfoIt = _receivedCnameMap.find(rtcpPacket.BYE.SenderSSRC); if (cnameInfoIt != _receivedCnameMap.end()) { delete cnameInfoIt->second; _receivedCnameMap.erase(cnameInfoIt); } xr_rr_rtt_ms_ = 0; rtcpParser.Iterate(); } void RTCPReceiver::HandleXrHeader( RTCPUtility::RTCPParserV2& parser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& packet = parser.Packet(); rtcpPacketInformation.xr_originator_ssrc = packet.XR.OriginatorSSRC; parser.Iterate(); } void RTCPReceiver::HandleXrReceiveReferenceTime( RTCPUtility::RTCPParserV2& parser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& packet = parser.Packet(); _remoteXRReceiveTimeInfo.sourceSSRC = rtcpPacketInformation.xr_originator_ssrc; _remoteXRReceiveTimeInfo.lastRR = RTCPUtility::MidNtp( packet.XRReceiverReferenceTimeItem.NTPMostSignificant, packet.XRReceiverReferenceTimeItem.NTPLeastSignificant); _clock->CurrentNtp(_lastReceivedXRNTPsecs, _lastReceivedXRNTPfrac); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrReceiverReferenceTime; parser.Iterate(); } void RTCPReceiver::HandleXrDlrrReportBlock( RTCPUtility::RTCPParserV2& parser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& packet = parser.Packet(); // Iterate through sub-block(s), if any. RTCPUtility::RTCPPacketTypes packet_type = parser.Iterate(); while (packet_type == RTCPUtility::kRtcpXrDlrrReportBlockItemCode) { HandleXrDlrrReportBlockItem(packet, rtcpPacketInformation); packet_type = parser.Iterate(); } } void RTCPReceiver::HandleXrDlrrReportBlockItem( const RTCPUtility::RTCPPacket& packet, RTCPPacketInformation& rtcpPacketInformation) EXCLUSIVE_LOCKS_REQUIRED(_criticalSectionRTCPReceiver) { if (registered_ssrcs_.find(packet.XRDLRRReportBlockItem.SSRC) == registered_ssrcs_.end()) { // Not to us. return; } rtcpPacketInformation.xr_dlrr_item = true; // To avoid problem with acquiring _criticalSectionRTCPSender while holding // _criticalSectionRTCPReceiver. _criticalSectionRTCPReceiver->Leave(); int64_t send_time_ms; bool found = _rtpRtcp.SendTimeOfXrRrReport( packet.XRDLRRReportBlockItem.LastRR, &send_time_ms); _criticalSectionRTCPReceiver->Enter(); if (!found) { return; } // The DelayLastRR field is in units of 1/65536 sec. uint32_t delay_rr_ms = (((packet.XRDLRRReportBlockItem.DelayLastRR & 0x0000ffff) * 1000) >> 16) + (((packet.XRDLRRReportBlockItem.DelayLastRR & 0xffff0000) >> 16) * 1000); int32_t rtt = _clock->CurrentNtpInMilliseconds() - delay_rr_ms - send_time_ms; xr_rr_rtt_ms_ = static_cast<uint16_t>(std::max(rtt, 1)); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrDlrrReportBlock; } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleXRVOIPMetric(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); if(rtcpPacket.XRVOIPMetricItem.SSRC == main_ssrc_) { // Store VoIP metrics block if it's about me // from OriginatorSSRC do we filter it? // rtcpPacket.XR.OriginatorSSRC; RTCPVoIPMetric receivedVoIPMetrics; receivedVoIPMetrics.burstDensity = rtcpPacket.XRVOIPMetricItem.burstDensity; receivedVoIPMetrics.burstDuration = rtcpPacket.XRVOIPMetricItem.burstDuration; receivedVoIPMetrics.discardRate = rtcpPacket.XRVOIPMetricItem.discardRate; receivedVoIPMetrics.endSystemDelay = rtcpPacket.XRVOIPMetricItem.endSystemDelay; receivedVoIPMetrics.extRfactor = rtcpPacket.XRVOIPMetricItem.extRfactor; receivedVoIPMetrics.gapDensity = rtcpPacket.XRVOIPMetricItem.gapDensity; receivedVoIPMetrics.gapDuration = rtcpPacket.XRVOIPMetricItem.gapDuration; receivedVoIPMetrics.Gmin = rtcpPacket.XRVOIPMetricItem.Gmin; receivedVoIPMetrics.JBabsMax = rtcpPacket.XRVOIPMetricItem.JBabsMax; receivedVoIPMetrics.JBmax = rtcpPacket.XRVOIPMetricItem.JBmax; receivedVoIPMetrics.JBnominal = rtcpPacket.XRVOIPMetricItem.JBnominal; receivedVoIPMetrics.lossRate = rtcpPacket.XRVOIPMetricItem.lossRate; receivedVoIPMetrics.MOSCQ = rtcpPacket.XRVOIPMetricItem.MOSCQ; receivedVoIPMetrics.MOSLQ = rtcpPacket.XRVOIPMetricItem.MOSLQ; receivedVoIPMetrics.noiseLevel = rtcpPacket.XRVOIPMetricItem.noiseLevel; receivedVoIPMetrics.RERL = rtcpPacket.XRVOIPMetricItem.RERL; receivedVoIPMetrics.Rfactor = rtcpPacket.XRVOIPMetricItem.Rfactor; receivedVoIPMetrics.roundTripDelay = rtcpPacket.XRVOIPMetricItem.roundTripDelay; receivedVoIPMetrics.RXconfig = rtcpPacket.XRVOIPMetricItem.RXconfig; receivedVoIPMetrics.signalLevel = rtcpPacket.XRVOIPMetricItem.signalLevel; rtcpPacketInformation.AddVoIPMetric(&receivedVoIPMetrics); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrVoipMetric; // received signal } rtcpParser.Iterate(); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandlePLI(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); if (main_ssrc_ == rtcpPacket.PLI.MediaSSRC) { TRACE_EVENT_INSTANT0("webrtc_rtp", "PLI"); ++packet_type_counter_.pli_packets; // Received a signal that we need to send a new key frame. rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpPli; } rtcpParser.Iterate(); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleTMMBR(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); uint32_t senderSSRC = rtcpPacket.TMMBR.SenderSSRC; RTCPReceiveInformation* ptrReceiveInfo = GetReceiveInformation(senderSSRC); if (ptrReceiveInfo == NULL) { // This remote SSRC must be saved before. rtcpParser.Iterate(); return; } if(rtcpPacket.TMMBR.MediaSSRC) { // rtcpPacket.TMMBR.MediaSSRC SHOULD be 0 if same as SenderSSRC // in relay mode this is a valid number senderSSRC = rtcpPacket.TMMBR.MediaSSRC; } // Use packet length to calc max number of TMMBR blocks // each TMMBR block is 8 bytes ptrdiff_t maxNumOfTMMBRBlocks = rtcpParser.LengthLeft() / 8; // sanity if(maxNumOfTMMBRBlocks > 200) // we can't have more than what's in one packet { assert(false); rtcpParser.Iterate(); return; } ptrReceiveInfo->VerifyAndAllocateTMMBRSet((uint32_t)maxNumOfTMMBRBlocks); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpRtpfbTmmbrItemCode) { HandleTMMBRItem(*ptrReceiveInfo, rtcpPacket, rtcpPacketInformation, senderSSRC); pktType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleTMMBRItem(RTCPReceiveInformation& receiveInfo, const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation, const uint32_t senderSSRC) { if (main_ssrc_ == rtcpPacket.TMMBRItem.SSRC && rtcpPacket.TMMBRItem.MaxTotalMediaBitRate > 0) { receiveInfo.InsertTMMBRItem(senderSSRC, rtcpPacket.TMMBRItem, _clock->TimeInMilliseconds()); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTmmbr; } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleTMMBN(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPReceiveInformation* ptrReceiveInfo = GetReceiveInformation(rtcpPacket.TMMBN.SenderSSRC); if (ptrReceiveInfo == NULL) { // This remote SSRC must be saved before. rtcpParser.Iterate(); return; } rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTmmbn; // Use packet length to calc max number of TMMBN blocks // each TMMBN block is 8 bytes ptrdiff_t maxNumOfTMMBNBlocks = rtcpParser.LengthLeft() / 8; // sanity if(maxNumOfTMMBNBlocks > 200) // we cant have more than what's in one packet { assert(false); rtcpParser.Iterate(); return; } ptrReceiveInfo->VerifyAndAllocateBoundingSet((uint32_t)maxNumOfTMMBNBlocks); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpRtpfbTmmbnItemCode) { HandleTMMBNItem(*ptrReceiveInfo, rtcpPacket); pktType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSR_REQ(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSrReq; rtcpParser.Iterate(); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleTMMBNItem(RTCPReceiveInformation& receiveInfo, const RTCPUtility::RTCPPacket& rtcpPacket) { receiveInfo.TmmbnBoundingSet.AddEntry( rtcpPacket.TMMBNItem.MaxTotalMediaBitRate, rtcpPacket.TMMBNItem.MeasuredOverhead, rtcpPacket.TMMBNItem.SSRC); } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSLI(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpPsfbSliItemCode) { HandleSLIItem(rtcpPacket, rtcpPacketInformation); pktType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleSLIItem(const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation) { // in theory there could be multiple slices lost rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSli; // received signal that we need to refresh a slice rtcpPacketInformation.sliPictureId = rtcpPacket.SLIItem.PictureId; } void RTCPReceiver::HandleRPSI(RTCPUtility::RTCPParserV2& rtcpParser, RTCPHelp::RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); if(pktType == RTCPUtility::kRtcpPsfbRpsiCode) { rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRpsi; // received signal that we have a confirmed reference picture if(rtcpPacket.RPSI.NumberOfValidBits%8 != 0) { // to us unknown // continue rtcpParser.Iterate(); return; } rtcpPacketInformation.rpsiPictureId = 0; // convert NativeBitString to rpsiPictureId uint8_t numberOfBytes = rtcpPacket.RPSI.NumberOfValidBits /8; for(uint8_t n = 0; n < (numberOfBytes-1); n++) { rtcpPacketInformation.rpsiPictureId += (rtcpPacket.RPSI.NativeBitString[n] & 0x7f); rtcpPacketInformation.rpsiPictureId <<= 7; // prepare next } rtcpPacketInformation.rpsiPictureId += (rtcpPacket.RPSI.NativeBitString[numberOfBytes-1] & 0x7f); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandlePsfbApp(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); if (pktType == RTCPUtility::kRtcpPsfbRembCode) { pktType = rtcpParser.Iterate(); if (pktType == RTCPUtility::kRtcpPsfbRembItemCode) { HandleREMBItem(rtcpParser, rtcpPacketInformation); rtcpParser.Iterate(); } } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleIJ(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpExtendedIjItemCode) { HandleIJItem(rtcpPacket, rtcpPacketInformation); pktType = rtcpParser.Iterate(); } } void RTCPReceiver::HandleIJItem(const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation) { rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTransmissionTimeOffset; rtcpPacketInformation.interArrivalJitter = rtcpPacket.ExtendedJitterReportItem.Jitter; } void RTCPReceiver::HandleREMBItem( RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRemb; rtcpPacketInformation.receiverEstimatedMaxBitrate = rtcpPacket.REMBItem.BitRate; } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleFIR(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); RTCPReceiveInformation* ptrReceiveInfo = GetReceiveInformation(rtcpPacket.FIR.SenderSSRC); RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate(); while (pktType == RTCPUtility::kRtcpPsfbFirItemCode) { HandleFIRItem(ptrReceiveInfo, rtcpPacket, rtcpPacketInformation); pktType = rtcpParser.Iterate(); } } // no need for critsect we have _criticalSectionRTCPReceiver void RTCPReceiver::HandleFIRItem(RTCPReceiveInformation* receiveInfo, const RTCPUtility::RTCPPacket& rtcpPacket, RTCPPacketInformation& rtcpPacketInformation) { // Is it our sender that is requested to generate a new keyframe if (main_ssrc_ != rtcpPacket.FIRItem.SSRC) { return; } ++packet_type_counter_.fir_packets; // rtcpPacket.FIR.MediaSSRC SHOULD be 0 but we ignore to check it // we don't know who this originate from if (receiveInfo) { // check if we have reported this FIRSequenceNumber before if (rtcpPacket.FIRItem.CommandSequenceNumber != receiveInfo->lastFIRSequenceNumber) { int64_t now = _clock->TimeInMilliseconds(); // sanity; don't go crazy with the callbacks if ((now - receiveInfo->lastFIRRequest) > RTCP_MIN_FRAME_LENGTH_MS) { receiveInfo->lastFIRRequest = now; receiveInfo->lastFIRSequenceNumber = rtcpPacket.FIRItem.CommandSequenceNumber; // received signal that we need to send a new key frame rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpFir; } } } else { // received signal that we need to send a new key frame rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpFir; } } void RTCPReceiver::HandleAPP(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpApp; rtcpPacketInformation.applicationSubType = rtcpPacket.APP.SubType; rtcpPacketInformation.applicationName = rtcpPacket.APP.Name; rtcpParser.Iterate(); } void RTCPReceiver::HandleAPPItem(RTCPUtility::RTCPParserV2& rtcpParser, RTCPPacketInformation& rtcpPacketInformation) { const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet(); rtcpPacketInformation.AddApplicationData(rtcpPacket.APP.Data, rtcpPacket.APP.Size); rtcpParser.Iterate(); } int32_t RTCPReceiver::UpdateTMMBR() { int32_t numBoundingSet = 0; uint32_t bitrate = 0; uint32_t accNumCandidates = 0; int32_t size = TMMBRReceived(0, 0, NULL); if (size > 0) { TMMBRSet* candidateSet = VerifyAndAllocateCandidateSet(size); // Get candidate set from receiver. accNumCandidates = TMMBRReceived(size, accNumCandidates, candidateSet); } else { // Candidate set empty. VerifyAndAllocateCandidateSet(0); // resets candidate set } // Find bounding set TMMBRSet* boundingSet = NULL; numBoundingSet = FindTMMBRBoundingSet(boundingSet); if (numBoundingSet == -1) { LOG(LS_WARNING) << "Failed to find TMMBR bounding set."; return -1; } // Set bounding set // Inform remote clients about the new bandwidth // inform the remote client _rtpRtcp.SetTMMBN(boundingSet); // might trigger a TMMBN if (numBoundingSet == 0) { // owner of max bitrate request has timed out // empty bounding set has been sent return 0; } // Get net bitrate from bounding set depending on sent packet rate if (CalcMinBitRate(&bitrate)) { // we have a new bandwidth estimate on this channel CriticalSectionScoped lock(_criticalSectionFeedbacks); if (_cbRtcpBandwidthObserver) { _cbRtcpBandwidthObserver->OnReceivedEstimatedBitrate(bitrate * 1000); } } return 0; } void RTCPReceiver::RegisterRtcpStatisticsCallback( RtcpStatisticsCallback* callback) { CriticalSectionScoped cs(_criticalSectionFeedbacks); stats_callback_ = callback; } RtcpStatisticsCallback* RTCPReceiver::GetRtcpStatisticsCallback() { CriticalSectionScoped cs(_criticalSectionFeedbacks); return stats_callback_; } // Holding no Critical section void RTCPReceiver::TriggerCallbacksFromRTCPPacket( RTCPPacketInformation& rtcpPacketInformation) { // Process TMMBR and REMB first to avoid multiple callbacks // to OnNetworkChanged. if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpTmmbr) { // Might trigger a OnReceivedBandwidthEstimateUpdate. UpdateTMMBR(); } unsigned int local_ssrc = 0; { // We don't want to hold this critsect when triggering the callbacks below. CriticalSectionScoped lock(_criticalSectionRTCPReceiver); local_ssrc = main_ssrc_; } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSrReq) { _rtpRtcp.OnRequestSendReport(); } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpNack) { if (rtcpPacketInformation.nackSequenceNumbers.size() > 0) { LOG(LS_VERBOSE) << "Incoming NACK length: " << rtcpPacketInformation.nackSequenceNumbers.size(); _rtpRtcp.OnReceivedNACK(rtcpPacketInformation.nackSequenceNumbers); } } { CriticalSectionScoped lock(_criticalSectionFeedbacks); // We need feedback that we have received a report block(s) so that we // can generate a new packet in a conference relay scenario, one received // report can generate several RTCP packets, based on number relayed/mixed // a send report block should go out to all receivers. if (_cbRtcpIntraFrameObserver) { if ((rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpPli) || (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpFir)) { if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpPli) { LOG(LS_VERBOSE) << "Incoming PLI from SSRC " << rtcpPacketInformation.remoteSSRC; } else { LOG(LS_VERBOSE) << "Incoming FIR from SSRC " << rtcpPacketInformation.remoteSSRC; } _cbRtcpIntraFrameObserver->OnReceivedIntraFrameRequest(local_ssrc); } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSli) { _cbRtcpIntraFrameObserver->OnReceivedSLI( local_ssrc, rtcpPacketInformation.sliPictureId); } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRpsi) { _cbRtcpIntraFrameObserver->OnReceivedRPSI( local_ssrc, rtcpPacketInformation.rpsiPictureId); } } if (_cbRtcpBandwidthObserver) { if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRemb) { LOG(LS_VERBOSE) << "Incoming REMB: " << rtcpPacketInformation.receiverEstimatedMaxBitrate; _cbRtcpBandwidthObserver->OnReceivedEstimatedBitrate( rtcpPacketInformation.receiverEstimatedMaxBitrate); } if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSr || rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRr) { int64_t now = _clock->TimeInMilliseconds(); _cbRtcpBandwidthObserver->OnReceivedRtcpReceiverReport( rtcpPacketInformation.report_blocks, rtcpPacketInformation.rtt, now); } } if(_cbRtcpFeedback) { if(!(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSr)) { _cbRtcpFeedback->OnReceiveReportReceived(_id, rtcpPacketInformation.remoteSSRC); } if(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpXrVoipMetric) { _cbRtcpFeedback->OnXRVoIPMetricReceived(_id, rtcpPacketInformation.VoIPMetric); } if(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpApp) { _cbRtcpFeedback->OnApplicationDataReceived(_id, rtcpPacketInformation.applicationSubType, rtcpPacketInformation.applicationName, rtcpPacketInformation.applicationLength, rtcpPacketInformation.applicationData); } } } { CriticalSectionScoped cs(_criticalSectionFeedbacks); if (stats_callback_) { for (ReportBlockList::const_iterator it = rtcpPacketInformation.report_blocks.begin(); it != rtcpPacketInformation.report_blocks.end(); ++it) { RtcpStatistics stats; stats.cumulative_lost = it->cumulativeLost; stats.extended_max_sequence_number = it->extendedHighSeqNum; stats.fraction_lost = it->fractionLost; stats.jitter = it->jitter; stats_callback_->StatisticsUpdated(stats, it->sourceSSRC); } } } } int32_t RTCPReceiver::CNAME(const uint32_t remoteSSRC, char cName[RTCP_CNAME_SIZE]) const { assert(cName); CriticalSectionScoped lock(_criticalSectionRTCPReceiver); RTCPCnameInformation* cnameInfo = GetCnameInformation(remoteSSRC); if (cnameInfo == NULL) { return -1; } cName[RTCP_CNAME_SIZE - 1] = 0; strncpy(cName, cnameInfo->name, RTCP_CNAME_SIZE - 1); return 0; } // no callbacks allowed inside this function int32_t RTCPReceiver::TMMBRReceived(const uint32_t size, const uint32_t accNumCandidates, TMMBRSet* candidateSet) const { CriticalSectionScoped lock(_criticalSectionRTCPReceiver); std::map<uint32_t, RTCPReceiveInformation*>::const_iterator receiveInfoIt = _receivedInfoMap.begin(); if (receiveInfoIt == _receivedInfoMap.end()) { return -1; } uint32_t num = accNumCandidates; if (candidateSet) { while( num < size && receiveInfoIt != _receivedInfoMap.end()) { RTCPReceiveInformation* receiveInfo = receiveInfoIt->second; if (receiveInfo == NULL) { return 0; } for (uint32_t i = 0; (num < size) && (i < receiveInfo->TmmbrSet.lengthOfSet()); i++) { if (receiveInfo->GetTMMBRSet(i, num, candidateSet, _clock->TimeInMilliseconds()) == 0) { num++; } } receiveInfoIt++; } } else { while (receiveInfoIt != _receivedInfoMap.end()) { RTCPReceiveInformation* receiveInfo = receiveInfoIt->second; if(receiveInfo == NULL) { return -1; } num += receiveInfo->TmmbrSet.lengthOfSet(); receiveInfoIt++; } } return num; } } // namespace webrtc
53,548
18,232
#ifndef AGPU_METAL_PIPELINE_STATE_HPP #define AGPU_METAL_PIPELINE_STATE_HPP #include "device.hpp" #include "pipeline_command_state.hpp" namespace AgpuMetal { class AMtlComputePipelineBuilder; class AMtlGraphicsPipelineBuilder; class AGPUMTLPipelineStateExtra { public: virtual ~AGPUMTLPipelineStateExtra() {} virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) {} virtual void applyComputeCommands(id<MTLComputeCommandEncoder> computeEncoder) {} virtual bool isRender() const { return false; } virtual bool isCompute() const { return false; } virtual MTLSize getLocalSize() { return MTLSize(); } virtual agpu_pipeline_command_state *getCommandState() { return nullptr; } }; class AGPUMTLRenderPipelineState : public AGPUMTLPipelineStateExtra { public: AGPUMTLRenderPipelineState(); ~AGPUMTLRenderPipelineState(); virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) override; virtual bool isRender() const override { return true; } virtual agpu_pipeline_command_state *getCommandState() override { return &commandState; } id<MTLRenderPipelineState> handle; id<MTLDepthStencilState> depthStencilState; agpu_pipeline_command_state commandState; agpu_float depthBiasConstantFactor; agpu_float depthBiasClamp; agpu_float depthBiasSlopeFactor; }; class AGPUMTLComputePipelineState : public AGPUMTLPipelineStateExtra { public: AGPUMTLComputePipelineState(); ~AGPUMTLComputePipelineState(); virtual void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder) override; virtual MTLSize getLocalSize() override { return localSize; } virtual bool isCompute() const override { return true; } id<MTLComputePipelineState> handle; MTLSize localSize; }; struct AMtlPipelineState : public agpu::pipeline_state { public: AMtlPipelineState(const agpu::device_ref &device); ~AMtlPipelineState(); static agpu::pipeline_state_ref createRender(const agpu::device_ref &device, AMtlGraphicsPipelineBuilder *builder, id<MTLRenderPipelineState> handle); static agpu::pipeline_state_ref createCompute(const agpu::device_ref &device, AMtlComputePipelineBuilder *builder, id<MTLComputePipelineState> handle); void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder); void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder); agpu_pipeline_command_state &getCommandState() { return *extraState->getCommandState(); } agpu::device_ref device; std::unique_ptr<AGPUMTLPipelineStateExtra> extraState; }; } // End of namespace AgpuMetal #endif //AGPU_METAL_PIPELINE_STATE_HPP
2,875
931
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "Tests.h" #include <GridMate/Carrier/StreamSocketDriver.h> #include <AzCore/Math/Random.h> using namespace GridMate; #define TEST_WITH_EXTERNAL_HOSTS 0 namespace UnitTest { bool ConnectStreamSocketDriverServerClient(StreamSocketDriver& server, StreamSocketDriver& client, StreamSocketDriver::SocketDriverAddressPtr& serverAddress, const AZ::u32 attempts) { for (AZ::u32 i = 0; i < attempts; ++i) { server.Update(); client.Update(); if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress)) { return true; } } return false; } bool ConnectStreamSocketInitializeAndConnect(StreamSocketDriver& server, StreamSocketDriver& client, const AZ::u32 attempts) { server.Initialize(); server.StartListen(1); client.Initialize(); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName)); client.ConnectTo(serverAddress); return ConnectStreamSocketDriverServerClient(server, client, serverAddress, attempts); } class StreamSocketOperationTests : public GridMateMPTestFixture { public: void run() { #if TEST_WITH_EXTERNAL_HOSTS // using blocking sockets // create and bind GridMate::SocketDriverCommon::SocketType theSocket; { SocketAddressInfo addressInfo; addressInfo.Resolve(nullptr, 0, Driver::BSDSocketFamilyType::BSD_AF_INET, false, GridMate::SocketAddressInfo::AdditionalOptionFlags::Passive); theSocket = SocketOperations::CreateSocket(false, Driver::BSDSocketFamilyType::BSD_AF_INET); AZ_TEST_ASSERT(SocketOperations::Bind(theSocket, addressInfo.GetAddressInfo()->ai_addr, addressInfo.GetAddressInfo()->ai_addrlen) == GridMate::Driver::EC_OK); } // connect and send and receive { GridMate::SocketOperations::ConnectionResult connectionResult; SocketAddressInfo addressInfo; auto flags = GridMate::SocketAddressInfo::AdditionalOptionFlags::Passive; AZ_TEST_ASSERT(addressInfo.Resolve("www.github.com", 80, Driver::BSDSocketFamilyType::BSD_AF_INET, false, flags)); AZ_TEST_ASSERT(SocketOperations::Connect(theSocket, addressInfo.GetAddressInfo()->ai_addr, addressInfo.GetAddressInfo()->ai_addrlen, connectionResult) == GridMate::Driver::EC_OK); // happy path char buf[] = { "GET http://www.github.com/ HTTP/1.0\r\nUser-Agent: HTTPTool/1.0\r\n\r\n\r\n" }; AZ::u32 bytesSent = sizeof(buf); AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], sizeof(buf), bytesSent) == GridMate::Driver::EC_OK); AZ_TEST_ASSERT(bytesSent > 0); char getBuffer[1024]; AZ::u32 bytesToGet = sizeof(getBuffer); AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) == GridMate::Driver::EC_OK); AZ_TEST_ASSERT(bytesToGet > 0); // fails expected AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], 0, bytesSent) != GridMate::Driver::EC_OK); AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], static_cast<AZ::u32>(-29), bytesSent) != GridMate::Driver::EC_OK); bytesToGet = 0; AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) != GridMate::Driver::EC_OK); bytesToGet = static_cast<AZ::u32>(-29); AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) != GridMate::Driver::EC_OK); } #endif // TEST_WITH_EXTERNAL_HOSTS } }; class StreamSocketDriverTestsCreateDelete : public GridMateMPTestFixture { public: void run() { StreamSocketDriver driver; AZ_TEST_ASSERT(driver.GetMaxNumConnections() == 32); } }; class StreamSocketDriverTestsBindSocketEmpty : public GridMateMPTestFixture { public: void run() { { StreamSocketDriver server(32); auto ret = server.Initialize(); AZ_TEST_ASSERT(ret == GridMate::Driver::EC_OK); } { StreamSocketDriver client(1); auto ret = client.Initialize(); AZ_TEST_ASSERT(ret == GridMate::Driver::EC_OK); } } }; class StreamSocketDriverTestsSimpleLockStepConnection : public GridMateMPTestFixture { public: void run() { StreamSocketDriver server(32); auto serverInitialize = server.Initialize(); AZ_TEST_ASSERT(serverInitialize == GridMate::Driver::EC_OK); StreamSocketDriver client(1); auto clientInitialize = client.Initialize(); AZ_TEST_ASSERT(clientInitialize == GridMate::Driver::EC_OK); AZ_TEST_ASSERT(server.StartListen(255) == GridMate::Driver::EC_OK); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); auto driveAddress = client.CreateDriverAddress(serverAddressName); auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(driveAddress); AZ_TEST_ASSERT(client.ConnectTo(serverAddress) == GridMate::Driver::EC_OK); bool didConnect = false; const int kNumTimes = 100; for (int i = 0; i < kNumTimes; ++i) { server.Update(); client.Update(); if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress)) { didConnect = true; break; } } AZ_TEST_ASSERT(didConnect); } }; class StreamSocketDriverTestsEstablishConnectAndSend : public GridMateMPTestFixture { public: void run() { StreamSocketDriver server(2); auto serverInitialize = server.Initialize(GridMate::Driver::BSDSocketFamilyType::BSD_AF_INET, "0.0.0.0", 29920, false, 0, 0); AZ_TEST_ASSERT(serverInitialize == GridMate::Driver::EC_OK); StreamSocketDriver client(1); auto clientInitialize = client.Initialize(); AZ_TEST_ASSERT(clientInitialize == GridMate::Driver::EC_OK); AZ_TEST_ASSERT(server.StartListen(2) == GridMate::Driver::EC_OK); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); auto driveAddress = client.CreateDriverAddress(serverAddressName); auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(driveAddress); AZ_TEST_ASSERT(client.ConnectTo(serverAddress) == GridMate::Driver::EC_OK); bool didConnect = false; const int kNumTimes = 1000; for (int i = 0; i < kNumTimes; ++i) { server.Update(); client.Update(); if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress)) { didConnect = true; break; } } AZ_TEST_ASSERT(didConnect); char packet[] = { "Hello Server" }; bool didSendPacket = false; for (int i = 0; i < kNumTimes; ++i) { server.Update(); client.Update(); AZStd::intrusive_ptr<DriverAddress> from; char buffer[64]; AZ::u32 bytesRead = server.Receive(buffer, sizeof(buffer), from); if (bytesRead > 0) { AZ_TEST_ASSERT(bytesRead == sizeof(packet)); didSendPacket = memcmp(buffer, packet, sizeof(packet)) == 0; break; } AZ_TEST_ASSERT(client.Send(driveAddress, packet, sizeof(packet)) == GridMate::Driver::EC_OK); } AZ_TEST_ASSERT(didSendPacket); } }; class StreamSocketDriverTestsManyRandomPackets : public GridMateMPTestFixture { public: void run() { StreamSocketDriver server(2, 1024); server.Initialize(); server.StartListen(2); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); StreamSocketDriver client(1); client.Initialize(); auto socketAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName)); client.ConnectTo(socketAddress); bool didConnect = ConnectStreamSocketDriverServerClient(server, client, socketAddress, 100); AZ_TEST_ASSERT(didConnect); AZ::BetterPseudoRandom rand; using TestPacket = AZStd::vector<char>; using PacketQueue = AZStd::queue<TestPacket>; #define MAX_PACKET_SIZE 128 const auto fnCreatePayload = [&](char* buffer, int size) { uint32_t randKey; rand.GetRandom(randKey); size_t numChars = randKey % size; rand.GetRandom(buffer, numChars); return numChars; }; const auto fnReadAndCompare = [](PacketQueue& packetList, StreamSocketDriver& driver, AZStd::intrusive_ptr<DriverAddress>& from) { GridMate::Driver::ResultCode rc; char buffer[MAX_PACKET_SIZE]; AZ::u32 bytesRead = driver.Receive(buffer, sizeof(buffer), from, &rc); AZ_TEST_ASSERT(rc == GridMate::Driver::EC_OK); while (bytesRead > 0) { auto tester = packetList.front(); packetList.pop(); AZ_TEST_ASSERT(memcmp(&buffer[0], &tester[0], bytesRead) == 0); bytesRead = driver.Receive(buffer, sizeof(buffer), from, &rc); AZ_TEST_ASSERT(rc == GridMate::Driver::EC_OK); } }; PacketQueue toServerPacketList; PacketQueue toClientPacketList; AZStd::intrusive_ptr<DriverAddress> clientAddress; const int kNumTimes = 500; for (int i = 0; i < kNumTimes; ++i) { server.Update(); client.Update(); // do reads AZStd::intrusive_ptr<DriverAddress> from; fnReadAndCompare(toServerPacketList, server, clientAddress); fnReadAndCompare(toClientPacketList, client, from); // do write if (i == 0 || (i % 2) == 0) { char buffer[MAX_PACKET_SIZE]; size_t numToSend = fnCreatePayload(buffer, sizeof(buffer)); if (numToSend > 0) { TestPacket testPacket(&buffer[0], &buffer[numToSend]); toServerPacketList.push(testPacket); AZ_TEST_ASSERT(client.Send(socketAddress, &buffer[0], (AZ::u32)numToSend) == GridMate::Driver::EC_OK); } } else if (clientAddress && clientAddress->GetPort() > 0) { char buffer[MAX_PACKET_SIZE]; size_t numToSend = fnCreatePayload(buffer, sizeof(buffer)); if (numToSend > 0) { TestPacket testPacket(&buffer[0], &buffer[numToSend]); toClientPacketList.push(testPacket); AZ_TEST_ASSERT(server.Send(clientAddress, &buffer[0], (AZ::u32)numToSend) == GridMate::Driver::EC_OK); } } } #undef MAX_PACKET_SIZE } }; class Integ_StreamSocketDriverTestsTooManyConnections : public GridMateMPTestFixture { public: void run() { using ClientList = AZStd::vector<StreamSocketDriver*>; const auto fnUpdate = [](StreamSocketDriver& server, ClientList& clients) { server.Update(); for (auto& c : clients) { c->Update(); } }; const AZ::u32 maxConnections = 4; StreamSocketDriver server(maxConnections); server.Initialize(); server.StartListen(maxConnections + 1); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); ClientList clientList; const AZ::u32 tooManyConnections = 32; for (int i = 0; i < tooManyConnections; ++i) { auto c = aznew StreamSocketDriver(1); c->Initialize(); auto serverAddress = c->CreateDriverAddress(serverAddressName); if (c->ConnectTo(AZStd::static_pointer_cast<SocketDriverAddress>(serverAddress)) == GridMate::Driver::EC_OK) { clientList.emplace_back(c); } else { delete c; } fnUpdate(server, clientList); } const AZ::u32 nUpdates = 100; for (AZ::u32 i = 0; i < nUpdates; ++i) { fnUpdate(server, clientList); AZ_TEST_ASSERT(server.GetNumberOfConnections() <= maxConnections); } for (auto& c : clientList) { delete c; } } }; class StreamSocketDriverTestsClientToInvalidServer : public GridMateMPTestFixture { public: void run() { const auto fnUpdateDrivers = [](StreamSocketDriver& server, StreamSocketDriver& client, const AZ::u32 nCount) { for (AZ::u32 i = 0; i < nCount; ++i) { server.Update(); client.Update(); } }; StreamSocketDriver server(1); server.Initialize(); server.StartListen(1); auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); StreamSocketDriver client(1); client.Initialize(); auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName)); client.ConnectTo(serverAddress); bool wasConnected = false; const AZ::u32 kMaxTries = 10; for (AZ::u32 i = 0; i < kMaxTries; ++i) { fnUpdateDrivers(server, client, 20); if (client.IsConnectedTo(serverAddress)) { wasConnected = true; break; } } AZ_TEST_ASSERT(wasConnected); AZ_TEST_ASSERT(client.DisconnectFrom(serverAddress) == GridMate::Driver::EC_OK); for (AZ::u32 i = 0; i < kMaxTries; ++i) { // allow for graceful disconnect fnUpdateDrivers(server, client, 20); } AZ_TEST_ASSERT(client.IsConnectedTo(serverAddress) == false); // try to connect to a bogus server address auto bogusAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress("127.0.0.1|1")); // the attempt should succeed... AZ_TEST_ASSERT(client.ConnectTo(bogusAddress) == GridMate::Driver::EC_OK); //... but it should not go into 'connected mode' for (AZ::u32 i = 0; i < kMaxTries; ++i) { fnUpdateDrivers(server, client, 20); AZ_TEST_ASSERT(client.IsConnectedTo(bogusAddress) == false); } //... now reconnect to the server client.ConnectTo(serverAddress); wasConnected = false; for (AZ::u32 i = 0; i < kMaxTries; ++i) { fnUpdateDrivers(server, client, 20); if (client.IsConnectedTo(serverAddress)) { wasConnected = true; break; } } AZ_TEST_ASSERT(wasConnected); } }; class StreamSocketDriverTestsManySends : public GridMateMPTestFixture { public: void run() { StreamSocketDriver server(1); StreamSocketDriver client(1); bool isConnected = ConnectStreamSocketInitializeAndConnect(server, client, 100); AZ_TEST_ASSERT(isConnected); auto serverName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort()); auto serverAddr = client.CreateDriverAddress(serverName); AZ::BetterPseudoRandom rand; using TestPacket = AZStd::vector<char>; using PacketQueue = AZStd::queue<TestPacket>; const auto fnCreatePayload = [&](char* buffer, int size) { uint32_t randKey; rand.GetRandom(randKey); size_t numChars = (randKey % size) + 1; rand.GetRandom(buffer, numChars); return numChars; }; const AZ::u32 kManyPackets = 1024; const AZ::u32 kMaxPacketSize = 128; PacketQueue sentPackets; for (int i = 0; i < kManyPackets; ++i) { char buffer[kMaxPacketSize]; size_t numToSend = fnCreatePayload(buffer, sizeof(buffer)); TestPacket testPacket(&buffer[0], &buffer[numToSend]); if (client.Send(serverAddr, buffer, static_cast<AZ::u32>(numToSend)) == GridMate::Driver::EC_OK) { sentPackets.push(testPacket); } else { client.Update(); server.Update(); } } AZ::u32 numAttempts = 2000; GridMate::Driver::ResultCode resultCode; AZStd::intrusive_ptr<GridMate::DriverAddress> from; char buffer[kMaxPacketSize]; client.Update(); server.Update(); AZ::u32 numBytes = server.Receive(buffer, sizeof(buffer), from, &resultCode); while (!sentPackets.empty()) { AZ_TEST_ASSERT(numAttempts > 0); if (numAttempts == 0) { break; } --numAttempts; if (numBytes > 0) { auto tester = sentPackets.front(); sentPackets.pop(); auto nCompare = memcmp(&buffer[0], &tester[0], numBytes); if (nCompare != 0) { --numAttempts; } AZ_TEST_ASSERT(nCompare == 0); } client.Update(); server.Update(); numBytes = server.Receive(buffer, sizeof(buffer), from, &resultCode); } } }; } #if !AZ_TRAIT_GRIDMATE_UNIT_TEST_DISABLE_STREAM_SOCKET_DRIVER_TESTS GM_TEST_SUITE(StreamSocketDriverTests) GM_TEST(StreamSocketOperationTests); GM_TEST(StreamSocketDriverTestsCreateDelete); GM_TEST(StreamSocketDriverTestsBindSocketEmpty); GM_TEST(StreamSocketDriverTestsSimpleLockStepConnection); GM_TEST(StreamSocketDriverTestsEstablishConnectAndSend); GM_TEST(StreamSocketDriverTestsManyRandomPackets); GM_TEST(Integ_StreamSocketDriverTestsTooManyConnections); GM_TEST(StreamSocketDriverTestsClientToInvalidServer); GM_TEST(StreamSocketDriverTestsManySends); GM_TEST_SUITE_END() #endif // !AZ_TRAIT_GRIDMATE_UNIT_TEST_DISABLE_STREAM_SOCKET_DRIVER_TESTS
20,758
5,915
/* A simple wrapper to suppress all warnings from gtest.h */ #pragma GCC system_header #include "gtest/gtest.h"
112
36
/* cpu_x86.cpp * * Author : Alexander J. Yee * Date Created : 04/12/2014 * Last Modified : 04/12/2014 * */ // Dependencies #include <iostream> #include <cstring> #if _WIN32 #include <Windows.h> #include <intrin.h> #else #include <cpuid.h> #endif #include "neo_ica/backend/cpu_x86.h" namespace neo_ica { /* * --------------------- * WINDOWS CPUID * -------------------- */ #if _WIN32 void cpu_x86::cpuid(int32_t out[4], int32_t x){ __cpuidex(out, x, 0); } __int64 xgetbv(unsigned int x){ return _xgetbv(x); } // Detect 64-bit - Note that this snippet of code for detecting 64-bit has been copied from MSDN. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); BOOL IsWow64() { BOOL bIsWow64 = FALSE; LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress( GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { printf("Error Detecting Operating System.\n"); printf("Defaulting to 32-bit OS.\n\n"); bIsWow64 = FALSE; } } return bIsWow64; } bool cpu_x86::detect_OS_x64(){ #ifdef _M_X64 return true; #else return IsWow64() != 0; #endif } #elif (defined __linux) && (defined __GNUC__) /* * --------------------- * LINUX CPUID * -------------------- */ void cpu_x86::cpuid(int32_t out[4], int32_t x){ __cpuid_count(x, 0, out[0], out[1], out[2], out[3]); } uint64_t xgetbv(unsigned int index){ uint32_t eax, edx; __asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); return ((uint64_t)edx << 32) | eax; } #define _XCR_XFEATURE_ENABLED_MASK 0 // Detect 64-bit bool cpu_x86::detect_OS_x64(){ // We only support x64 on Linux. return true; } #else #error "No cpuid intrinsic defined." #endif bool cpu_x86::detect_OS_AVX(){ // Copied from: http://stackoverflow.com/a/22521619/922184 bool avxSupported = false; int cpuInfo[4]; cpuid(cpuInfo, 1); bool osUsesXSAVE_XrhoTORE = (cpuInfo[2] & (1 << 27)) != 0; bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0; if (osUsesXSAVE_XrhoTORE && cpuAVXSuport) { uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); avxSupported = (xcrFeatureMask & 0x6) == 0x6; } return avxSupported; } bool cpu_x86::detect_OS_AVX512(){ if (!detect_OS_AVX()) return false; uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); return (xcrFeatureMask & 0xe6) == 0xe6; } void cpu_x86::detect_host(){ // OS Features OS_x64 = detect_OS_x64(); OS_AVX = detect_OS_AVX(); OS_AVX512 = detect_OS_AVX512(); // Vendor std::string vendor(get_vendor_string()); if (vendor == "GenuineIntel"){ Vendor_Intel = true; }else if (vendor == "AuthenticAMD"){ Vendor_AMD = true; } int info[4]; cpuid(info, 0); int nIds = info[0]; cpuid(info, 0x80000000); uint32_t nExIds = info[0]; // Detect Features if (nIds >= 0x00000001){ cpuid(info, 0x00000001); HW_MMX = (info[3] & ((int)1 << 23)) != 0; HW_SSE = (info[3] & ((int)1 << 25)) != 0; HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; HW_AES = (info[2] & ((int)1 << 25)) != 0; HW_AVX = (info[2] & ((int)1 << 28)) != 0; HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; } if (nIds >= 0x00000007){ cpuid(info, 0x00000007); HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; HW_ADX = (info[1] & ((int)1 << 19)) != 0; HW_MPX = (info[1] & ((int)1 << 14)) != 0; HW_SHA = (info[1] & ((int)1 << 29)) != 0; HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0; HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0; HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0; HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0; HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0; HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0; HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0; HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0; HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0; } if (nExIds >= 0x80000001){ cpuid(info, 0x80000001); HW_x64 = (info[3] & ((int)1 << 29)) != 0; HW_ABM = (info[2] & ((int)1 << 5)) != 0; HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; HW_XOP = (info[2] & ((int)1 << 11)) != 0; } } cpu_x86::cpu_x86(){ detect_host(); } std::string cpu_x86::get_vendor_string(){ int32_t CPUInfo[4]; char name[13]; cpuid(CPUInfo, 0); memcpy(name + 0, &CPUInfo[1], 4); memcpy(name + 4, &CPUInfo[3], 4); memcpy(name + 8, &CPUInfo[2], 4); name[12] = '\0'; return name; } }
5,391
2,615
// QTSimpleDemo // // Copyright © 2020 tencent. All rights reserved. // #include "VideoListView.h" #include "ui_VideoListView.h" #include <QtDebug> #include "ui_TestVideoSetting.h" #ifdef __APPLE__ #include "GenerateTestUserSig.h" #endif #ifdef _WIN32 #include "GenerateTestUsersig.h" #endif VideoListView::VideoListView(QWidget *parent) : QDialog(parent), ui(new Ui::VideoListView) { ui->setupUi(this); m_trtcCloud = getTRTCShareInstance(); if (m_trtcCloud == nullptr) return; m_trtcCloud->addCallback(this); setupList(); updateVideoViews(true); } VideoListView::~VideoListView() { reset(); delete ui; if (m_trtcCloud != nullptr) { m_trtcCloud->removeCallback(this); m_trtcCloud = nullptr; } } QWidget *VideoListView::getLocalView() { if (m_videoViews.count() > 0) { return m_videoViews.at(0); } return nullptr; } void VideoListView::enterRoom(const trtc::TRTCParams& params, trtc::TRTCAppScene scene) { m_userId = QString(params.userId); m_trtcCloud->setDefaultStreamRecvMode(true, true); m_trtcCloud->enableAudioVolumeEvaluation(300); m_trtcCloud->enterRoom(params, scene); m_trtcCloud->startLocalAudio(trtc::TRTCAudioQualityDefault); // 真实开发中可根据不同场景灵活调用 m_trtcCloud->startLocalPreview(reinterpret_cast<trtc::TXView>(ui->videoView0->winId())); m_trtcCloud->setBeautyStyle(trtc::TRTCBeautyStyleSmooth, 6, 6, 6); } void VideoListView::updateRoomMembers() { bool isEmpty = m_roomMembers.count() == 0; ui->switchAllRemoteVideo->setEnabled(isEmpty == false); ui->switchAllRemoteAudio->setEnabled(isEmpty == false); if (isEmpty) { ui->memberLabel->setText(QString::fromLocal8Bit("暂无成员~").toUtf8()); return; } QString memberIds = QString::fromLocal8Bit("成员列表: "); for (int i = 0; i < m_roomMembers.count(); i++) { memberIds = memberIds + m_roomMembers.at(i) + (i == m_roomMembers.count() - 1 ? "" : ", "); } QByteArray mids = memberIds.toUtf8(); ui->memberLabel->setText(mids); } void VideoListView::reset() { updateVideoViews(true); updateRoomMembers(); ui->switchAllRemoteVideo->setEnabled(false); ui->switchAllRemoteAudio->setEnabled(false); ui->switchDashBoardButton->setEnabled(false); } void VideoListView::updateVideoViews(bool hidden) { std::lock_guard<std::mutex> lk(m_remoteVideoViewsMutex); for (int i = 0; i < m_videoViews.count(); i++) { QWidget *videoView = m_videoViews[i]; videoView->setHidden(hidden); QProgressBar *progressBar = m_progressBars[i]; progressBar->setHidden(hidden); QPushButton *audio = m_audios[i]; audio->setHidden(hidden); QPushButton *video = m_videos[i]; video->setHidden(hidden); updateButtonState(audio, false, Audio, progressBar); updateButtonState(video, false, Video); } #ifdef _WIN32 // fix the white border issue for win-system if (m_videoViews.count() < 1) return; QPalette pal; pal.setColor(QPalette::Background, Qt::black); m_videoViews[0]->setAutoFillBackground(true); m_videoViews[0]->setPalette(pal); #endif } void VideoListView::onEnterRoom(int result) { if (result > 0) { // 进房成功 ui->videoView0->setHidden(false); ui->video0->setHidden(false); ui->audio0->setHidden(false); ui->progressBar0->setHidden(false); m_userIds.push_back(m_userId); ui->switchDashBoardButton->setEnabled(true); } else { // 进房失败 QString errorTip(QString::fromLocal8Bit("进房失败,错误码:").toUtf8()); errorTip.append(QString::number(result)); errorTip.append(QString::fromLocal8Bit("\n请您检查房间号、用户ID等输入是否合法\n或您可尝试重新输入房间号、用户ID").toUtf8()); std::string msg = errorTip.toStdString(); m_alertDialog.showMessageTip(msg.c_str()); } } void VideoListView::onExitRoom(int reason) { ui->videoView0->setHidden(true); m_roomMembers.clear(); m_userIds.clear(); reset(); } void VideoListView::onRemoteUserEnterRoom(const char *userId) { m_roomMembers.push_back(QString(userId)); updateRoomMembers(); } void VideoListView::onRemoteUserLeaveRoom(const char *userId, int reason) { m_roomMembers.remove(m_roomMembers.indexOf(QString(userId))); updateRoomMembers(); } void VideoListView::onUserVoiceVolume(trtc::TRTCVolumeInfo* userVolumes, uint32_t userVolumesCount, uint32_t totalVolume) { if (userVolumes == nullptr) return; int volume = (int)userVolumes->volume; if (strlen(userVolumes->userId) < 1) { // 自己在说话 ui->progressBar0->setValue(volume); } else { QString uid = QString(userVolumes->userId); int index = m_userIds.indexOf(uid); if (index > 0 && index < m_progressBars.count() - 1) { m_progressBars[index]->setValue(volume); } } } void VideoListView::onUserVideoAvailable(const char *userId, bool available) { int index = m_userIds.indexOf(QString(userId)); if (available) { if (index < 0) { m_userIds.push_back(QString(userId)); refreshRemoteVideoViews(m_userIds.count() - 1); ui->switchAllRemoteAudio->setChecked(false); ui->switchAllRemoteVideo->setChecked(false); } else { // 因为第0个永远是本地画面,所以从1开始refresh refreshRemoteVideoViews(1); } } else { m_trtcCloud->stopRemoteView(userId, trtc::TRTCVideoStreamTypeSmall); m_userIds.remove(index); refreshRemoteVideoViews(index); } } void VideoListView::refreshRemoteVideoViews(int from) { for (int i = from; i < m_videoViews.count(); i++) { bool needUpdate = i < m_userIds.count(); if (needUpdate) { std::string str = m_userIds.at(i).toStdString(); m_trtcCloud->startRemoteView(str.c_str(), trtc::TRTCVideoStreamTypeSmall, reinterpret_cast<trtc::TXView>(m_videoViews[i]->winId())); on_switchAllRemoteAudio_clicked(false); on_switchAllRemoteVideo_clicked(false); } m_audios.at(i)->setHidden(!needUpdate); m_videos.at(i)->setHidden(!needUpdate); m_videoViews.at(i)->setHidden(!needUpdate); m_progressBars.at(i)->setHidden(!needUpdate); } } void VideoListView::onUserSubStreamAvailable(const char *userId, bool available) { if (available) { m_trtcCloud->startRemoteView(userId, trtc::TRTCVideoStreamTypeSub, (trtc::TXView)(ui->screenCaptureView->winId())); } else { m_trtcCloud->stopRemoteView(userId, trtc::TRTCVideoStreamTypeSub); } } void VideoListView::on_switchAllRemoteVideo_clicked(bool checked) { m_trtcCloud->muteAllRemoteVideoStreams(checked); for (int i = 1; i < m_videos.count(); i++) { updateButtonState(m_videos[i], checked, Video); } } void VideoListView::on_switchAllRemoteAudio_clicked(bool checked) { m_trtcCloud->muteAllRemoteAudio(checked); for (int i = 1; i < m_audios.count(); i++) { updateButtonState(m_audios[i], checked, Audio, m_progressBars[i]); } } /** * 简单起见,本Demo中下述 audio & video 的相关控制事件定义的比较激进粗糙,真实开发中应考虑封装优化 * */ void VideoListView::on_audio0_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 1) return; if (flag) ui->audio0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_close.png);}"); else ui->audio0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_normal.png);}"); if (flag == false) { if (m_progressBars[0] != nullptr) m_progressBars[0]->setValue(0); } m_trtcCloud->muteLocalAudio(flag); } void VideoListView::on_video0_clicked() { static bool flag = false; flag = !flag; if (flag) ui->video0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_close.png);}"); else ui->video0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_normal.png);}"); m_trtcCloud->muteLocalVideo(flag); } void VideoListView::on_audio1_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 2) return; updateButtonState(ui->audio1, flag, Audio, m_progressBars[1]); muteRemoteStream(Audio, flag, 1); } void VideoListView::on_video1_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video1, flag, Video); muteRemoteStream(Video, flag, 1); } void VideoListView::on_audio2_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 3) return; updateButtonState(ui->audio2, flag, Audio, m_progressBars[2]); muteRemoteStream(Audio, flag, 2); } void VideoListView::on_video2_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video2, flag, Video); muteRemoteStream(Video, flag, 2); } void VideoListView::on_audio3_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 4) return; updateButtonState(ui->audio3, flag, Audio, m_progressBars[3]); muteRemoteStream(Audio, flag, 3); } void VideoListView::on_video3_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video3, flag, Video); muteRemoteStream(Video, flag, 3); } void VideoListView::on_audio4_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 5) return; updateButtonState(ui->audio4, flag, Audio, m_progressBars[4]); muteRemoteStream(Audio, flag, 4); } void VideoListView::on_video4_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video4, flag, Video); muteRemoteStream(Video, flag, 4); } void VideoListView::on_audio5_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 6) return; updateButtonState(ui->audio5, flag, Audio, m_progressBars[5]); muteRemoteStream(Audio, flag, 5); } void VideoListView::on_video5_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video5, flag, Video); muteRemoteStream(Video, flag, 5); } void VideoListView::on_audio6_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 7) return; updateButtonState(ui->audio6, flag, Audio, m_progressBars[6]); muteRemoteStream(Audio, flag, 6); } void VideoListView::on_video6_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video6, flag, Video); muteRemoteStream(Video, flag, 6); } void VideoListView::on_audio7_clicked() { static bool flag = false; flag = !flag; if (m_progressBars.count() < 8) return; updateButtonState(ui->audio7, flag, Audio, m_progressBars[7]); muteRemoteStream(Audio, flag, 7); } void VideoListView::on_video7_clicked() { static bool flag = false; flag = !flag; updateButtonState(ui->video7, flag, Video); muteRemoteStream(Video, flag, 7); } void VideoListView::muteRemoteStream(ControlButtonType type, bool mute, int index) { if (index < 0 || index > m_userIds.count() - 1) return; if (type == Audio) { std::string uid = m_userIds.at(index).toStdString(); m_trtcCloud->muteRemoteAudio(uid.c_str(), mute); } else if (type == Video) { std::string uid = m_userIds.at(index).toStdString(); m_trtcCloud->muteRemoteVideoStream(uid.c_str(), mute); } } void VideoListView::updateButtonState(QPushButton *button, bool state, ControlButtonType type, QProgressBar *progressBar) { if (type == Audio) { if (state) button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_close.png);}"); else button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_normal.png);}"); if (state == false) { ui->switchAllRemoteAudio->setChecked(false); if (progressBar != nullptr) progressBar->setValue(0); } } else if (type == Video) { if (state) button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_close.png);}"); else button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_normal.png);}"); if (state == false) ui->switchAllRemoteVideo->setChecked(false); } } void VideoListView::on_switchDashBoardButton_clicked(bool checked) { m_trtcCloud->showDebugView(checked ? 2 : 0); // 0不显示信息,1显示简略信息,2显示详细信息 } void VideoListView::setupList() { // 目前最多支持 8 个画面的布局 m_videoViews.push_back(ui->videoView0); m_videoViews.push_back(ui->videoView1); m_videoViews.push_back(ui->videoView2); m_videoViews.push_back(ui->videoView3); m_videoViews.push_back(ui->videoView4); m_videoViews.push_back(ui->videoView5); m_videoViews.push_back(ui->videoView6); m_videoViews.push_back(ui->videoView7); m_progressBars.push_back(ui->progressBar0); m_progressBars.push_back(ui->progressBar1); m_progressBars.push_back(ui->progressBar2); m_progressBars.push_back(ui->progressBar3); m_progressBars.push_back(ui->progressBar4); m_progressBars.push_back(ui->progressBar5); m_progressBars.push_back(ui->progressBar6); m_progressBars.push_back(ui->progressBar7); m_audios.push_back(ui->audio0); m_audios.push_back(ui->audio1); m_audios.push_back(ui->audio2); m_audios.push_back(ui->audio3); m_audios.push_back(ui->audio4); m_audios.push_back(ui->audio5); m_audios.push_back(ui->audio6); m_audios.push_back(ui->audio7); m_videos.push_back(ui->video0); m_videos.push_back(ui->video1); m_videos.push_back(ui->video2); m_videos.push_back(ui->video3); m_videos.push_back(ui->video4); m_videos.push_back(ui->video5); m_videos.push_back(ui->video6); m_videos.push_back(ui->video7); for (int i = 0; i < m_videoViews.count(); i++) { QWidget *videoView = m_videoViews.at(i); if (videoView != nullptr) videoView->setAttribute(Qt::WA_PaintOnScreen, true); } } QPaintEngine *VideoListView::paintEngine() const { return nullptr; } void VideoListView::onError(TXLiteAVError errCode, const char *errMsg, void *extraInfo) { qDebug() << "errCode: " << errCode << " errMsg: " << errMsg << " extraInfo: " << extraInfo; } void VideoListView::onWarning(TXLiteAVWarning warningCode, const char *warningMsg, void *extraInfo) { qDebug() << "warningCode: " << warningCode << " warningMsg: " << warningMsg << " extraInfo: " << extraInfo; }
14,451
5,158
// fastjet stuff #include "fastjet/ClusterSequence.hh" #include "fastjet/SISConePlugin.hh" // sisocne stuff #include "siscone/momentum.h" #include "siscone/siscone.h" // other stuff #include<sstream> FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh using namespace std; using namespace siscone; /// shortcut for converting siscone Cmomentum into PseudoJet template<> PseudoJet::PseudoJet(const siscone::Cmomentum & four_vector) { (*this) = PseudoJet(four_vector.px,four_vector.py,four_vector.pz, four_vector.E); } ///////////////////////////////////////////// // static members declaration // ///////////////////////////////////////////// std::auto_ptr<SISConePlugin> SISConePlugin::stored_plugin; std::auto_ptr<std::vector<PseudoJet> > SISConePlugin::stored_particles; std::auto_ptr<Csiscone> SISConePlugin::stored_siscone; ///////////////////////////////////////////// // now comes the implementation itself // ///////////////////////////////////////////// string SISConePlugin::description () const { ostringstream desc; const string on = "on"; const string off = "off"; string sm_scale_string = "split-merge uses " + split_merge_scale_name(Esplit_merge_scale(split_merge_scale())); desc << "SISCone jet algorithm with " ; desc << "cone_radius = " << cone_radius () << ", "; desc << "overlap_threshold = " << overlap_threshold () << ", "; desc << "n_pass_max = " << n_pass_max () << ", "; desc << "protojet_ptmin = " << protojet_ptmin() << ", "; desc << sm_scale_string << ", "; desc << "caching turned " << (caching() ? on : off); desc << ", SM stop scale = " << _split_merge_stopping_scale; // add a note to the description if we use the pt-weighted splitting if (_use_pt_weighted_splitting){ desc << ", using pt-weighted splitting"; } if (_use_jet_def_recombiner){ desc << ", using jet-definition's own recombiner"; } // create a fake siscone object so that we can find out more about it Csiscone siscone; if (siscone.merge_identical_protocones) { desc << ", and (IR unsafe) merge_indentical_protocones=true" ; } desc << ", SISCone code v" << siscone_version(); return desc.str(); } // overloading the base class implementation void SISConePlugin::run_clustering(ClusterSequence & clust_seq) const { Csiscone local_siscone; Csiscone * siscone; unsigned n = clust_seq.jets().size(); bool new_siscone = true; // by default we'll be running it if (caching()) { // Establish if we have a cached run with the same R, npass and // particles. If not then do any tidying up / reallocation that's // necessary for the next round of caching, otherwise just set // relevant pointers so that we can reuse and old run. if (stored_siscone.get() != 0) { new_siscone = !(stored_plugin->cone_radius() == cone_radius() && stored_plugin->n_pass_max() == n_pass_max() && stored_particles->size() == n); if (!new_siscone) { for(unsigned i = 0; i < n; i++) { // only check momentum because indices will be correctly dealt // with anyway when extracting the clustering order. new_siscone |= !have_same_momentum(clust_seq.jets()[i], (*stored_particles)[i]); } } } // allocate the new siscone, etc., if need be if (new_siscone) { stored_siscone .reset( new Csiscone ); stored_particles.reset( new std::vector<PseudoJet>(clust_seq.jets())); reset_stored_plugin(); } siscone = stored_siscone.get(); } else { siscone = &local_siscone; } // make sure stopping scale is set in siscone siscone->SM_var2_hardest_cut_off = _split_merge_stopping_scale*_split_merge_stopping_scale; // set the specific parameters // when running with ghosts for passive areas, do not put the // ghosts into the stable-cone search (not relevant) siscone->stable_cone_soft_pt2_cutoff = ghost_separation_scale() * ghost_separation_scale(); // set the type of splitting we want (default=std one, true->pt-weighted split) siscone->set_pt_weighted_splitting(_use_pt_weighted_splitting); if (new_siscone) { // transfer fastjet initial particles into the siscone type std::vector<Cmomentum> siscone_momenta(n); for(unsigned i = 0; i < n; i++) { const PseudoJet & p = clust_seq.jets()[i]; // shorthand siscone_momenta[i] = Cmomentum(p.px(), p.py(), p.pz(), p.E()); } // run the jet finding //cout << "plg sms: " << split_merge_scale() << endl; siscone->compute_jets(siscone_momenta, cone_radius(), overlap_threshold(), n_pass_max(), protojet_or_ghost_ptmin(), Esplit_merge_scale(split_merge_scale())); } else { // rerun the jet finding // just run the overlap part of the jets. //cout << "plg rcmp sms: " << split_merge_scale() << endl; siscone->recompute_jets(overlap_threshold(), protojet_or_ghost_ptmin(), Esplit_merge_scale(split_merge_scale())); } // extract the jets [in reverse order -- to get nice ordering in pt at end] int njet = siscone->jets.size(); // allocate space for the extras object SISConeExtras * extras = new SISConeExtras(n); for (int ijet = njet-1; ijet >= 0; ijet--) { const Cjet & jet = siscone->jets[ijet]; // shorthand // Successively merge the particles that make up the cone jet // until we have all particles in it. Start off with the zeroth // particle. int jet_k = jet.contents[0]; for (unsigned ipart = 1; ipart < jet.contents.size(); ipart++) { // take the last result of the merge int jet_i = jet_k; // and the next element of the jet int jet_j = jet.contents[ipart]; // and merge them (with a fake dij) double dij = 0.0; if (_use_jet_def_recombiner) { clust_seq.plugin_record_ij_recombination(jet_i, jet_j, dij, jet_k); } else { // create the new jet by hand so that we can adjust its user index PseudoJet newjet = clust_seq.jets()[jet_i] + clust_seq.jets()[jet_j]; // set the user index to be the pass in which the jet was discovered newjet.set_user_index(jet.pass); clust_seq.plugin_record_ij_recombination(jet_i, jet_j, dij, newjet, jet_k); } } // we have merged all the jet's particles into a single object, so now // "declare" it to be a beam (inclusive) jet. // [NB: put a sensible looking d_iB just to be nice...] double d_iB = clust_seq.jets()[jet_k].perp2(); clust_seq.plugin_record_iB_recombination(jet_k, d_iB); // now record the pass of the jet in the extras object extras->_pass[clust_seq.jets()[jet_k].cluster_hist_index()] = jet.pass; } // now copy the list of protocones into an "extras" objects for (unsigned ipass = 0; ipass < siscone->protocones_list.size(); ipass++) { for (unsigned ipc = 0; ipc < siscone->protocones_list[ipass].size(); ipc++) { PseudoJet protocone(siscone->protocones_list[ipass][ipc]); protocone.set_user_index(ipass); extras->_protocones.push_back(protocone); } } extras->_most_ambiguous_split = siscone->most_ambiguous_split; // tell it what the jet definition was extras->_jet_def_plugin = this; // give the extras object to the cluster sequence. clust_seq.plugin_associate_extras(std::auto_ptr<ClusterSequence::Extras>(extras)); } void SISConePlugin::reset_stored_plugin() const{ stored_plugin.reset( new SISConePlugin(*this)); } FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh
7,763
2,693
//********************************************************* // AB_Data.cpp - network link A->B access classes //********************************************************* #include "AB_Data.hpp" //--------------------------------------------------------- // AB_Key constructor //--------------------------------------------------------- AB_Key::AB_Key (int max_records) : Complex_Array (sizeof (AB_Data), 2, false, max_records, false) { }
441
110
// Copyright 2020 VMware, Inc. // SPDX-License-Identifier: Apache-2.0 // #include "herald/datatype/signal_characteristic_data.h" #include "herald/ble/ble_sensor_configuration.h" #include <vector> #include <optional> namespace herald { namespace datatype { namespace SignalCharacteristicData { using namespace herald::ble; // PRIVATE METHODS std::byte signalDataActionCode(const Data& signalData) { if (signalData.size() == 0) { return std::byte(0); } return signalData.at(0); } int int16(const Data& data, std::size_t index, bool& success) { if (index < data.size() - 1) { // TODO TEST size() boundary limits - as it's two bytes, little endian int v = (((int)data.at(index)) << 8) | (int)data.at(index + 1); success = true; return v; } success = false; return 0; } // HEADER PUBLIC METHODS std::optional<Data> encodeWriteRssi(const BLESensorConfiguration& config,const RSSI& rssi) noexcept { int r = rssi.intValue(); std::vector<std::byte> vec(3); vec.push_back(config.signalCharacteristicActionWriteRSSI); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb return std::optional<Data>(Data(std::move(vec))); // constructs the optional with a value } std::optional<RSSI> decodeWriteRSSI(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWriteRSSI) { return {}; } if (data.size() != 3) { return {}; } bool success = true; int rssi = int16(data,1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } return std::optional<RSSI>(RSSI{rssi}); // constructs the optional with a value } std::optional<Data> encodeWritePayload(const BLESensorConfiguration& config,const PayloadData& payloadData) noexcept { int r = (int)payloadData.size(); std::vector<std::byte> vec(3 + r); vec.push_back(config.signalCharacteristicActionWritePayload); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb Data d(std::move(vec)); d.append(payloadData); return std::optional<Data>(d); // constructs the optional with a value } std::optional<PayloadData> decodeWritePayload(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayload) { return {}; } if (data.size() < 3) { return {}; } bool success = true; int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } if (data.size() != (3 + std::size_t(payloadDataCount))) { return {}; } return std::optional<PayloadData>(PayloadData(data.subdata(3))); // constructs the optional with a value } std::optional<Data> encodeWritePayloadSharing(const BLESensorConfiguration& config,const PayloadSharingData& payloadSharingData) noexcept { int r = payloadSharingData.rssi.intValue(); int r2 = (int)payloadSharingData.data.size(); std::vector<std::byte> vec(5 + r2); vec.push_back(config.signalCharacteristicActionWritePayloadSharing); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb vec.push_back(std::byte(r2)); // force least significant bit vec.push_back(std::byte(r2 >> 8)); // msb Data d(std::move(vec)); d.append(payloadSharingData.data); return std::optional<Data>(d); // constructs the optional with a value } std::optional<PayloadSharingData> decodeWritePayloadSharing(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayloadSharing) { return {}; } if (data.size() < 5) { return {}; } bool success = true; int rssiValue = int16(data, 1, success); if (!success) { return {}; } int payloadDataCount = int16(data, 3, success); // idx 3 & 4 (little endian) if (!success) { return {}; } if (data.size() != (5 + std::size_t(payloadDataCount))) { return {}; } Data d = data.subdata(5); RSSI rssi(rssiValue); PayloadSharingData pd{std::move(rssi), std::move(data)}; return std::optional<PayloadSharingData>(pd); // constructs the optional with a value } std::optional<Data> encodeImmediateSend(const BLESensorConfiguration& config,const ImmediateSendData& immediateSendData) noexcept { int r = (int)immediateSendData.size(); std::vector<std::byte> vec(3 + r); vec.push_back(config.signalCharacteristicActionWriteImmediate); vec.push_back(static_cast<std::byte>(r)); // force least significant bit vec.push_back(static_cast<std::byte>(r >> 8)); // msb Data d(std::move(vec)); d.append(immediateSendData); return std::optional<Data>(d); // constructs the optional with a value } std::optional<ImmediateSendData> decodeImmediateSend(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWriteImmediate) { return {}; } if (data.size() < 3) { return {}; } bool success = true; int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } if (data.size() != (3 + std::size_t(payloadDataCount))) { return {}; } return std::optional<ImmediateSendData>(ImmediateSendData(data.subdata(3))); // constructs the optional with a value } SignalCharacteristicDataType detect(const BLESensorConfiguration& config,const Data& data) noexcept { auto val = signalDataActionCode(data); if (config.signalCharacteristicActionWriteRSSI == val) { return SignalCharacteristicDataType::rssi; } else if (config.signalCharacteristicActionWritePayload == val) { return SignalCharacteristicDataType::payload; } else if (config.signalCharacteristicActionWritePayloadSharing == val) { return SignalCharacteristicDataType::payloadSharing; } else if (config.signalCharacteristicActionWriteImmediate == val) { return SignalCharacteristicDataType::immediateSend; } else { return SignalCharacteristicDataType::unknown; } } } // end namespace } // end namespace } // end namespace
6,352
2,142
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <EMotionFX/Source/EventHandler.h> #include <Editor/PropertyWidgets/AnimGraphParameterMaskHandler.h> #include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h> #include <QHBoxLayout> #include <QMessageBox> #include <QTimer> namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(AnimGraphParameterMaskHandler, EditorAllocator, 0) AnimGraphParameterMaskHandler::AnimGraphParameterMaskHandler() : QObject() , AzToolsFramework::PropertyHandler<AZStd::vector<AZStd::string>, AnimGraphParameterPicker>() , m_object(nullptr) { } AZ::u32 AnimGraphParameterMaskHandler::GetHandlerName() const { return AZ_CRC("AnimGraphParameterMask", 0x67dd0993); } QWidget* AnimGraphParameterMaskHandler::CreateGUI(QWidget* parent) { AnimGraphParameterPicker* picker = aznew AnimGraphParameterPicker(parent, false, true); connect(picker, &AnimGraphParameterPicker::ParametersChanged, this, [picker](const AZStd::vector<AZStd::string>& newParameters) { EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, picker); }); return picker; } void AnimGraphParameterMaskHandler::ConsumeAttribute(AnimGraphParameterPicker* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName) { if (attrValue) { AnimGraphNode* node = static_cast<AnimGraphNode*>(attrValue->GetInstancePointer()); m_object = azdynamic_cast<ObjectAffectedByParameterChanges*>(node); GUI->SetObjectAffectedByParameterChanges(m_object); } if (attrib == AZ::Edit::Attributes::ReadOnly) { bool value; if (attrValue->Read<bool>(value)) { GUI->setEnabled(!value); } } } void AnimGraphParameterMaskHandler::WriteGUIValuesIntoProperty(size_t index, AnimGraphParameterPicker* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* node) { // Don't update the parameter names yet, we still need the information for constructing the command group. instance = m_object->GetParameters(); } bool AnimGraphParameterMaskHandler::ReadValuesIntoGUI(size_t index, AnimGraphParameterPicker* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node) { QSignalBlocker signalBlocker(GUI); GUI->InitializeParameterNames(instance); return true; } } // namespace EMotionFX
3,106
894
#include <iostream> #include <cstdio> #include <string> #include <sstream> #include <fstream> #include <cmath> #include <valarray> #include <complex> #include <cufft.h> #include <cufftXt.h> #include <thrust/complex.h> #include <gtest/gtest.h> #include "isce3/signal/Signal.h" #include "isce3/io/Raster.h" #include "isce3/cuda/except/Error.h" #include "isce3/cuda/signal/gpuSignal.h" using isce3::cuda::signal::gpuSignal; TEST(gpuSignal, ForwardBackwardRangeFloat) { // take a block of data, perform range FFT and then iverse FFT and compare with original data isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt"); int width = inputSlc.width(); int blockLength = inputSlc.length(); thrust::complex<float> *d_data; // reserve memory for a block of data std::valarray<std::complex<float>> data(width*blockLength); // reserve memory for a block of data computed from inverse FFT std::valarray<std::complex<float>> inverted_data(width*blockLength); // read a block of data inputSlc.getBlock(data, 0, 0, width, blockLength); // copy data to device size_t data_sz = width * blockLength * sizeof(thrust::complex<float>); checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz)); checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice)); // a signal object gpuSignal<float> sig(CUFFT_C2C); // create the plan sig.rangeFFT(width, blockLength); sig.forwardDevMem(d_data); sig.inverseDevMem(d_data); cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost); //normalize the result of inverse fft inverted_data /=width; int blockSize = width*blockLength; std::complex<float> err(0.0, 0.0); double max_err = 0.0; for ( size_t i = 0; i < blockSize; ++i ) { err = inverted_data[i] - data[i]; if (std::abs(err) > max_err){ max_err = std::abs(err); } } ASSERT_LT(max_err, 1.0e-4); } TEST(gpuSignal, ForwardBackwardRangeDouble) { // take a block of data, perform range FFT and then iverse FFT and compare with original data isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt"); int width = inputSlc.width(); int blockLength = inputSlc.length(); thrust::complex<double> *d_data; // reserve memory for a block of data std::valarray<std::complex<double>> data(width*blockLength); // reserve memory for a block of data computed from inverse FFT std::valarray<std::complex<double>> inverted_data(width*blockLength); // read a block of data inputSlc.getBlock(data, 0, 0, width, blockLength); // copy data to device size_t data_sz = width * blockLength * sizeof(thrust::complex<double>); checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz)); checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice)); // a signal object gpuSignal<double> sig(CUFFT_Z2Z); // create the plan sig.rangeFFT(width, blockLength); sig.forwardDevMem(d_data); sig.inverseDevMem(d_data); cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost); //normalize the result of inverse fft inverted_data /=width; int blockSize = width*blockLength; std::complex<double> err(0.0, 0.0); double max_err = 0.0; for ( size_t i = 0; i < blockSize; ++i ) { err = inverted_data[i] - data[i]; if (std::abs(err) > max_err){ max_err = std::abs(err); } } ASSERT_LT(max_err, 1.0e-4); } TEST(gpuSignal, ForwardBackwardAzimuthFloat) { // take a block of data, perform range FFT and then iverse FFT and compare with original data isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt"); int width = inputSlc.width(); int blockLength = inputSlc.length(); thrust::complex<float> *d_data; // reserve memory for a block of data std::valarray<std::complex<float>> data(width*blockLength); // reserve memory for a block of data computed from inverse FFT std::valarray<std::complex<float>> inverted_data(width*blockLength); // read a block of data inputSlc.getBlock(data, 0, 0, width, blockLength); // copy data to device size_t data_sz = width * blockLength * sizeof(thrust::complex<float>); checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz)); checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice)); // a signal object gpuSignal<float> sig(CUFFT_C2C); // create the plan sig.azimuthFFT(width, blockLength); sig.forwardDevMem(d_data); sig.inverseDevMem(d_data); cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost); //normalize the result of inverse fft inverted_data /=width; int blockSize = width*blockLength; std::complex<float> err(0.0, 0.0); double max_err = 0.0; for ( size_t i = 0; i < blockSize; ++i ) { err = inverted_data[i] - data[i]; if (std::abs(err) > max_err){ max_err = std::abs(err); } } ASSERT_LT(max_err, 1.0e-4); } TEST(gpuSignal, ForwardBackwardAzimuthDouble) { // take a block of data, perform range FFT and then iverse FFT and compare with original data isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt"); int width = inputSlc.width(); int blockLength = inputSlc.length(); thrust::complex<double> *d_data; // reserve memory for a block of data std::valarray<std::complex<double>> data(width*blockLength); // reserve memory for a block of data computed from inverse FFT std::valarray<std::complex<double>> inverted_data(width*blockLength); // read a block of data inputSlc.getBlock(data, 0, 0, width, blockLength); // copy data to device size_t data_sz = width * blockLength * sizeof(thrust::complex<double>); checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz)); checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice)); // a signal object gpuSignal<double> sig(CUFFT_Z2Z); // create the plan sig.azimuthFFT(width, blockLength); sig.forwardDevMem(d_data); sig.inverseDevMem(d_data); cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost); //normalize the result of inverse fft inverted_data /=width; int blockSize = width*blockLength; std::complex<double> err(0.0, 0.0); double max_err = 0.0; for ( size_t i = 0; i < blockSize; ++i ) { err = inverted_data[i] - data[i]; if (std::abs(err) > max_err){ max_err = std::abs(err); } } ASSERT_LT(max_err, 1.0e-9); } TEST(gpuSignal, upsampleFloat) { int width = 100; // fft length for FFT computations size_t nfft; //sig.nextPowerOfTwo(width, nfft); nfft = width; // upsampling factor int oversample = 2; // reserve memory for a block of data with the size of nfft std::valarray<std::complex<float>> slc(nfft); std::valarray<std::complex<float>> slcU(nfft*oversample); for (size_t i=0; i<width; ++i){ float phase = std::sin(10*M_PI*i/width); slc[i] = std::complex<float> (std::cos(phase), std::sin(phase)); } // instantiate a signal object gpuSignal<float> sig_lo_res(CUFFT_C2C); gpuSignal<float> sig_hi_res(CUFFT_C2C); // create plans sig_lo_res.rangeFFT(nfft, 1); sig_hi_res.rangeFFT(oversample*nfft, 1); upsample(sig_lo_res, sig_hi_res, slc, slcU); // Check if the original smaples have the same phase in the signal before and after upsampling float max_err = 0.0; float err = 0.0; for (size_t col = 0; col<width; col++){ err = std::arg(slc[col] * std::conj(slcU[oversample*col])); if (std::abs(err) > max_err){ max_err = std::abs(err); } } float max_err_u = 0.0; float err_u; float step = 1.0/oversample; std::complex<float> cpxData; for (size_t col = 0; col<width*oversample; col++){ float i = col*step; float phase = std::sin(10*M_PI*i/(width)); cpxData = std::complex<float> (std::cos(phase), std::sin(phase)); err_u = std::arg(cpxData * std::conj(slcU[col])); if (std::abs(err_u) > max_err_u){ max_err_u = std::abs(err_u); } } ASSERT_LT(max_err, 1.0e-6); ASSERT_LT(max_err_u, 1.0e-6); } TEST(gpuSignal, upsampleDouble) { int width = 100; // fft length for FFT computations size_t nfft; //sig.nextPowerOfTwo(width, nfft); nfft = width; // upsampling factor int oversample = 2; // reserve memory for a block of data with the size of nfft std::valarray<std::complex<double>> slc(nfft); std::valarray<std::complex<double>> slcU(nfft*oversample); for (size_t i=0; i<width; ++i){ double phase = std::sin(10*M_PI*i/width); slc[i] = std::complex<double> (std::cos(phase), std::sin(phase)); } // instantiate a signal object gpuSignal<double> sig_lo_res(CUFFT_Z2Z); gpuSignal<double> sig_hi_res(CUFFT_Z2Z); // create plans sig_lo_res.rangeFFT(nfft, 1); sig_hi_res.rangeFFT(oversample*nfft, 1); upsample(sig_lo_res, sig_hi_res, slc, slcU); // Check if the original smaples have the same phase in the signal before and after upsampling double max_err = 0.0; double err = 0.0; for (size_t col = 0; col<width; col++){ err = std::arg(slc[col] * std::conj(slcU[oversample*col])); if (std::abs(err) > max_err){ max_err = std::abs(err); } } double max_err_u = 0.0; double err_u; double step = 1.0/oversample; std::complex<double> cpxData; for (size_t col = 0; col<width*oversample; col++){ double i = col*step; double phase = std::sin(10*M_PI*i/(width)); cpxData = std::complex<double> (std::cos(phase), std::sin(phase)); err_u = std::arg(cpxData * std::conj(slcU[col])); if (std::abs(err_u) > max_err_u){ max_err_u = std::abs(err_u); } } ASSERT_LT(max_err, 1.0e-9); ASSERT_LT(max_err_u, 1.0e-9); } TEST(gpuSignal, FFT2D) { int width = 12; int length = 10; thrust::complex<double> *d_data; // int blockLength = length; // reserve memory for a block of data std::valarray<std::complex<double>> data(width*blockLength); // reserve memory for the spectrum of the block of data std::valarray<std::complex<double>> spectrum(width*blockLength); // reserve memory for a block of data computed from inverse FFT std::valarray<std::complex<double>> invertData(width*blockLength); for (size_t i = 0; i< length; ++i){ for (size_t j = 0; j< width; ++j){ data[i*width + j] = std::complex<double> (std::cos(i*j), std::sin(i*j)); } } // copy data to device size_t data_sz = width * blockLength * sizeof(thrust::complex<double>); checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz)); checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice)); // a signal object gpuSignal<double> sig(CUFFT_Z2Z); // create plan sig.FFT2D(width, blockLength); sig.forwardDevMem(d_data); sig.inverseDevMem(d_data); cudaMemcpy(&invertData[0], d_data, data_sz, cudaMemcpyDeviceToHost); invertData /= width*length; double max_err = 0.0; double err = 0.0; for (size_t i = 0; i< length; ++i){ for (size_t j = 0; j< width; ++j){ err = std::abs(data[i*width + j] - invertData[i*width + j]); if (err > max_err) max_err = err; } } ASSERT_LT(max_err, 1.0e-12); } TEST(gpuSignal, realDoubleDataFFT) { int width = 120; int length = 100; int blockLength = length; // reserve memory for a block of data double *data = new double[width*blockLength]; // reserve memory for the spectrum of the block of data std::complex<double> *spectrum = new std::complex<double>[width*blockLength]; // reserve memory for a block of data computed from inverse FFT double *invertData = new double[width*blockLength]; for (size_t i = 0; i< length; ++i){ for (size_t j = 0; j< width; ++j){ data[i*width + j] = i+j; } } // a signal objects gpuSignal<double> sig_D2Z(CUFFT_D2Z); gpuSignal<double> sig_Z2D(CUFFT_Z2D); // make plans sig_D2Z.FFT2D(width, blockLength); sig_Z2D.FFT2D(width, blockLength); // forward and inverse transform sig_D2Z.forwardD2Z(data, spectrum); sig_Z2D.inverseZ2D(spectrum, invertData); for (size_t i = 0; i< length; ++i){ for (size_t j = 0; j< width; ++j){ invertData[i*width + j] = i+j; } } double max_err_2DFFT = 0.0; double err = 0.0; for (size_t i = 0; i< length; ++i){ for (size_t j = 0; j< width; ++j){ err = std::abs(data[i*width + j] - invertData[i*width + j]); if (err > max_err_2DFFT) max_err_2DFFT = err; } } ASSERT_LT(max_err_2DFFT, 1.0e-12); } int main(int argc, char * argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } // end of file
13,436
5,092
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <openvino/opsets/opset7.hpp> #include "op_table.hpp" using namespace std; using namespace ov; using namespace ov::frontend::tensorflow::detail; namespace ov { namespace frontend { namespace tensorflow { namespace op { OutputVector translate_max_pool_op(const NodeContext& node) { auto ng_input = node.get_input(0); auto tf_strides = node.get_attribute<std::vector<int32_t>>("strides"); auto tf_ksize = node.get_attribute<std::vector<int32_t>>("ksize"); auto tf_padding_type = node.get_attribute<std::string>("padding"); auto tf_data_format = node.get_attribute<std::string>("data_format"); bool is_nhwc = (tf_data_format == "NHWC") || (tf_data_format == "NDHWC"); int N = 2; if (node.get_name() == "MaxPool3D") { N = 3; } Strides ng_strides(N); Shape ng_image_shape(N); Shape ng_kernel_shape(N); Shape ng_dilations(N, 1); convert_nhwc_to_hw(is_nhwc, tf_strides, ng_strides); convert_nhwc_to_hw(is_nhwc, ng_input.get_shape(), ng_image_shape); convert_nhwc_to_hw(is_nhwc, tf_ksize, ng_kernel_shape); convert_nhwc_to_nchw(node.get_name(), is_nhwc, ng_input); CoordinateDiff padding_below; CoordinateDiff padding_above; make_padding(tf_padding_type, ng_image_shape, ng_kernel_shape, ng_strides, ng_dilations, padding_below, padding_above); // TODO: remove this once OV supports negative padding // (CoordinateDiff) for MaxPool Shape ng_padding_below(padding_below.begin(), padding_below.end()); Shape ng_padding_above(padding_above.begin(), padding_above.end()); auto res_node = make_shared<ov::opset7::MaxPool>(ng_input, ng_strides, ng_padding_below, ng_padding_above, ng_kernel_shape, ov::op::RoundingType::FLOOR); auto res = res_node->output(0); convert_nchw_to_nhwc(node.get_name(), is_nhwc, res); set_node_name(node.get_name(), res.get_node_shared_ptr()); return {res}; } } // namespace op } // namespace tensorflow } // namespace frontend } // namespace ov
2,463
817
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Audio/AudioDevice.hpp> #include <SFML/Audio/ALCheck.hpp> #include <SFML/Audio/Listener.hpp> #include <SFML/System/Err.hpp> #include <memory> namespace { ALCdevice* audioDevice = NULL; ALCcontext* audioContext = NULL; float listenerVolume = 100.f; sf::Vector3f listenerPosition (0.f, 0.f, 0.f); sf::Vector3f listenerDirection(0.f, 0.f, -1.f); sf::Vector3f listenerUpVector (0.f, 1.f, 0.f); } namespace sf { namespace priv { //////////////////////////////////////////////////////////// AudioDevice::AudioDevice() { // Create the device audioDevice = alcOpenDevice(NULL); if (audioDevice) { // Create the context audioContext = alcCreateContext(audioDevice, NULL); if (audioContext) { // Set the context as the current one (we'll only need one) alcMakeContextCurrent(audioContext); // Apply the listener properties the user might have set float orientation[] = {listenerDirection.x, listenerDirection.y, listenerDirection.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z}; alCheck(alListenerf(AL_GAIN, listenerVolume * 0.01f)); alCheck(alListener3f(AL_POSITION, listenerPosition.x, listenerPosition.y, listenerPosition.z)); alCheck(alListenerfv(AL_ORIENTATION, orientation)); } else { err() << "Failed to create the audio context" << std::endl; } } else { err() << "Failed to open the audio device" << std::endl; } } //////////////////////////////////////////////////////////// AudioDevice::~AudioDevice() { // Destroy the context alcMakeContextCurrent(NULL); if (audioContext) alcDestroyContext(audioContext); // Destroy the device if (audioDevice) alcCloseDevice(audioDevice); } //////////////////////////////////////////////////////////// bool AudioDevice::isExtensionSupported(const std::string& extension) { // Create a temporary audio device in case none exists yet. // This device will not be used in this function and merely // makes sure there is a valid OpenAL device for extension // queries if none has been created yet. std::auto_ptr<AudioDevice> device; if (!audioDevice) device.reset(new AudioDevice); if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC")) return alcIsExtensionPresent(audioDevice, extension.c_str()) != AL_FALSE; else return alIsExtensionPresent(extension.c_str()) != AL_FALSE; } //////////////////////////////////////////////////////////// int AudioDevice::getFormatFromChannelCount(unsigned int channelCount) { // Create a temporary audio device in case none exists yet. // This device will not be used in this function and merely // makes sure there is a valid OpenAL device for format // queries if none has been created yet. std::auto_ptr<AudioDevice> device; if (!audioDevice) device.reset(new AudioDevice); // Find the good format according to the number of channels int format = 0; switch (channelCount) { case 1: format = AL_FORMAT_MONO16; break; case 2: format = AL_FORMAT_STEREO16; break; case 4: format = alGetEnumValue("AL_FORMAT_QUAD16"); break; case 6: format = alGetEnumValue("AL_FORMAT_51CHN16"); break; case 7: format = alGetEnumValue("AL_FORMAT_61CHN16"); break; case 8: format = alGetEnumValue("AL_FORMAT_71CHN16"); break; default: format = 0; break; } // Fixes a bug on OS X if (format == -1) format = 0; return format; } //////////////////////////////////////////////////////////// void AudioDevice::setGlobalVolume(float volume) { if (audioContext) alCheck(alListenerf(AL_GAIN, volume * 0.01f)); listenerVolume = volume; } //////////////////////////////////////////////////////////// float AudioDevice::getGlobalVolume() { return listenerVolume; } //////////////////////////////////////////////////////////// void AudioDevice::setPosition(const Vector3f& position) { if (audioContext) alCheck(alListener3f(AL_POSITION, position.x, position.y, position.z)); listenerPosition = position; } //////////////////////////////////////////////////////////// Vector3f AudioDevice::getPosition() { return listenerPosition; } //////////////////////////////////////////////////////////// void AudioDevice::setDirection(const Vector3f& direction) { if (audioContext) { float orientation[] = {direction.x, direction.y, direction.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z}; alCheck(alListenerfv(AL_ORIENTATION, orientation)); } listenerDirection = direction; } //////////////////////////////////////////////////////////// Vector3f AudioDevice::getDirection() { return listenerDirection; } //////////////////////////////////////////////////////////// void AudioDevice::setUpVector(const Vector3f& upVector) { if (audioContext) { float orientation[] = {listenerDirection.x, listenerDirection.y, listenerDirection.z, upVector.x, upVector.y, upVector.z}; alCheck(alListenerfv(AL_ORIENTATION, orientation)); } listenerUpVector = upVector; } //////////////////////////////////////////////////////////// Vector3f AudioDevice::getUpVector() { return listenerUpVector; } } // namespace priv } // namespace sf
6,993
1,875
#include <iostream> #include <type_traits> // When applying the detection-idiom it may be necessary to rely on ADL - we may want to check // if some expression can be called on a given type, taking into account free functions provided // in some namespace and also taking ADL into consideration. // We can do so, without polluting the given namespace with using declarations. // Given a `is_detected` idiom template: template<typename...> using void_t = void; template<template<typename...> class Expression, typename Void, typename... Ts> struct is_detected_impl : std::false_type { }; template<template<typename...> class Expression, typename... Ts> struct is_detected_impl<Expression, void_t<Expression<Ts...>>, Ts...> : std::true_type { }; template<template<typename...> class Expression, typename... Ts> using is_detected_t = is_detected_impl<Expression, void, Ts...>; template<template<typename...> class Expression, typename... Ts> inline constexpr bool is_detected{is_detected_t<Expression, Ts...>::value}; // If and we want to check if calling `begin` and `end` on a given type are valid operations // we can take ADL into consideration by doing the following: namespace detail { using std::begin; using std::end; template<typename T> using begin_expression = decltype(begin(std::declval<T>())); template<typename T> using end_expression = decltype(end(std::declval<T>())); } // namespace detail template<typename T> inline constexpr bool IsRange{is_detected<begin_expression, T> && is_detected<end_expression, T>}; int main() { }
1,574
452
// Copyright Vladimir Prus 2004. // 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) #pragma once #include <hpx/program_options/config.hpp> /** The version of the source interface. The value will be incremented whenever a change is made which might cause compilation errors for existing code. */ #ifdef HPX_PROGRAM_OPTIONS_VERSION #error HPX_PROGRAM_OPTIONS_VERSION already defined #endif #define HPX_PROGRAM_OPTIONS_VERSION 2 // Signal that implicit options will use values from next // token, if available. #define HPX_PROGRAM_OPTIONS_IMPLICIT_VALUE_NEXT_TOKEN 1
718
250
/** * Copyright (c) 2017 Melown Technologies SE * * 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. */ #ifndef mapproxy_support_metatile_hpp_included_ #define mapproxy_support_metatile_hpp_included_ #include "vts-libs/registry.hpp" #include "vts-libs/vts/basetypes.hpp" #include "vts-libs/vts/tileop.hpp" #include "../resource.hpp" #include "./coverage.hpp" namespace vts = vtslibs::vts; namespace vr = vtslibs::registry; /** Metatile block (part of metatile sharing same spatial division) */ struct MetatileBlock { std::string srs; vts::TileRange view; math::Extents2 extents; /** Common ancestor of nodes in this block */ vts::NodeInfo commonAncestor; vts::TileId offset; typedef std::vector<MetatileBlock> list; MetatileBlock(vts::Lod lod, const vr::ReferenceFrame &referenceFrame , const std::string &srs, const vts::TileRange &view , const math::Extents2 &extents); bool valid() const { return commonAncestor.valid(); } bool partial() const { return commonAncestor.partial(); } }; /** Generate metatile blocks for given metatile id in given reference frame * * \param referenceFrame reference frame * \param tileId metatile id * \param metaBinaryOrder metatile binary order override if nonzero */ MetatileBlock::list metatileBlocks(const Resource &resource , const vts::TileId &tileId , unsigned int metaBinaryOrder = 0 , bool includeInvalid = false); inline bool special(const vr::ReferenceFrame &referenceFrame , const vts::TileId &tileId) { if (const auto *node = referenceFrame.find(vts::rfNodeId(tileId), std::nothrow)) { switch (node->partitioning.mode) { case vr::PartitioningMode::manual: case vr::PartitioningMode::barren: return true; default: return false; } } return false; } class ShiftMask { public: ShiftMask(const MetatileBlock &block, int samplesPerTile , const MaskTree &maskTree_ = MaskTree()) : offset_(block.offset.x * samplesPerTile , block.offset.y * samplesPerTile) , mask_(generateCoverage((1 << block.offset.lod) * samplesPerTile , block.commonAncestor, maskTree_ , vts::NodeInfo::CoverageType::grid)) {} bool operator()(int x, int y) const { return mask_.get(x + offset_(0), y + offset_(1)); } private: const math::Point2i offset_; const vts::NodeInfo::CoverageMask mask_; }; /** Boundlayer metatile from mask */ cv::Mat boundlayerMetatileFromMaskTree(const vts::TileId &tileId , const MaskTree &maskTree , const MetatileBlock::list &blocks); #endif // mapproxy_support_metatile_hpp_included_
4,230
1,346
// // HashStatistic.cpp // // $Id: //poco/1.4/Foundation/src/HashStatistic.cpp#1 $ // // Library: Foundation // Package: Hashing // Module: HashStatistic // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/HashStatistic.h" #include <sstream> namespace Poco { HashStatistic::HashStatistic( UInt32 tableSize, UInt32 numEntries, UInt32 numZeroEntries, UInt32 maxEntry, std::vector<UInt32> details): _sizeOfTable(tableSize), _numberOfEntries(numEntries), _numZeroEntries(numZeroEntries), _maxEntriesPerHash(maxEntry), _detailedEntriesPerHash(details) { } HashStatistic::~HashStatistic() { } std::string HashStatistic::toString() const { std::ostringstream str; str << "HashTable of size " << _sizeOfTable << " containing " << _numberOfEntries << " entries:\n"; str << " NumberOfZeroEntries: " << _numZeroEntries << "\n"; str << " MaxEntry: " << _maxEntriesPerHash << "\n"; str << " AvgEntry: " << avgEntriesPerHash() << ", excl Zero slots: " << avgEntriesPerHashExclZeroEntries() << "\n"; str << " DetailedStatistics: \n"; for (int i = 0; i < _detailedEntriesPerHash.size(); ++i) { // 10 entries per line if (i % 10 == 0) { str << "\n " << i << ":"; } str << " " << _detailedEntriesPerHash[i]; } str << "\n"; str.flush(); return str.str(); } } // namespace Poco
2,806
1,003
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #include "chrono/solver/ChSolverSOR.h" namespace chrono { // Register into the object factory, to enable run-time dynamic creation and persistence CH_FACTORY_REGISTER(ChSolverSOR) double ChSolverSOR::Solve(ChSystemDescriptor& sysd ///< system description with constraints and variables ) { std::vector<ChConstraint*>& mconstraints = sysd.GetConstraintsList(); std::vector<ChVariables*>& mvariables = sysd.GetVariablesList(); tot_iterations = 0; double maxviolation = 0.; double maxdeltalambda = 0.; int i_friction_comp = 0; double old_lambda_friction[3]; // 1) Update auxiliary data in all constraints before starting, // that is: g_i=[Cq_i]*[invM_i]*[Cq_i]' and [Eq_i]=[invM_i]*[Cq_i]' for (unsigned int ic = 0; ic < mconstraints.size(); ic++) mconstraints[ic]->Update_auxiliary(); // Average all g_i for the triplet of contact constraints n,u,v. // int j_friction_comp = 0; double gi_values[3]; for (unsigned int ic = 0; ic < mconstraints.size(); ic++) { if (mconstraints[ic]->GetMode() == CONSTRAINT_FRIC) { gi_values[j_friction_comp] = mconstraints[ic]->Get_g_i(); j_friction_comp++; if (j_friction_comp == 3) { double average_g_i = (gi_values[0] + gi_values[1] + gi_values[2]) / 3.0; mconstraints[ic - 2]->Set_g_i(average_g_i); mconstraints[ic - 1]->Set_g_i(average_g_i); mconstraints[ic - 0]->Set_g_i(average_g_i); j_friction_comp = 0; } } } // 2) Compute, for all items with variables, the initial guess for // still unconstrained system: for (unsigned int iv = 0; iv < mvariables.size(); iv++) { if (mvariables[iv]->IsActive()) mvariables[iv]->Compute_invMb_v(mvariables[iv]->Get_qb(), mvariables[iv]->Get_fb()); // q = [M]'*fb } // 3) For all items with variables, add the effect of initial (guessed) // lagrangian reactions of contraints, if a warm start is desired. // Otherwise, if no warm start, simply resets initial lagrangians to zero. if (warm_start) { for (unsigned int ic = 0; ic < mconstraints.size(); ic++) if (mconstraints[ic]->IsActive()) mconstraints[ic]->Increment_q(mconstraints[ic]->Get_l_i()); } else { for (unsigned int ic = 0; ic < mconstraints.size(); ic++) mconstraints[ic]->Set_l_i(0.); } // 4) Perform the iteration loops // for (int iter = 0; iter < max_iterations; iter++) { // The iteration on all constraints // maxviolation = 0; maxdeltalambda = 0; i_friction_comp = 0; for (unsigned int ic = 0; ic < mconstraints.size(); ic++) { // skip computations if constraint not active. if (mconstraints[ic]->IsActive()) { // compute residual c_i = [Cq_i]*q + b_i + cfm_i*l_i double mresidual = mconstraints[ic]->Compute_Cq_q() + mconstraints[ic]->Get_b_i() + mconstraints[ic]->Get_cfm_i() * mconstraints[ic]->Get_l_i(); // true constraint violation may be different from 'mresidual' (ex:clamped if unilateral) double candidate_violation = fabs(mconstraints[ic]->Violation(mresidual)); // compute: delta_lambda = -(omega/g_i) * ([Cq_i]*q + b_i + cfm_i*l_i ) double deltal = (omega / mconstraints[ic]->Get_g_i()) * (-mresidual); if (mconstraints[ic]->GetMode() == CONSTRAINT_FRIC) { candidate_violation = 0; // update: lambda += delta_lambda; old_lambda_friction[i_friction_comp] = mconstraints[ic]->Get_l_i(); mconstraints[ic]->Set_l_i(old_lambda_friction[i_friction_comp] + deltal); i_friction_comp++; if (i_friction_comp == 1) candidate_violation = fabs(ChMin(0.0, mresidual)); if (i_friction_comp == 3) { mconstraints[ic - 2]->Project(); // the N normal component will take care of N,U,V double new_lambda_0 = mconstraints[ic - 2]->Get_l_i(); double new_lambda_1 = mconstraints[ic - 1]->Get_l_i(); double new_lambda_2 = mconstraints[ic - 0]->Get_l_i(); // Apply the smoothing: lambda= sharpness*lambda_new_projected + (1-sharpness)*lambda_old if (this->shlambda != 1.0) { new_lambda_0 = shlambda * new_lambda_0 + (1.0 - shlambda) * old_lambda_friction[0]; new_lambda_1 = shlambda * new_lambda_1 + (1.0 - shlambda) * old_lambda_friction[1]; new_lambda_2 = shlambda * new_lambda_2 + (1.0 - shlambda) * old_lambda_friction[2]; mconstraints[ic - 2]->Set_l_i(new_lambda_0); mconstraints[ic - 1]->Set_l_i(new_lambda_1); mconstraints[ic - 0]->Set_l_i(new_lambda_2); } double true_delta_0 = new_lambda_0 - old_lambda_friction[0]; double true_delta_1 = new_lambda_1 - old_lambda_friction[1]; double true_delta_2 = new_lambda_2 - old_lambda_friction[2]; mconstraints[ic - 2]->Increment_q(true_delta_0); mconstraints[ic - 1]->Increment_q(true_delta_1); mconstraints[ic - 0]->Increment_q(true_delta_2); if (this->record_violation_history) { maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_0)); maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_1)); maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_2)); } i_friction_comp = 0; } } else { // update: lambda += delta_lambda; double old_lambda = mconstraints[ic]->Get_l_i(); mconstraints[ic]->Set_l_i(old_lambda + deltal); // If new lagrangian multiplier does not satisfy inequalities, project // it into an admissible orthant (or, in general, onto an admissible set) mconstraints[ic]->Project(); // After projection, the lambda may have changed a bit.. double new_lambda = mconstraints[ic]->Get_l_i(); // Apply the smoothing: lambda= sharpness*lambda_new_projected + (1-sharpness)*lambda_old if (this->shlambda != 1.0) { new_lambda = shlambda * new_lambda + (1.0 - shlambda) * old_lambda; mconstraints[ic]->Set_l_i(new_lambda); } double true_delta = new_lambda - old_lambda; // For all items with variables, add the effect of incremented // (and projected) lagrangian reactions: mconstraints[ic]->Increment_q(true_delta); if (this->record_violation_history) maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta)); } maxviolation = ChMax(maxviolation, fabs(candidate_violation)); } // end IsActive() } // end loop on constraints // For recording into violaiton history, if debugging if (this->record_violation_history) AtIterationEnd(maxviolation, maxdeltalambda, iter); tot_iterations++; // Terminate the loop if violation in constraints has been succesfully limited. if (maxviolation < tolerance) break; } // end iteration loop return maxviolation; } } // end namespace chrono
8,673
2,655
/****************************************************************************/ /*** ***/ /*** Altona main configuration file. ***/ /*** ***/ /****************************************************************************/ /*** ***/ /*** Please rename this file to "altona_config.hpp" and edit it to ***/ /*** reflect your needs. ***/ /*** ***/ /****************************************************************************/ /*** ***/ /*** This file is compiled in every altona application ***/ /*** In addition to that, makeproject parses this file by hand on ***/ /*** every invokation. ***/ /*** ***/ /****************************************************************************/ // operator new shenanigans (one should investigate this) #pragma warning (disable: 4595) #pragma warning (disable: 5043) // GCed objects don't have delete #pragma warning (disable: 4291) // macro redef in shader disasm (conflict between dxsdk and windows sdk) #pragma warning (disable: 4005) #define sCONFIG_CODEROOT L"" #define sCONFIG_SDK_DX9 1 // Microsoft DX9 sdk installed (required for input, sound, graphics) #define sCONFIG_SDK_DX11 1 #define sCONFIG_SDK_CG 0 #define sCONFIG_GUID {0x74F17E89,{0x915F,0x4264,0xB67A},{0xBA,0xDF,0x00,0xD5,0x32,0x5A}} #define sCONFIG_RENDER_DX9 #define sCONFIG_CEF 1 #ifdef _DEBUG #define sCONFIG_BUILD_DEBUG #else #define sCONFIG_BUILD_RELEASE #endif
2,005
507
#pragma once #include <lava/sill.hpp> #include <nlohmann/json.hpp> struct GameState; class Frame { public: Frame(GameState& gameState); Frame(const Frame&) = delete; Frame& operator=(const Frame&) = delete; /// Create a frame. static Frame& make(GameState& gameState); /// Prepare the frame to be removed. /// The destructor does not destroy anything /// so that shutting down the application is fast enough. virtual void clear(bool removeFromLevel = true); const std::string& name() const { return m_name; } void name(const std::string& name) { m_name = name; } const lava::sill::EntityFrame& entityFrame() const { return *m_entityFrame; } lava::sill::EntityFrame& entityFrame() { return *m_entityFrame; } void entityFrame(lava::sill::EntityFrame& entityFrame) { m_entityFrame = &entityFrame; } const lava::sill::MeshFrameComponent& mesh() const { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); }; lava::sill::MeshFrameComponent& mesh() { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); }; protected: GameState& m_gameState; lava::sill::EntityFrame* m_entityFrame = nullptr; std::string m_name; }; uint32_t findFrameIndex(GameState& gameState, const lava::sill::EntityFrame& entityFrame); inline uint32_t findFrameIndex(GameState& gameState, const Frame& frame) { return findFrameIndex(gameState, frame.entityFrame()); }
1,440
452
int Jn, ZjHQ/*Y*//*dEky*/ ,H , lAIw, Mb4p , Rfpqw,s ,e6k,zuS,sSjf /*T*//**/ ,IBH , dg4 ,Vhk, iLTc ,X5YU, F4, hL /*2jtUXBP*/, oHs , JC,MHO, joPQ , zOHJ ; void f_f0 () {;//0uh { { int VTT; volatile int N ,/*kec*/ n , Q,O ; { for(int i=1 ; i< 1 ;++i//zYj ){} { for (int i=1;i<2 ;++i//X ) //b if (/*nG*/true ) {/*aQ*/ }else {//rU } }} VTT=O +N+ n+ Q ;}{ /*Mp*/return ;if( true ) {; }else if( true ) {; { }{ int Y//O ; volatile int QVq ,T8RxN , gUq;Y =//qBmC gUq + QVq + T8RxN ; if( true ) {} else for (int i=1;i<3;++i) ; //Vd } } else if (//a true)// ;else { { };/*Hg4b*/ }{volatile int O5E , ceux, fH0 ; {//duB }zOHJ//mI = fH0 + O5E+ceux ; }} for(int i=1;i< 4 ;++i)if (true) return ;else if (true/*VXU*/);else {int FN ;//S volatile int Ch ,C9 , Z;{ return ; if (//d true) {}else ; } { /*M2*/return ;/*kM7*/ for (int /*V*/i=1 ; i< /**/ 5/*k*/ ;++i ) return ;}FN =Z +/*Fv*/Ch+ C9 ; }return ; } return ; return ; return ;} void f_f1 () {for(int i=1; i< 6 ;++i);{ volatile int ReS ,zP, PXb//UmM7m ,u4Y, Bj, VTCUC , Bz ; //9S {//t volatile int Wj7, /*nn*/Khx//P9 , mstW , rjoH , tSdj;; { {volatile int W9y ,Ous4 ;//H if(true ) Jn= Ous4+W9y//8h //o1DB ; /*d*/else return ; } if//ix (true ) {} else return ;/*yc4z*/}ZjHQ=tSdj + Wj7 + Khx+mstW+//ry rjoH; } if( true//RhY ) H=Bz+ReS//87 + zP+ PXb + u4Y+Bj + VTCUC ;else{ { //DglY { ;} } ; { { ; }{} } }{ if ( true);else return ;{ {} return ;} }{ volatile int KcUw5P,satW, I5; { int ofQ; volatile int LNPT , kJf,mY ;{ } ofQ= mY + LNPT+ kJf; };lAIw= I5+ KcUw5P + satW ;}} { {int UM;/*mG*/ volatile int RYkTe,EQcC ,O3 ; if ( true ) UM = O3 +RYkTe + EQcC //aY ; else {{ {}{ }{ } }}{ volatile int q,a5gF , X9T03 , gFe6uE; if ( true ) {{/*6n*/volatile int Ln ;if (true // )Mb4p = Ln ; else//XD return ; } } else/*EFG*/ Rfpqw = gFe6uE + q//e + a5gF +X9T03; { } // }{ volatile int Hr ,XtU ,/*zO*/uQ; {} s = uQ + Hr + XtU;}if (true) {{{}if ( true){ } else{} }{/*tT*/ {} } }else {{ } }for(int i=1 ; i< 7 ;++i )if( true ) {/*v5o*/ int w5bB ;volatile int QxP//v6N //HVF6q ,iaa1e; if(true)for(int i=1;i< 8 ;++i )for (int i=1 ; i<9 ;++i )if (true ) return ; else return/*J*/ ; else w5bB = iaa1e +QxP ; { {}{ } } {{ } } } else { volatile int vEH ,C4n3p , Gj3SY, AFCK;/*qR*/e6k= AFCK + vEH + C4n3p + Gj3SY; } // return ;}{{ ; if ( true ) {} else{ volatile int j1, lg ; return ;zuS = lg +j1 ;return ; } } ; /*cSAm*/ } {{{{ { } } } { if /*rP*/( true ){ }else return ; } } {/**/return ;{if ( true ) //1 return ; else{ } } }if(true ) ;else {/*J*/{ { }{ }{} }//PGE {} /*ffJ*/{ } } if (true ) { if /*KZ8*/( true ){} else ; }else {for (int i=1; i< 10 ;++i)return ; ; return/*gCypm*/ ; } } ;{ {//S { return ; { }//uC5D }{int AD /*R2*/; volatile int PRE, Swtj; AD =Swtj+ PRE ; return ; { }} } if ( true//uxo ) { /*x*/return ; } else ; }}return ; return/*k*/ ; }void f_f2 (){{{ int n97; volatile int WJT1z , x4N , Sy ;n97 // =Sy+WJT1z //lv +x4N ; { {int L1N; volatile int XU/*ahy*/ //w ; L1N= XU ;}//d for (int i=1 //hB7gK ; i< 11;++i ){} ;} for/*X*/ (int i=1 ;i<12 ;++i){ ; }}{ int vsp ; volatile int j ,Ylgro, RGV9 //YP ,//nmy GE ,g55 , //tA PkmsX,ms , R ;//pR //Hx {volatile int V5 , VJsOq, c ; sSjf=c +V5 +VJsOq //a ;} IBH =R +j+Ylgro+RGV9+GE ; vsp = g55 + PkmsX +ms// ; } for (int i=1 ; i<13;++i) { return ; if (true)if(true ) {//O return ; return ;} else return ; else for (int i=1 ; i< 14 ;++i ) {/*UYB*/{} }{; for (int i=1 ;i< /*n1S*/ 15 ;++i )for(int i=1 ;//gf9 // i<16 ;++i){} } } {volatile int V89x8, YN8, Cr0jX//Wt ;for (int i=1 //v1o ; i</**/ 17 /*PWv*/ ;++i ) if (true) dg4= Cr0jX + V89x8 +/**/YN8;else return ;{//fe ;} if ( true ) {{ } { }{; }{int hX0W;volatile int N5 , lw0U ; if(true ) {//Tg // } else{} for (int i=1 ;i< 18;++i ) return//D ; { } hX0W=lw0U + N5 ;} } else { return ; {}; }} }{{ int W1Q;volatile int a ,zW , D ,E;return ;W1Q//BV0P =/*J5*/ E +a + zW+D; { { {{ } }} /*6hb*/{}}{ return ;; /*n*/ //n {for (int i=1 ;i<//qzq 19/*IN4*/;++i ) for (int i=1; i<20 ;++i ) if( true )return ; else ;/*V56*/if ( true ) { return ; }else {} { }} }/*gNm*/; } { int kVag ;volatile int i2,xRW , //Hjl bPYOQ7, SdKrE, e6;for (int i=1 ;i<21;++i //tt9T ) /*Y*/{; { { } }} /*Gs*/kVag= e6+i2 + xRW +bPYOQ7+ SdKrE ; } ; } {;return ;//Wo ;} return ; return ;//M6To } int main /*d*/() { /*oh*/volatile int fF3, W8hKj , rZ , /*SN5*/ mj ,r; if//C (true ) return 1747888762 ; else/*t*/ /**/ if( true ) //6o for (int i=1; i<22 ;++i ) { { return//2 1892777458; {{{} }} //VBI return 973039688 //Pmf ;} //fh { return 979197843; { return 1574272463;}{ {{ } }return 1112267248 ; } }{;//Kg { {volatile int OVcBo ,DL2 ;{ } Vhk = DL2 + OVcBo;}for (int i=1; i< 23 ;++i ) { return //m 472807525;return 2080782169 ; } {} } { {} {;} for(int i=1;i< 24;++i//5X ) return 403167836 ;} } }else iLTc= r + fF3/**/ + W8hKj+rZ + mj//rn ; { { volatile int g99Nx, Sxvj, gmw, Ge//0AXsi ; X5YU //3E5T =Ge+ g99Nx /*m2*/ + Sxvj+gmw ; { {volatile int BGQ , u ;F4 =u+ BGQ ; } } //uO { { } {{}return 1107412337 ;}} for (int i=1; i< 25 ;++i) { { {{} { } } } { {if ( true ){ } /*o*/else {//Nr for (int i=1 ; /*l*/i< 26 ;++i){ } } } //U2 ;for (int i=1 ; i< 27 ;++i )// { ; ; } }} }; {{{{ } {/*m*/ } //P2i }}//h for(int i=1;i<28;++i ) {; {} ; {{} }} }} ;if/*J3B*/ ( true )return 2058880243;else/*OO*/ ;; {volatile int //Lc rCK , WZN ,Fm, Bcc , zslP, YrC4 , fD ,/*1*/ wX ,hy ,RIQ ; hL = RIQ +rCK + WZN +Fm+ Bcc; {{ //I7Q { } for(int i=1 ;i< 29 ;++i ) { }} { {}//I return 1287420094//HX ;}} oHs= //JpO zslP +YrC4+ fD+ wX + hy //NuZ ;{{{ int pxnN; volatile int/*cc3pC*/ hx , WQVc ;pxnN= WQVc+ hx ; /*v7R*/{ } }} { volatile int Gh , LdwE , L20 , qoH4 , Opg, aFoc ,NJR ,ba8JC ,//rS b2mXaio; JC = b2mXaio +Gh +LdwE ;{ } if /**/( true ) for(int i=1 ;i<30 ;++i // ) MHO =L20+ qoH4;else joPQ=Opg + aFoc +NJR/*4eLY*/ +ba8JC ; } //6WE {{ }} }} }
6,338
4,347
/* ------------------------------------------------------------------------- * * nbtdesc.cpp * rmgr descriptor routines for access/nbtree/nbtxlog.cpp * * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/gausskernel/storage/access/rmgrdesc/nbtdesc.cpp * * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "access/nbtree.h" void btree_desc(StringInfo buf, XLogReaderState* record) { char* rec = XLogRecGetData(record); uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK; switch (info) { case XLOG_BTREE_INSERT_LEAF: { xl_btree_insert* xlrec = (xl_btree_insert*)rec; appendStringInfo(buf, "insert leaf: "); appendStringInfo(buf, "off %u", (uint32)xlrec->offnum); break; } case XLOG_BTREE_INSERT_UPPER: { xl_btree_insert* xlrec = (xl_btree_insert*)rec; appendStringInfo(buf, "insert upper: "); appendStringInfo(buf, "off %u", (uint32)xlrec->offnum); break; } case XLOG_BTREE_INSERT_META: { xl_btree_insert* xlrec = (xl_btree_insert*)rec; appendStringInfo(buf, "insert meta: "); appendStringInfo(buf, "off %u",(uint32)xlrec->offnum); break; } case XLOG_BTREE_SPLIT_L: { xl_btree_split* xlrec = (xl_btree_split*)rec; appendStringInfo(buf, "split left: "); appendStringInfo(buf, "level %u; firstright %u; new off %u", xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff); break; } case XLOG_BTREE_SPLIT_R: { xl_btree_split* xlrec = (xl_btree_split*)rec; appendStringInfo(buf, "split right: "); appendStringInfo(buf, "level %u; firstright %u; new off %u", xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff); break; } case XLOG_BTREE_SPLIT_L_ROOT: { xl_btree_split* xlrec = (xl_btree_split*)rec; appendStringInfo(buf, "split left root: "); appendStringInfo(buf, "level %u; firstright %u; new off %u", xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff); break; } case XLOG_BTREE_SPLIT_R_ROOT: { xl_btree_split* xlrec = (xl_btree_split*)rec; appendStringInfo(buf, "split right root: "); appendStringInfo(buf, "level %u; firstright %u; new off %u", xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff); break; } case XLOG_BTREE_VACUUM: { xl_btree_vacuum* xlrec = (xl_btree_vacuum*)rec; appendStringInfo(buf, "vacuum: lastBlockVacuumed %u ", xlrec->lastBlockVacuumed); break; } case XLOG_BTREE_DELETE: { xl_btree_delete* xlrec = (xl_btree_delete*)rec; int bucket_id = XLogRecGetBucketId(record); if (bucket_id == -1) { appendStringInfo(buf, "delete: %d items; heap %u/%u/%u", xlrec->nitems, xlrec->hnode.spcNode, xlrec->hnode.dbNode, xlrec->hnode.relNode); } else { appendStringInfo(buf, "delete: %d items; heap %u/%u/%d/%u", xlrec->nitems, xlrec->hnode.spcNode, xlrec->hnode.dbNode, bucket_id, xlrec->hnode.relNode); } break; } case XLOG_BTREE_DELETE_PAGE: { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec; appendStringInfo(buf, "delete page: "); appendStringInfo(buf, "left %u; right %u; btpo_xact " XID_FMT "; parent off %u", xlrec->leftblk, xlrec->rightblk, xlrec->btpo_xact, (uint32)xlrec->poffset); break; } case XLOG_BTREE_DELETE_PAGE_META: { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec; appendStringInfo(buf, "delete page meta: "); appendStringInfo(buf, "left %u; right %u; btpo_xact " XID_FMT "; parent off %u", xlrec->leftblk, xlrec->rightblk, xlrec->btpo_xact, (uint32)xlrec->poffset); break; } case XLOG_BTREE_DELETE_PAGE_HALF: { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec; appendStringInfo(buf, "delete page half: "); appendStringInfo(buf, "left %u; right %u; btpo_xact " XID_FMT "; parent off %u", xlrec->leftblk, xlrec->rightblk, xlrec->btpo_xact, (uint32)xlrec->poffset); break; } case XLOG_BTREE_NEWROOT: { xl_btree_newroot* xlrec = (xl_btree_newroot*)rec; appendStringInfo(buf, "lev %u", xlrec->level); break; } case XLOG_BTREE_REUSE_PAGE: { xl_btree_reuse_page* xlrec = (xl_btree_reuse_page*)rec; int bucket_id = XLogRecGetBucketId(record); if (bucket_id == -1) { appendStringInfo(buf, "reuse_page: rel %u/%u/%u; latestRemovedXid " XID_FMT, xlrec->node.spcNode, xlrec->node.dbNode, xlrec->node.relNode, xlrec->latestRemovedXid); } else { appendStringInfo(buf, "reuse_page: rel %u/%u/%u/%d; latestRemovedXid " XID_FMT, xlrec->node.spcNode, xlrec->node.dbNode, xlrec->node.relNode, bucket_id, xlrec->latestRemovedXid); } break; } default: appendStringInfo(buf, "UNKNOWN"); break; } }
6,368
2,151
#include "TTreeNodeStack.h" TTreeNodeStack& TTreeNodeStack::operator = (const TTreeNodeStack& treeNodeStack) { fStack = treeNodeStack.fStack; return (*this); } void TTreeNodeStack::Pop (TTreeNode*& item) { TObject* obj = NULL; fStack.Pop (obj); item = (TTreeNode*)obj; } void TTreeNodeStack::Top (const TTreeNode*& item) const { const TObject* obj = NULL; fStack.Top (obj); item = (TTreeNode*) obj; } TTreeNodeStack::TTreeNodeStack (void) : fStack () { } TTreeNodeStack::TTreeNodeStack (const TTreeNodeStack& treeNodeStack) : fStack (treeNodeStack.fStack) { } TTreeNodeStack::~TTreeNodeStack (void) { }
626
225
// Copyright (c) 2015 The CSUTIL 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 "base/search.h" namespace base { } #ifdef _SEARCH_MAIN_TEST_ #include <deque> #include <vector> #include <utility> #include <assert.h> int main(int argc, char *argv[]) {/*{{{*/ using namespace base; // descend search int arr_des_odd[] = {40, 35, 30, 25, 20, 15, 10}; Print(arr_des_odd, arr_des_odd + sizeof(arr_des_odd)/sizeof(arr_des_odd[0]), arr_des_odd[0]); int pos = 0; int test_arr_odd[] = {43, 40, 37, 35, 32, 30, 28, 25, 21, 20, 16, 15, 13, 10, 2 }; for (int i = 0; i < (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])); ++i) { Code ret = BinaryDescendSearch(arr_des_odd, sizeof(arr_des_odd)/sizeof(arr_des_odd[0]), test_arr_odd[i], &pos, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_odd[i], pos, arr_des_odd[pos]); } fprintf(stderr, "\n"); int arr_des_even[] = {40, 35, 30, 25, 20, 15}; Print(arr_des_even, arr_des_even + sizeof(arr_des_even)/sizeof(arr_des_even[0]), arr_des_even[0]); int test_arr_even[] = {44, 40, 38, 35, 33, 30, 26, 25, 24, 20, 18, 15, 11}; for (int i = 0; i < (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])); ++i) { Code ret = BinaryDescendSearch(arr_des_even, sizeof(arr_des_even)/sizeof(arr_des_even[0]), test_arr_even[i], &pos, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_even[i], pos, arr_des_even[pos]); } fprintf(stderr, "\n"); // ascend search int arr_asc_odd[] = {10, 15, 20, 25, 30, 35, 40}; Print(arr_asc_odd, arr_asc_odd + sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0]), arr_asc_odd[0]); for (int i = (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])) - 1; i >= 0; --i) { Code ret = BinaryAscendSearch(arr_asc_odd, sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0]), test_arr_odd[i], &pos, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_odd[i], pos, arr_asc_odd[pos]); } fprintf(stderr, "\n"); int arr_asc_even[] = {15, 20, 25, 30, 35, 40}; Print(arr_asc_even, arr_asc_even + sizeof(arr_asc_even)/sizeof(arr_asc_even[0]), arr_asc_even[0]); for (int i = (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])) -1; i >= 0; --i) { Code ret = BinaryAscendSearch(arr_asc_even, sizeof(arr_asc_even)/sizeof(arr_asc_even[0]), test_arr_even[i], &pos, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_even[i], pos, arr_asc_even[pos]); } fprintf(stderr, "\n"); // descend search using RandomIterator std::vector<int> vec_des_odd(arr_des_odd, arr_des_odd+sizeof(arr_des_odd)/sizeof(arr_des_odd[0])); Print(vec_des_odd.begin(), vec_des_odd.end(), vec_des_odd[0]); std::vector<int>::iterator it; for (int i = 0; i < (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])); ++i) { Code ret = BinaryDescendSearch(vec_des_odd.begin(), vec_des_odd.end(), test_arr_odd[i], &it, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, value:%d\n", test_arr_odd[i], *it); } fprintf(stderr, "\n"); std::vector<int> vec_des_even(arr_des_even, arr_des_even+sizeof(arr_des_even)/sizeof(arr_des_even[0])); Print(vec_des_even.begin(), vec_des_even.end(), vec_des_even[0]); for (int i = 0; i < (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])); ++i) { Code ret = BinaryDescendSearch(vec_des_even.begin(), vec_des_even.end(), test_arr_even[i], &it, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, value:%d\n", test_arr_even[i], *it); } fprintf(stderr, "\n"); // ascend search using RandomIterator std::deque<int> deq_asc_odd(arr_asc_odd, arr_asc_odd+sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0])); Print(deq_asc_odd.begin(), deq_asc_odd.end(), deq_asc_odd[0]); std::deque<int>::iterator deq_it; for (int i = (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])) - 1; i >= 0; --i) { Code ret = BinaryAscendSearch(deq_asc_odd.begin(), deq_asc_odd.end(), test_arr_odd[i], &deq_it, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, value:%d\n", test_arr_odd[i], *deq_it); } fprintf(stderr, "\n"); std::deque<int> deq_asc_even(arr_asc_even, arr_asc_even+sizeof(arr_asc_even)/sizeof(arr_asc_even[0])); Print(deq_asc_even.begin(), deq_asc_even.end(), deq_asc_even[0]); for (int i = (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])) -1; i >= 0; --i) { Code ret = BinaryAscendSearch(deq_asc_even.begin(), deq_asc_even.end(), test_arr_even[i], &deq_it, CompareNum<int>); assert(ret == kOk); fprintf(stderr, "test_value:%d, value:%d\n", test_arr_even[i], *deq_it); } fprintf(stderr, "\n"); fprintf(stderr, "\n"); // ascend search using RandomIterator and ComparePair std::vector<std::pair<std::string, std::string> > dir; dir.push_back(std::make_pair<std::string, std::string>("aa", "aa.txt")); dir.push_back(std::make_pair<std::string, std::string>("hh", "hh.txt")); dir.push_back(std::make_pair<std::string, std::string>("oo", "oo.txt")); dir.push_back(std::make_pair<std::string, std::string>("uu", "uu.txt")); std::pair<std::string, std::string> finds[] = {/*{{{*/ std::pair<std::string, std::string>("aa", ""), std::pair<std::string, std::string>("bb", ""), std::pair<std::string, std::string>("cc", ""), std::pair<std::string, std::string>("hh", ""), std::pair<std::string, std::string>("ii", ""), std::pair<std::string, std::string>("jj", ""), std::pair<std::string, std::string>("oo", ""), std::pair<std::string, std::string>("pp", ""), std::pair<std::string, std::string>("qq", ""), std::pair<std::string, std::string>("uu", ""), std::pair<std::string, std::string>("vv", ""), std::pair<std::string, std::string>("xx", ""), };/*}}}*/ fprintf(stderr, "finds num:%zu, single size:%zu\n", sizeof(finds)/sizeof(finds[0]), sizeof(finds[0])); std::vector<std::pair<std::string, std::string> >::iterator pair_it; for (int i = 0; i < (int)(sizeof(finds)/sizeof(finds[0])); ++i) { Code ret = BinaryAscendSearch(dir.begin(), dir.end(), finds[i], &pair_it, ComparePair<std::pair<std::string, std::string> >); assert(ret == kOk); fprintf(stderr, "finds key:%s, value:(%s, %s)\n", finds[i].first.c_str(), pair_it->first.c_str(), pair_it->second.c_str()); } fprintf(stderr, "\n"); return 0; }/*}}}*/ #endif
7,127
2,877
#include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout); using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const int MAX_N = 1e6 + 10; template <typename T> inline T sqr(T a) { return a * a;}; int t, n, ans[MAX_N], d[MAX_N], len; char buf[MAX_N]; struct Trie { int nxt[MAX_N][26], fail[MAX_N], end[MAX_N]; int root, L; int newnode() { for(int i = 0; i < 26; i++) nxt[L][i] = -1; end[L++] = 0; return L-1; } void init() { L = 0; root = newnode(); } void insert(char buf[]) { int len = strlen(buf); int now = root; for(int i = 0; i < len; i++) { if(nxt[now][buf[i]-'a'] == -1) nxt[now][buf[i]-'a'] = newnode(); now = nxt[now][buf[i]-'a']; } end[now] = 1; d[now] = len; } void build() { queue<int> Q; fail[root] = root; for(int i = 0; i < 26; i++) if(nxt[root][i] == -1) nxt[root][i] = root; else { fail[nxt[root][i]] = root; Q.push(nxt[root][i]); } while( !Q.empty() ) { int now = Q.front(); Q.pop(); for(int i = 0; i < 26; i++) if(nxt[now][i] == -1) nxt[now][i] = nxt[fail[now]][i]; else { fail[nxt[now][i]] = nxt[fail[now]][i]; Q.push(nxt[now][i]); } } } void solve(char buf[]) { int cur = root; int len = strlen(buf); int index; for(int i = 0; i < len; ++i) { if(buf[i] >= 'A' && buf[i] <= 'Z') index = buf[i] - 'A'; else if(buf[i] >= 'a' && buf[i] <= 'z') index = buf[i] - 'a'; else continue; cur = nxt[cur][index]; int x = cur; while(x != root) { if(end[x]) { ans[i + 1] -= 1; ans[i - d[x] + 1] += 1; break; } x = fail[x]; } } } }; Trie ac; int main(void) { scanf("%d", &t); while (t--) { ac.init(); scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%s", buf); ac.insert(buf); } getchar(); ac.build(); gets(buf); memset(ans, 0, sizeof ans); ac.solve(buf); ll res = 0; len = strlen(buf); for (int i = 0; i < len; ++i) { res += ans[i]; if (res <= 0) printf("%c", buf[i]); else printf("*"); } printf("\n"); for (int i = 0; i < len; ++i) cout << ans[i]; cout << endl; } return 0; }
3,262
1,204
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/geom/GeoLocation.h" #include "carla/geom/Location.h" #include "carla/geom/Math.h" #include <cmath> #if defined(_WIN32) && !defined(_USE_MATH_DEFINES) # define _USE_MATH_DEFINES # include <math.h> // cmath is not enough for MSVC #endif namespace carla { namespace geom { /// Earth radius at equator [m]. static constexpr double EARTH_RADIUS_EQUA = 6378137.0; /// Convert latitude to scale, which is needed by mercator /// transformations /// @param lat latitude in degrees (DEG) /// @return scale factor /// @note when converting from lat/lon -> mercator and back again, /// or vice versa, use the same scale in both transformations! static double LatToScale(double lat) { return std::cos(Math::to_radians(lat)); } /// Converts lat/lon/scale to mx/my (mx/my in meters if correct scale /// is given). template <class float_type> static void LatLonToMercator(double lat, double lon, double scale, float_type &mx, float_type &my) { mx = scale * Math::to_radians(lon) * EARTH_RADIUS_EQUA; my = scale * EARTH_RADIUS_EQUA * std::log(std::tan((90.0 + lat) * Math::pi() / 360.0)); } /// Converts mx/my/scale to lat/lon (mx/my in meters if correct scale /// is given). static void MercatorToLatLon(double mx, double my, double scale, double &lat, double &lon) { lon = mx * 180.0 / (Math::pi() * EARTH_RADIUS_EQUA * scale); lat = 360.0 * std::atan(std::exp(my / (EARTH_RADIUS_EQUA * scale))) / Math::pi() - 90.0; } /// Adds meters dx/dy to given lat/lon and returns new lat/lon. static void LatLonAddMeters( double lat_start, double lon_start, double dx, double dy, double &lat_end, double &lon_end) { double scale = LatToScale(lat_start); double mx, my; LatLonToMercator(lat_start, lon_start, scale, mx, my); mx += dx; my += dy; MercatorToLatLon(mx, my, scale, lat_end, lon_end); } GeoLocation GeoLocation::Transform(const Location &location) const { GeoLocation result{0.0, 0.0, altitude + location.z}; LatLonAddMeters( latitude, longitude, location.x, location.y, result.latitude, result.longitude); return result; } } // namespace geom } // namespace carla
2,475
906
#include <iostream> #include "include/rules.hpp" #include "include/helper.hpp" int main(int argc, char **argv) { std::ios::sync_with_stdio(false); Game game(BoardSize::SMALL, atoi(argv[1])); while (true) { size_t c, r; game.render(); input_play(game, game.get_turn()); if (game.get_captured().first != 0) { break; } game.next_turn(); } }
427
153
// // Copyright (C) 2014 Haruki Hasegawa // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef CXXDASP_FILTER_TSVF_TSVF_HPP_ #define CXXDASP_FILTER_TSVF_TSVF_HPP_ #include <cxxporthelper/compiler.hpp> #include <cxxdasp/filter/digital_filter.hpp> #include <cxxdasp/filter/tsvf/tsvf_coeffs.hpp> namespace cxxdasp { namespace filter { /** * Linear Trapezoidal Integrated State Variable Filter * * @tparam TFrame audio frame type * @tparam TTSVFCoreOperator core operator class * * @sa "Solving the continuous SVF equations using trapezoidal integration and equivalent currents" * by Andrew Simper <andy@cytomic.com> * http://www.cytomic.com/files/dsp/SvfLinearTrapOptimised2.pdf */ template <typename TFrame, class TTSVFCoreOperator> class trapezoidal_state_variable_filter { /// @cond INTERNAL_FIELD trapezoidal_state_variable_filter(const trapezoidal_state_variable_filter &) = delete; trapezoidal_state_variable_filter &operator=(const trapezoidal_state_variable_filter &) = delete; /// @endcond public: /** * Audio frame type. */ typedef TFrame frame_type; /** * Core operator class. */ typedef TTSVFCoreOperator core_operator_type; /** * Constructor. */ trapezoidal_state_variable_filter(); /** * Destructor. */ ~trapezoidal_state_variable_filter(); /** * Initialize. * @param params [in] general filter parameters * @returns Success or Failure */ bool init(const filter_params_t &params) CXXPH_NOEXCEPT; /** * Initialize. * @param coeffs [in] trapezoidal state variable filter coefficients * @returns Success or Failure */ bool init(const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT; /** * Update filter parameters. * @param params [in] general filter parameters * @returns Success or Failure */ bool update(const filter_params_t &params) CXXPH_NOEXCEPT; /** * Update filter parameters. * @param coeffs [in] trapezoidal state variable filter coefficients * @returns Success or Failure */ bool update(const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT; /** * Reset state. */ void reset() CXXPH_NOEXCEPT; /** * Perform filtering. * @param src_dest [in/out] data buffer (overwrite) * @param n [in] count of samples */ void perform(frame_type *src_dest, int n) CXXPH_NOEXCEPT; /** * Perform filtering. * @param src [in] source data buffer * @param dest [out] destination data buffer * @param n [in] count of samples */ void perform(const frame_type *CXXPH_RESTRICT src, frame_type *CXXPH_RESTRICT dest, int n) CXXPH_NOEXCEPT; private: /// @cond INTERNAL_FIELD core_operator_type core_operator_; /// @endcond }; template <typename TFrame, class TTSVFCoreOperator> inline trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::trapezoidal_state_variable_filter() : core_operator_() { } template <typename TFrame, class TTSVFCoreOperator> inline trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::~trapezoidal_state_variable_filter() { } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::init(const filter_params_t &params) CXXPH_NOEXCEPT { trapezoidal_state_variable_filter_coeffs coeffs; if (!coeffs.make(params)) { return false; } return init(coeffs); } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::init( const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT { core_operator_.set_params(coeffs.a1, coeffs.a2, coeffs.a3, coeffs.m0, coeffs.m1, coeffs.m2); core_operator_.reset(); return true; } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::update(const filter_params_t &params) CXXPH_NOEXCEPT { trapezoidal_state_variable_filter_coeffs coeffs; if (!coeffs.make(params)) { return false; } return update(coeffs); } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::update( const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT { core_operator_.set_params(coeffs.a1, coeffs.a2, coeffs.a3, coeffs.m0, coeffs.m1, coeffs.m2); return true; } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::reset() CXXPH_NOEXCEPT { core_operator_.reset(); } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::perform(frame_type *src_dest, int n) CXXPH_NOEXCEPT { core_operator_.perform(src_dest, n); } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::perform(const frame_type *CXXPH_RESTRICT src, frame_type *CXXPH_RESTRICT dest, int n) CXXPH_NOEXCEPT { core_operator_.perform(src, dest, n); } } // namespace filter } // namespace cxxdasp #endif // CXXDASP_FILTER_TSVF_TSVF_HPP_
6,051
2,055
#include "mainwindow.h" #include "savedialog.h" #include <ui_savedialog.h> #include "ui_mainwindow.h" #include <QtCore> #include <QPainter> #include <QtXml/QtXml> #include <QMessageBox> #include <QMenu> #include <QXmlReader> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->centralWidget->setMinimumWidth(1200); ui->centralWidget->setMinimumHeight(600); int weight=ui->centralWidget->width(); int height=ui->centralWidget->height(); for(int x=0;x+50<=weight;x+=50){ for (int y=0;y+50<=height;y+=50) { QRect rectangle(x,y,50,50); Layout layout; layout.rect = rectangle; layout.color = QColor(255,255,255); layout.xstart=x; layout.ystart=y; layout.xfinish=x+50; layout.yfinish=y+50; m_Layouts.push_back(layout); } } } MainWindow::~MainWindow() { delete ui; appQuit(); } int x1,x2,ybir,yiki; bool presshavepoint=false; SaveDialog *savedialog; void MainWindow::ShowContextMenu(const QPoint &pos) { QMenu contextMenu(tr("Context menu"), this); QAction action1("SAVE", this); connect(&action1, SIGNAL(triggered()),this,SLOT(showInfoDisplay())); contextMenu.addAction(&action1); QAction action2("UNDO",this); connect(&action2,SIGNAL(triggered()),this,SLOT(undo())); contextMenu.addAction(&action2); QAction action3("CLEAR",this); connect(&action3,SIGNAL(triggered()),this,SLOT(clearForm())); contextMenu.addAction(&action3); QAction action4("EXIT",this); connect(&action4,SIGNAL(triggered()),this,SLOT(appQuit())); contextMenu.addAction(&action4); contextMenu.exec(mapToGlobal(pos)); } void MainWindow::undo() { if(createdLayout.size()>0){ int size=createdLayout.size()-1; for (int i=0;i<m_Layouts.size();i++) { if(m_Layouts[i].xstart>=createdLayout[size].xstart && m_Layouts[i].xfinish<=createdLayout[size].xfinish && m_Layouts[i].ystart>=createdLayout[size].ystart && m_Layouts[i].yfinish<=createdLayout[size].yfinish){ m_Layouts[i].dolu=false; } } createdLayout.pop_back(); //delete from createdlayout update(); } else { QMessageBox::information(this,"INFORMATION","FORM IS EMPTY"); } } void MainWindow::showInfoDisplay() { if(createdLayout.size()>0){ savedialog=new SaveDialog(); savedialog->maindialog=this; savedialog->show(); } else{ QMessageBox::information(this,"ERROR","THERE ISN'T ANY LAYOUT"); } } bool ctrlactive=false; void MainWindow::keyPressEvent(QKeyEvent *e) { if(e->key()==16777249){ //press ctrl ctrlactive=true; } else if (e->key()==90) { //press z if(ctrlactive){ undo(); } } else if (e->key()==83) { //press s if(ctrlactive){ showInfoDisplay(); } } else if (e->key()==67) { //press c if(ctrlactive){ clearForm(); } } else if (e->key()==69) { //press e if(ctrlactive){ appQuit(); } } } void MainWindow::keyReleaseEvent(QKeyEvent *e) { if(e->key()==16777249){ //release ctrl ctrlactive=false; } } void MainWindow::appQuit() { QApplication::quit(); } void MainWindow::clearForm() { if(createdLayout.size()>0){ createdLayout.clear(); for (int i=0;i<m_Layouts.size();i++){ m_Layouts[i].dolu=false; } update(); } else { QMessageBox::information(this,"INFORMATION","AREA IS ALREADY EMPTY !!!"); } } bool MainWindow::areaControl(int xstart,int xfinish,int ystart,int yfinish) { for (int i=0;i<m_Layouts.size();i++) { if(m_Layouts[i].xstart>=xstart && m_Layouts[i].xfinish<=xfinish && m_Layouts[i].ystart>=ystart && m_Layouts[i].yfinish<=yfinish){ if(m_Layouts[i].dolu==true) return false; } } return true; } void MainWindow::paintEvent(QPaintEvent *event){ QPainter painter(this); QPen pen; pen.setColor(Qt::blue); pen.setWidth(3); painter.setPen(pen); for(int i=0;i<m_Layouts.size();i++){ painter.drawRect(m_Layouts[i].rect); painter.fillRect(m_Layouts[i].rect,m_Layouts[i].color); } for (int i=0;i<createdLayout.size();i++) { painter.drawRect(createdLayout[i].rect); painter.fillRect(createdLayout[i].rect,createdLayout[i].color); } if(templayout.isActive){ painter.drawRect(templayout.rect); } } void MainWindow::mousePressEvent(QMouseEvent *event) { if(event->button()==Qt::RightButton){ ShowContextMenu(event->pos()); } if(event->button() == Qt::LeftButton){ templayout.isActive=true; templayout.xstart=event->x(); templayout.ystart=event->y(); if(point_control(event->x(),event->y())){ presshavepoint=false; for (int i=0;i<m_Layouts.size();i++) { if(m_Layouts[i].xstart<event->x() && m_Layouts[i].xfinish>event->x() && m_Layouts[i].ystart<event->y() && m_Layouts[i].yfinish>event->y()){ x1=m_Layouts[i].xstart; ybir=m_Layouts[i].ystart; } } } else { presshavepoint=true; } } } void MainWindow::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton){ templayout.isActive=false; if(presshavepoint==false){ if(point_control(event->x(),event->y())){ for (int i=0;i<m_Layouts.size();i++) { if(m_Layouts[i].xstart<event->x() && m_Layouts[i].xfinish>event->x() && m_Layouts[i].ystart<event->y() && m_Layouts[i].yfinish>event->y()){ x2=m_Layouts[i].xfinish; yiki=m_Layouts[i].yfinish; //swapping if(x1>=x2){ int temp=x2; x2=x1+50; x1=temp-50; } if(ybir>=yiki){ int temp=yiki; yiki=ybir+50; ybir=temp-50; } if(areaControl(x1,x2,ybir,yiki)){ for (int j=0;j<m_Layouts.size();j++) { if(m_Layouts[j].xstart>=x1 && m_Layouts[j].xfinish<=x2 && m_Layouts[j].ystart>=ybir && m_Layouts[j].yfinish<=yiki){ m_Layouts[j].dolu=true; } } QRect rectangle(x1,ybir,(x2-x1),(yiki-ybir)); Layout layout; layout.rect = rectangle; layout.color = QColor(rand() % 255,rand() % 255,rand() % 255); layout.xstart=x1; layout.ystart=ybir; layout.xfinish=x2; layout.yfinish=yiki; createdLayout.push_back(layout); update(); //for paintevent running } else { QMessageBox::information(this,"ERROR","AREA IS NOT EMPTY !!!"); } } } } else { QMessageBox::information(this,"ERROR","LAST COORD IS FULL !!!"); } } else { QMessageBox::information(this,"ERROR","FIRST COORD IS FULL !!!"); } } } void MainWindow::mouseMoveEvent(QMouseEvent *event) { if(templayout.isActive){ QRect rectangle(templayout.xstart,templayout.ystart, (event->x()-templayout.xstart),(event->y()-templayout.ystart)); templayout.rect=rectangle; update(); } } bool MainWindow::point_control(int x, int y) { for (int i=0;i<m_Layouts.size();i++) { if(m_Layouts[i].xstart<x && m_Layouts[i].xfinish>x && m_Layouts[i].ystart<y && m_Layouts[i].yfinish>y){ if (m_Layouts[i].dolu==false) { return true; } else { return false; } } } } void MainWindow::XML_Save(QString name,QString shortcut,int ontoolbar) { QFile file("C:/Qt/examples/infodif/MyXML.xml"); QDomDocument document; if(file.open(QIODevice::ReadOnly | QIODevice::Text)){ document.setContent(&file); file.close(); } QDomElement xmlroot=document.firstChildElement(); document.appendChild(xmlroot); //QDomElement root=document.createElement("Layouts"); //for first running //document.appendChild(root); //first element must be "layouts" QDomElement layout=document.createElement("Layout"); layout.setAttribute("name",name); layout.setAttribute("short_cut",shortcut); layout.setAttribute("on_tool_bar",ontoolbar); xmlroot.appendChild(layout); for (int i = 0; i < createdLayout.size(); i++) { QDomElement position=document.createElement("Position"); position.setAttribute("number",QString::number(i)); position.setAttribute("row",createdLayout[i].ystart); position.setAttribute("column",createdLayout[i].xstart); position.setAttribute("row_span",(createdLayout[i].xfinish-createdLayout[i].xstart)); position.setAttribute("column_span",(createdLayout[i].yfinish-createdLayout[i].ystart)); layout.appendChild(position); } if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){ QMessageBox::information(this,"ERROR","FILE DIDN'T OPEN !"); } else { QTextStream stream(&file); stream<<document.toString(); file.close(); QMessageBox::information(this,"INFORMATION","SUCCESFULLY"); } }
10,855
3,571
/* 21. Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/ Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. */ /* Solution: -> Simple and short recursive code that works by pointer manipulation. -> Uses O(1) space apart from stack usage of recursive function calls */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1 -> val < l2 -> val){ l1 -> next = mergeTwoLists(l1 -> next, l2); return l1; } else{ l2 -> next = mergeTwoLists(l1, l2 -> next); return l2; } } };
723
268
/* Copyright 2017-2018 ccls 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. ==============================================================================*/ #pragma once #include "config.hh" #include "lsp.hh" #include <functional> #include <mutex> #include <string> #include <unordered_map> #include <vector> namespace ccls { struct WorkingFiles; std::pair<LanguageId, bool> lookupExtension(std::string_view filename); struct Project { struct Entry { std::string root; std::string directory; std::string filename; std::vector<const char *> args; // If true, this entry is inferred and was not read from disk. bool is_inferred = false; int id = -1; }; struct Folder { std::string name; // Include directories for <> headers std::vector<std::string> angle_search_list; // Include directories for "" headers std::vector<std::string> quote_search_list; std::vector<Entry> entries; std::unordered_map<std::string, int> path2entry_index; }; std::mutex mutex_; std::unordered_map<std::string, Folder> root2folder; // Loads a project for the given |directory|. // // If |config->compilationDatabaseDirectory| is not empty, look for .ccls or // compile_commands.json in it, otherwise they are retrieved in // |root_directory|. // For .ccls, recursive directory listing is used and files with known // suffixes are indexed. .ccls files can exist in subdirectories and they // will affect flags in their subtrees (relative paths are relative to the // project root, not subdirectories). For compile_commands.json, its entries // are indexed. void Load(const std::string &root_directory); // Lookup the CompilationEntry for |filename|. If no entry was found this // will infer one based on existing project structure. Entry FindEntry(const std::string &path, bool can_be_inferred); // If the client has overridden the flags, or specified them for a file // that is not in the compilation_database.json make sure those changes // are permanent. void SetArgsForFile(const std::vector<const char *> &args, const std::string &path); void Index(WorkingFiles *wfiles, RequestId id); }; } // namespace ccls
2,711
786
#include "node.hpp" #include "cmd.hpp" #include <iostream> #include <string> int main(int argc, char** argv) { bool quit = false; tree_node* root = nullptr; while(!quit) { std::string input = ""; std::cout << ">"; std::cin >> input; tree_cmd cmd = parse_command(input); switch (cmd) { case tree_cmd::create: if (root) { std::cout << "Existing Tree. See \"reset\" command." << std::endl; } else { root = tree_node::build_tree(); } break; case tree_cmd::load: if (root) { std::cout << "Existing Tree. See \"reset\" command." << std::endl; } else { root = tree_node::build_tree(); } break; case tree_cmd::print: if (root) { std::cout << root << std::endl; } else { std::cout << "No tree. See \"create\" or \"load\" commands." << std::endl; } break; case tree_cmd::quit: tree_node::destroy_node(root); quit = true; break; case tree_cmd::reset: tree_node::destroy_node(root); break; case tree_cmd::edit: break; default: std::cout << "Invalid command." << std::endl; } } return 0; }
1,734
442
#ifndef FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP #define FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP #include <falcon/type_traits/use_def.hpp> namespace falcon { namespace _aux { FALCON_USE_XXX_TRAIT_NAMED_DEF(difference_type, use_difference_type); } template <class T> struct use_difference_type : _aux::use_difference_type<T> {}; } #endif
338
149
/* Boot selection menu * * Initial author: Floris Bos * Maintained by Raspberry Pi * * See LICENSE.txt for license details * */ #include "bootselectiondialog.h" #include "ui_bootselectiondialog.h" #include "config.h" #include "json.h" #include "util.h" #include <QDir> #include <QMessageBox> #include <QProcess> #include <QListWidgetItem> #include <QPushButton> #include <QTimer> #include <QSettings> #include <QDesktopWidget> #include <QScreen> #include <QWSServer> #include <QDebug> BootSelectionDialog::BootSelectionDialog(const QString &defaultPartition, QWidget *parent) : QDialog(parent), _countdown(11), ui(new Ui::BootSelectionDialog) { setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint); ui->setupUi(this); QRect s = QApplication::desktop()->screenGeometry(); if (s.height() < 500) resize(s.width()-10, s.height()-100); QDir dir; dir.mkdir("/settings"); if (QProcess::execute("mount -o remount,ro /settings") != 0 && QProcess::execute("mount -t ext4 -o ro " SETTINGS_PARTITION " /settings") != 0) { QMessageBox::critical(this, tr("Cannot display boot menu"), tr("Error mounting settings partition")); return; } /* Also mount /dev/mmcblk0p1 as it may contain icons we need */ if (QProcess::execute("mount -t vfat -o ro /dev/mmcblk0p1 /mnt") != 0) { /* Not fatal if this fails */ } QVariantList installed_os = Json::loadFromFile("/settings/installed_os.json").toList(); QSize currentsize = ui->list->iconSize(); foreach (QVariant v, installed_os) { QVariantMap m = v.toMap(); QString iconfilename = m.value("icon").toString(); QIcon icon; if (!iconfilename.isEmpty() && QFile::exists(iconfilename)) { icon = QIcon(iconfilename); QList<QSize> avs = icon.availableSizes(); if (avs.isEmpty()) { /* Icon file corrupt */ icon = QIcon(); } else { QSize iconsize = avs.first(); if (iconsize.width() > currentsize.width() || iconsize.height() > currentsize.height()) { /* Make all icons as large as the largest icon we have */ currentsize = QSize(qMax(iconsize.width(), currentsize.width()),qMax(iconsize.height(), currentsize.height())); ui->list->setIconSize(currentsize); } } } if (canBootOs(m.value("name").toString(), m)) { QListWidgetItem *item = new QListWidgetItem(icon, m.value("name").toString()+"\n"+m.value("description").toString(), ui->list); item->setData(Qt::UserRole, m); } } if (ui->list->count() != 0) { // If default boot partition set then boot to that after 5 seconds QSettings settings("/settings/noobs.conf", QSettings::IniFormat, this); int partition = settings.value("default_partition_to_boot", defaultPartition).toInt(); if (partition != 800) { // Start timer qDebug() << "Starting 10 second timer before booting into partition" << partition; _timer.setInterval(1000); connect(&_timer, SIGNAL(timeout()), this, SLOT(countdown())); _timer.start(); countdown(); ui->list->installEventFilter(this); // Select OS booted previously QByteArray partstr = "/dev/mmcblk0p"+QByteArray::number(partition); for (int i=0; i<ui->list->count(); i++) { QVariantMap m = ui->list->item(i)->data(Qt::UserRole).toMap(); if (m.value("partitions").toList().first() == partstr) { ui->list->setCurrentRow(i); break; } } } else { ui->list->setCurrentRow(0); } } if (ui->list->count() == 1) { // Only one OS, boot that qDebug() << "accepting"; QTimer::singleShot(1, this, SLOT(accept())); } } BootSelectionDialog::~BootSelectionDialog() { delete ui; } void BootSelectionDialog::bootPartition() { QSettings settings("/settings/noobs.conf", QSettings::IniFormat, this); QByteArray partition = settings.value("default_partition_to_boot", 800).toByteArray(); qDebug() << "Booting partition" << partition; setRebootPartition(partition); QDialog::accept(); } void BootSelectionDialog::accept() { QListWidgetItem *item = ui->list->currentItem(); if (!item) return; QSettings settings("/settings/noobs.conf", QSettings::IniFormat, this); QVariantMap m = item->data(Qt::UserRole).toMap(); QByteArray partition = m.value("partitions").toList().first().toByteArray(); partition.replace("/dev/mmcblk0p", ""); int partitionNr = partition.toInt(); int oldpartitionNr = settings.value("default_partition_to_boot", 0).toInt(); if (partitionNr != oldpartitionNr) { // Save OS boot choice as the new default QProcess::execute("mount -o remount,rw /settings"); settings.setValue("default_partition_to_boot", partitionNr); settings.sync(); QProcess::execute("mount -o remount,ro /settings"); } bootPartition(); } void BootSelectionDialog::on_list_activated(const QModelIndex &) { accept(); } void BootSelectionDialog::setDisplayMode() { #ifdef Q_WS_QWS QString cmd, mode; QSettings settings("/settings/noobs.conf", QSettings::IniFormat, this); /* Restore saved display mode */ int modenr = settings.value("display_mode", 0).toInt(); switch (modenr) { case 1: cmd = "-e \'DMT 4 DVI\'"; mode = tr("HDMI safe mode"); break; case 2: cmd = "-c \'PAL 4:3\'"; mode = tr("composite PAL mode"); break; case 3: cmd = "-c \'NTSC 4:3\'"; mode = tr("composite NTSC mode"); break; default: return; } // Trigger framebuffer resize QProcess *presize = new QProcess(this); presize->start(QString("sh -c \"tvservice -o; tvservice %1;\"").arg(cmd)); presize->waitForFinished(4000); // Update screen resolution with current value (even if we didn't // get what we thought we'd get) QProcess *update = new QProcess(this); update->start(QString("sh -c \"tvservice -s | cut -d , -f 2 | cut -d \' \' -f 2 | cut -d x -f 1;tvservice -s | cut -d , -f 2 | cut -d \' \' -f 2 | cut -d x -f 2\"")); update->waitForFinished(4000); update->setProcessChannelMode(QProcess::MergedChannels); QTextStream stream(update); int xres = stream.readLine().toInt(); int yres = stream.readLine().toInt(); int oTop = 0, oBottom = 0, oLeft = 0, oRight = 0; getOverscan(oTop, oBottom, oLeft, oRight); QScreen::instance()->setMode(xres-oLeft-oRight, yres-oTop-oBottom, 16); // Update UI item locations QRect s = QApplication::desktop()->screenGeometry(); if (s.height() < 400) resize(s.width()-10, s.height()-100); setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), qApp->desktop()->availableGeometry())); // Refresh screen qApp->processEvents(); QWSServer::instance()->refresh(); #endif } bool BootSelectionDialog::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::MouseButtonPress) { stopCountdown(); } return QDialog::eventFilter(obj, event); } void BootSelectionDialog::stopCountdown() { _timer.stop(); setWindowTitle(tr("Select OS to boot")); } void BootSelectionDialog::countdown() { setWindowTitle(tr("Previously selected OS will boot in %1 seconds").arg(--_countdown)); if (_countdown == 0) { _timer.stop(); bootPartition(); } }
7,985
2,548
// 16. 3Sum Closest // https://leetcode.com/problems/3sum-closest/ #include <algorithm> #include <climits> #include <iostream> #include <numeric> #include <vector> #include "leetcode_util.h" using namespace std; class Solution { public: int threeSumClosest(vector<int> & nums, int target) { if (nums.size() <= 3) return accumulate(nums.begin(), nums.end(), 0); sort(nums.begin(), nums.end()); int sum = 0, new_sum = 0, delta = INT_MAX, new_delta = INT_MAX; auto i = nums.begin(), j = i, k = i, nums_end = nums.end(); for (; i != nums_end; ++i) for (j = i + 1; j != nums_end; ++j) for (k = j + 1; k != nums_end; ++k) { if (delta == 0) return target; new_sum = *i + *j + *k; new_delta = abs(new_sum - target); if (new_delta < delta) { sum = new_sum; delta = new_delta; continue; } if (new_sum - target > 0) break; } return sum; } }; int main() { Solution sol; vector<pair<vector<int>, int>> data = { {{1,2,3},4}, {{1,2,5},4}, {{1,2,5,2},4}, {{0},1}, {{29,16,92,56,25,62,59,31,-52,-57,100,-68,-33,-93,-77,31,7,-44,-52,-30,-72,71,16,-68,-1,67,-58,21,-7,-90,-67,59,-38,-19,13,70,37,16,-86,25,-20,87,61,80,16,33,-50,48,-44,9}, 23}, {{0,7,-4,-7,0,14,-6,-4,-12,11,4,9,7,4,-10,8,10,5,4,14,6,0,-9,5,6,6,-11,1,-8,-1,2,-1,13,5,-1,-2,4,9,9,-1,-3,-1,-7,11,10,-2,-4,5,10,-15,-4,-6,-8,2,14,13,-7,11,-9,-8,-13,0,-1,-15,-10,13,-2,1,-1,-15,7,3,-9,7,-1,-14,-10,2,6,8,-6,-12,-13,1,-3,8,-9,-2,4,-2,-3,6,5,11,6,11,10,12,-11,-14}, 133}, }; for (auto i: data) { cout << leetcode::to_string(sol.threeSumClosest(i.first, i.second)) << endl; } }
1,913
895
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ #include <node.h> #include "keymapping.h" namespace vscode_keyboard { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Array; using v8::Value; void AddEntry(Isolate* isolate, std::vector<Local<Object>> &result, std::string key_code, Local<String> value, Local<String> withShift, Local<String> withAltGr, Local<String> withShiftAltGr) { Local<Object> entry = Object::New(isolate); entry->Set(String::NewFromUtf8(isolate, "key_code"), String::NewFromUtf8(isolate, key_code.c_str())); entry->Set(String::NewFromUtf8(isolate, "value"), value); entry->Set(String::NewFromUtf8(isolate, "withShift"), withShift); entry->Set(String::NewFromUtf8(isolate, "withAltGr"), withAltGr); entry->Set(String::NewFromUtf8(isolate, "withShiftAltGr"), withShiftAltGr); result.push_back(entry); } void GenerateEntries(Isolate* isolate, std::vector<Local<Object>> &result, std::vector<KeyMapping>::iterator it) { if (it->value.length() == 0 && it->withShift.length() == 0 && it->withAltGr.length() == 0 && it->withShiftAltGr.length() == 0) { return; } Local<String> value = String::NewFromUtf8(isolate, it->value.c_str()); Local<String> withShift = String::NewFromUtf8(isolate, it->withShift.c_str()); Local<String> withAltGr = String::NewFromUtf8(isolate, it->withAltGr.c_str()); Local<String> withShiftAltGr = String::NewFromUtf8(isolate, it->withShiftAltGr.c_str()); ui::KeyboardCode key_code = it->key_code; if (key_code == ui::KeyboardCode::VKEY_BACK) AddEntry(isolate, result, "VKEY_BACK", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_TAB) AddEntry(isolate, result, "VKEY_TAB", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_CLEAR) AddEntry(isolate, result, "VKEY_CLEAR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RETURN) AddEntry(isolate, result, "VKEY_RETURN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SHIFT) AddEntry(isolate, result, "VKEY_SHIFT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_CONTROL) AddEntry(isolate, result, "VKEY_CONTROL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MENU) AddEntry(isolate, result, "VKEY_MENU", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PAUSE) AddEntry(isolate, result, "VKEY_PAUSE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_CAPITAL) AddEntry(isolate, result, "VKEY_CAPITAL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_KANA) AddEntry(isolate, result, "VKEY_KANA", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_HANGUL) AddEntry(isolate, result, "VKEY_HANGUL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_JUNJA) AddEntry(isolate, result, "VKEY_JUNJA", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_FINAL) AddEntry(isolate, result, "VKEY_FINAL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_HANJA) AddEntry(isolate, result, "VKEY_HANJA", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_KANJI) AddEntry(isolate, result, "VKEY_KANJI", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ESCAPE) AddEntry(isolate, result, "VKEY_ESCAPE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_CONVERT) AddEntry(isolate, result, "VKEY_CONVERT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NONCONVERT) AddEntry(isolate, result, "VKEY_NONCONVERT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ACCEPT) AddEntry(isolate, result, "VKEY_ACCEPT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MODECHANGE) AddEntry(isolate, result, "VKEY_MODECHANGE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SPACE) AddEntry(isolate, result, "VKEY_SPACE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PRIOR) AddEntry(isolate, result, "VKEY_PRIOR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NEXT) AddEntry(isolate, result, "VKEY_NEXT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_END) AddEntry(isolate, result, "VKEY_END", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_HOME) AddEntry(isolate, result, "VKEY_HOME", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_LEFT) AddEntry(isolate, result, "VKEY_LEFT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_UP) AddEntry(isolate, result, "VKEY_UP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RIGHT) AddEntry(isolate, result, "VKEY_RIGHT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DOWN) AddEntry(isolate, result, "VKEY_DOWN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SELECT) AddEntry(isolate, result, "VKEY_SELECT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PRINT) AddEntry(isolate, result, "VKEY_PRINT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_EXECUTE) AddEntry(isolate, result, "VKEY_EXECUTE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SNAPSHOT) AddEntry(isolate, result, "VKEY_SNAPSHOT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_INSERT) AddEntry(isolate, result, "VKEY_INSERT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DELETE) AddEntry(isolate, result, "VKEY_DELETE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_HELP) AddEntry(isolate, result, "VKEY_HELP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_0) AddEntry(isolate, result, "VKEY_0", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_1) AddEntry(isolate, result, "VKEY_1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_2) AddEntry(isolate, result, "VKEY_2", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_3) AddEntry(isolate, result, "VKEY_3", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_4) AddEntry(isolate, result, "VKEY_4", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_5) AddEntry(isolate, result, "VKEY_5", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_6) AddEntry(isolate, result, "VKEY_6", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_7) AddEntry(isolate, result, "VKEY_7", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_8) AddEntry(isolate, result, "VKEY_8", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_9) AddEntry(isolate, result, "VKEY_9", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_A) AddEntry(isolate, result, "VKEY_A", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_B) AddEntry(isolate, result, "VKEY_B", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_C) AddEntry(isolate, result, "VKEY_C", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_D) AddEntry(isolate, result, "VKEY_D", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_E) AddEntry(isolate, result, "VKEY_E", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F) AddEntry(isolate, result, "VKEY_F", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_G) AddEntry(isolate, result, "VKEY_G", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_H) AddEntry(isolate, result, "VKEY_H", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_I) AddEntry(isolate, result, "VKEY_I", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_J) AddEntry(isolate, result, "VKEY_J", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_K) AddEntry(isolate, result, "VKEY_K", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_L) AddEntry(isolate, result, "VKEY_L", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_M) AddEntry(isolate, result, "VKEY_M", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_N) AddEntry(isolate, result, "VKEY_N", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_O) AddEntry(isolate, result, "VKEY_O", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_P) AddEntry(isolate, result, "VKEY_P", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_Q) AddEntry(isolate, result, "VKEY_Q", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_R) AddEntry(isolate, result, "VKEY_R", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_S) AddEntry(isolate, result, "VKEY_S", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_T) AddEntry(isolate, result, "VKEY_T", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_U) AddEntry(isolate, result, "VKEY_U", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_V) AddEntry(isolate, result, "VKEY_V", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_W) AddEntry(isolate, result, "VKEY_W", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_X) AddEntry(isolate, result, "VKEY_X", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_Y) AddEntry(isolate, result, "VKEY_Y", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_Z) AddEntry(isolate, result, "VKEY_Z", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_LWIN) AddEntry(isolate, result, "VKEY_LWIN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_COMMAND) AddEntry(isolate, result, "VKEY_COMMAND", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RWIN) AddEntry(isolate, result, "VKEY_RWIN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_APPS) AddEntry(isolate, result, "VKEY_APPS", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SLEEP) AddEntry(isolate, result, "VKEY_SLEEP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD0) AddEntry(isolate, result, "VKEY_NUMPAD0", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD1) AddEntry(isolate, result, "VKEY_NUMPAD1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD2) AddEntry(isolate, result, "VKEY_NUMPAD2", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD3) AddEntry(isolate, result, "VKEY_NUMPAD3", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD4) AddEntry(isolate, result, "VKEY_NUMPAD4", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD5) AddEntry(isolate, result, "VKEY_NUMPAD5", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD6) AddEntry(isolate, result, "VKEY_NUMPAD6", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD7) AddEntry(isolate, result, "VKEY_NUMPAD7", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD8) AddEntry(isolate, result, "VKEY_NUMPAD8", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMPAD9) AddEntry(isolate, result, "VKEY_NUMPAD9", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MULTIPLY) AddEntry(isolate, result, "VKEY_MULTIPLY", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ADD) AddEntry(isolate, result, "VKEY_ADD", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SEPARATOR) AddEntry(isolate, result, "VKEY_SEPARATOR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SUBTRACT) AddEntry(isolate, result, "VKEY_SUBTRACT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DECIMAL) AddEntry(isolate, result, "VKEY_DECIMAL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DIVIDE) AddEntry(isolate, result, "VKEY_DIVIDE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F1) AddEntry(isolate, result, "VKEY_F1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F2) AddEntry(isolate, result, "VKEY_F2", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F3) AddEntry(isolate, result, "VKEY_F3", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F4) AddEntry(isolate, result, "VKEY_F4", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F5) AddEntry(isolate, result, "VKEY_F5", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F6) AddEntry(isolate, result, "VKEY_F6", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F7) AddEntry(isolate, result, "VKEY_F7", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F8) AddEntry(isolate, result, "VKEY_F8", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F9) AddEntry(isolate, result, "VKEY_F9", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F10) AddEntry(isolate, result, "VKEY_F10", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F11) AddEntry(isolate, result, "VKEY_F11", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F12) AddEntry(isolate, result, "VKEY_F12", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F13) AddEntry(isolate, result, "VKEY_F13", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F14) AddEntry(isolate, result, "VKEY_F14", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F15) AddEntry(isolate, result, "VKEY_F15", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F16) AddEntry(isolate, result, "VKEY_F16", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F17) AddEntry(isolate, result, "VKEY_F17", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F18) AddEntry(isolate, result, "VKEY_F18", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F19) AddEntry(isolate, result, "VKEY_F19", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F20) AddEntry(isolate, result, "VKEY_F20", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F21) AddEntry(isolate, result, "VKEY_F21", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F22) AddEntry(isolate, result, "VKEY_F22", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F23) AddEntry(isolate, result, "VKEY_F23", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_F24) AddEntry(isolate, result, "VKEY_F24", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NUMLOCK) AddEntry(isolate, result, "VKEY_NUMLOCK", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_SCROLL) AddEntry(isolate, result, "VKEY_SCROLL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_LSHIFT) AddEntry(isolate, result, "VKEY_LSHIFT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RSHIFT) AddEntry(isolate, result, "VKEY_RSHIFT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_LCONTROL) AddEntry(isolate, result, "VKEY_LCONTROL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RCONTROL) AddEntry(isolate, result, "VKEY_RCONTROL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_LMENU) AddEntry(isolate, result, "VKEY_LMENU", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_RMENU) AddEntry(isolate, result, "VKEY_RMENU", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_BACK) AddEntry(isolate, result, "VKEY_BROWSER_BACK", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_FORWARD) AddEntry(isolate, result, "VKEY_BROWSER_FORWARD", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_REFRESH) AddEntry(isolate, result, "VKEY_BROWSER_REFRESH", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_STOP) AddEntry(isolate, result, "VKEY_BROWSER_STOP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_SEARCH) AddEntry(isolate, result, "VKEY_BROWSER_SEARCH", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_FAVORITES) AddEntry(isolate, result, "VKEY_BROWSER_FAVORITES", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_BROWSER_HOME) AddEntry(isolate, result, "VKEY_BROWSER_HOME", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_VOLUME_MUTE) AddEntry(isolate, result, "VKEY_VOLUME_MUTE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_VOLUME_DOWN) AddEntry(isolate, result, "VKEY_VOLUME_DOWN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_VOLUME_UP) AddEntry(isolate, result, "VKEY_VOLUME_UP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_NEXT_TRACK) AddEntry(isolate, result, "VKEY_MEDIA_NEXT_TRACK", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_PREV_TRACK) AddEntry(isolate, result, "VKEY_MEDIA_PREV_TRACK", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_STOP) AddEntry(isolate, result, "VKEY_MEDIA_STOP", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_PLAY_PAUSE) AddEntry(isolate, result, "VKEY_MEDIA_PLAY_PAUSE", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_LAUNCH_MAIL) AddEntry(isolate, result, "VKEY_MEDIA_LAUNCH_MAIL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_LAUNCH_MEDIA_SELECT) AddEntry(isolate, result, "VKEY_MEDIA_LAUNCH_MEDIA_SELECT", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_LAUNCH_APP1) AddEntry(isolate, result, "VKEY_MEDIA_LAUNCH_APP1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_MEDIA_LAUNCH_APP2) AddEntry(isolate, result, "VKEY_MEDIA_LAUNCH_APP2", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_1) AddEntry(isolate, result, "VKEY_OEM_1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_PLUS) AddEntry(isolate, result, "VKEY_OEM_PLUS", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_COMMA) AddEntry(isolate, result, "VKEY_OEM_COMMA", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_MINUS) AddEntry(isolate, result, "VKEY_OEM_MINUS", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_PERIOD) AddEntry(isolate, result, "VKEY_OEM_PERIOD", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_2) AddEntry(isolate, result, "VKEY_OEM_2", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_3) AddEntry(isolate, result, "VKEY_OEM_3", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_4) AddEntry(isolate, result, "VKEY_OEM_4", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_5) AddEntry(isolate, result, "VKEY_OEM_5", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_6) AddEntry(isolate, result, "VKEY_OEM_6", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_7) AddEntry(isolate, result, "VKEY_OEM_7", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_8) AddEntry(isolate, result, "VKEY_OEM_8", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_102) AddEntry(isolate, result, "VKEY_OEM_102", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PROCESSKEY) AddEntry(isolate, result, "VKEY_PROCESSKEY", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PACKET) AddEntry(isolate, result, "VKEY_PACKET", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DBE_SBCSCHAR) AddEntry(isolate, result, "VKEY_DBE_SBCSCHAR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_DBE_DBCSCHAR) AddEntry(isolate, result, "VKEY_DBE_DBCSCHAR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ATTN) AddEntry(isolate, result, "VKEY_ATTN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_CRSEL) AddEntry(isolate, result, "VKEY_CRSEL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_EXSEL) AddEntry(isolate, result, "VKEY_EXSEL", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_EREOF) AddEntry(isolate, result, "VKEY_EREOF", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PLAY) AddEntry(isolate, result, "VKEY_PLAY", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ZOOM) AddEntry(isolate, result, "VKEY_ZOOM", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_NONAME) AddEntry(isolate, result, "VKEY_NONAME", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_PA1) AddEntry(isolate, result, "VKEY_PA1", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_OEM_CLEAR) AddEntry(isolate, result, "VKEY_OEM_CLEAR", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_UNKNOWN) AddEntry(isolate, result, "VKEY_UNKNOWN", value, withShift, withAltGr, withShiftAltGr); if (key_code == ui::KeyboardCode::VKEY_ALTGR) AddEntry(isolate, result, "VKEY_ALTGR", value, withShift, withAltGr, withShiftAltGr); } void GetKeyMap(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); std::vector<KeyMapping> mapping = GetKeyMapping(); std::vector<Local<Object>> result; for(std::vector<KeyMapping>::iterator it = mapping.begin(); it != mapping.end(); ++it) { GenerateEntries(isolate, result, it); } int resultCount = (int)result.size(); Local<Array> resultArr = Array::New(isolate, resultCount); for (int index = 0; index < resultCount; index++) { resultArr->Set(index, result[index]); } args.GetReturnValue().Set(resultArr); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "getKeyMap", GetKeyMap); } NODE_MODULE(addon, init) } // namespace vscode_keyboard
26,297
9,989
/* RandomSynthesizer.hpp randomly copy from source to target; good for initialization Li-Yi Wei August 17, 2014 */ #ifndef _RANDOM_SYNTHESIZER_HPP #define _RANDOM_SYNTHESIZER_HPP #include "Synthesizer.hpp" class RandomSynthesizer : public Synthesizer { public: RandomSynthesizer(const Texture & source); virtual ~RandomSynthesizer(void); virtual string Synthesize(const Position & position, Texture & target) const; protected: const Texture & _source; }; #endif
495
176
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "op_table.hpp" #include "openvino/opsets/opset8.hpp" using namespace std; using namespace ov::opset8; namespace ov { namespace frontend { namespace tensorflow { namespace op { OutputVector translate_slice_op(const NodeContext& node) { auto input = node.get_input(0); auto start = node.get_input(1); auto size = node.get_input(2); auto stop = make_shared<Add>(start, size); auto one = make_shared<Constant>(element::i64, Shape{1}, 1); auto shape = make_shared<ShapeOf>(start); auto step = make_shared<Broadcast>(one, shape); auto res = make_shared<Slice>(input, start, stop, step); set_node_name(node.get_name(), res); return res->outputs(); } } // namespace op } // namespace tensorflow } // namespace frontend } // namespace ov
876
302
#include <iostream> int main() { // 1 Byte = 8bit bool my_value0 = true; // false // 1 Byte = 8bit char my_value1 = 10; // 2 Byte = 16bit short my_value2 = 42; // 4 Byte = 32bit int my_value3 = 22; // 4 Byte = 32bit float my_value4 = 12.0f; // 8 Byte = 64bit double my_value5 = 13.0; return 0; }
355
169
#include <iostream.h> #include "DisjSets.h" // Test main; all finds on same output line should be identical int main( ) { int numElements = 128; int numInSameSet = 16; DisjSets ds( numElements ); int set1, set2; for( int k = 1; k < numInSameSet; k *= 2 ) { for( int j = 0; j + k < numElements; j += 2 * k ) { set1 = ds.find( j ); set2 = ds.find( j + k ); ds.unionSets( set1, set2 ); } } for( int i = 0; i < numElements; i++ ) { cout << ds.find( i ) << "*"; if( i % numInSameSet == numInSameSet - 1 ) cout << endl; } cout << endl; return 0; }
899
276
/*****************************************************************************\ Copyright (c) 2011-2017 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 <cstdlib> #include <ctime> #include <cstdio> #include <conio.h> #include <cstdarg> #include <mutex> #include <set> #include "utilities.h" bool verboseOutput = true; // printf is only guaranteed to handle strings up to this length. // The Microsoft compiler handles much more than this, but // we want this to be as portable as reasonably possible. const int MAX_PRINTF_STRLEN = 4095; static char formatBuffer[MAX_PRINTF_STRLEN + 1]; static std::mutex formatMutex; #define FORMAT(fmt, buffer, bufflen) \ va_list argptr; \ va_start(argptr, fmt); \ int num_required = vsnprintf((buffer), (bufflen), (fmt), argptr); \ va_end(argptr); \ Assert(num_required < bufflen) /***********************************************\ Console output can slow a program down a lot. This is a printf-substitute that can be turned on or off. Use this only for stuff that you want to suppress when running flat-out for speed. Use plain-old printf for stuff that you want to always be printed. \***********************************************/ void prn(const char* fmt, ...) { if(!verboseOutput) return; std::lock_guard<std::mutex> lock{ formatMutex }; FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN); printf("%s", formatBuffer); } /***********************************************\ Because printf-style formatting is just too nice to do without. \***********************************************/ std::string formatString(const char* fmt, ...) { std::lock_guard<std::mutex> lock{ formatMutex }; FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN); std::string result(formatBuffer); return result; } /*****************************************************************************\ Return the size of the given file, or zero if the file can't be obtained \*****************************************************************************/ size_t getFileSize(const char* filename) { struct stat st; if (stat(filename, &st) != 0) { return 0; } return st.st_size; } /*****************************************************************************\ Load the given file into a single contiguous string. This function won't return if the load operation fails. It will fail for the usual reasons file operations fail, or if the file contains embedded zeros or characters that won't fit in a signed char. \*****************************************************************************/ std::string loadText(const char* fname) { std::string result; size_t size = getFileSize(fname); if(size > result.max_size()) { failf("File %s is too large for a single string", fname); } if(size == 0) { failf("Failure loading text file %s\n", fname); } // We use "rb" because we want an exact copy, with no // line ending translation. FILE* fp = fopen(fname, "rb"); if (!fp) { failf("Failure loading text file %s\n", fname); } result.reserve(size); char c = fgetc(fp); int charnum = 0; while(!feof(fp)) { if(c == 0) { failf("File contains embedded zero character in position %d\n", charnum); } if (c > 0x7E) { failf("Text contains non-printing character: (char)%d in character #%d\n", c, charnum); } result.push_back(c); c = fgetc(fp); charnum++; } return result; } /*****************************************************************************\ A simple, quick checksum, not intended for security or UUID purposes. \*****************************************************************************/ int checksum(const std::string& str) { int result = 0; for(auto c : str) { result += c; } return result; } /*****************************************************************************\ Fail sort of gracefully with an error message. \*****************************************************************************/ void failf(const char* fmt, ...) { // Something bad has happened, therefore we won't assume we can use // the shared format buffer. const int bufsize = 255; char failbuf[bufsize + 1]; FORMAT(fmt, failbuf, bufsize); printf("Failure: %s\n", failbuf); printf("Hit any key to exit..\n"); getch(); exit(-1); } /*****************************************************************************\ \*****************************************************************************/ Stopwatch::Stopwatch() { clock(); startTime = std::chrono::steady_clock::now(); } void Stopwatch::start() { startTime = std::chrono::steady_clock::now(); } double Stopwatch::elapsedSeconds() const { auto now = std::chrono::steady_clock::now(); std::chrono::duration<double> dt = now - startTime; double elapsed_seconds = dt.count(); return elapsed_seconds; } /*****************************************************************************\ Return the fractional difference between x and y: Abs(x-y) / Max(x,y) \*****************************************************************************/ double fractionalDifference(double x, double y) { double maxval = Max(Abs(x), Abs(y)); if (maxval == 0) return 0; double delta = Abs(x - y); // This is not intended as a general-purpose function that may // be called with pathological inputs, so we're going to be // pragmatic and not stress about things like overflows, except // for a basic sanity check. Assert(maxval > 1e-10); return delta / maxval; }
6,810
1,945
#ifndef RYML_SINGLE_HEADER #include "c4/yml/std/std.hpp" #include "c4/yml/parse.hpp" #include "c4/yml/emit.hpp" #include <c4/format.hpp> #include <c4/yml/detail/checks.hpp> #include <c4/yml/detail/print.hpp> #endif #include "./test_case.hpp" #include <gtest/gtest.h> namespace c4 { namespace yml { std::string emit2str(Tree const& t) { return emitrs<std::string>(t); } TEST(style, flags) { Tree tree = parse_in_arena("foo: bar"); EXPECT_TRUE(tree.rootref().type().default_block()); EXPECT_FALSE(tree.rootref().type().marked_flow()); EXPECT_FALSE(tree.rootref().type().marked_flow_sl()); EXPECT_FALSE(tree.rootref().type().marked_flow_ml()); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_TRUE(tree.rootref().type().marked_flow()); EXPECT_TRUE(tree.rootref().type().marked_flow_sl()); EXPECT_FALSE(tree.rootref().type().marked_flow_ml()); tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_ML); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_TRUE(tree.rootref().type().marked_flow()); EXPECT_FALSE(tree.rootref().type().marked_flow_sl()); EXPECT_TRUE(tree.rootref().type().marked_flow_ml()); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- csubstr scalar_yaml = R"( this is the key: >- this is the multiline "val" with 'empty' lines )"; void check_same_emit(Tree const& expected) { #if 0 #define _showtrees(num) \ std::cout << "--------\nEMITTED" #num "\n--------\n"; \ std::cout << ws ## num; \ std::cout << "--------\nACTUAL" #num "\n--------\n"; \ print_tree(actual ## num); \ std::cout << "--------\nEXPECTED" #num "\n--------\n"; \ print_tree(expected) #else #define _showtrees(num) #endif std::string ws1, ws2, ws3, ws4; emitrs(expected, &ws1); { SCOPED_TRACE("actual1"); Tree actual1 = parse_in_arena(to_csubstr(ws1)); _showtrees(1); test_compare(actual1, expected); emitrs(actual1, &ws2); } { SCOPED_TRACE("actual2"); Tree actual2 = parse_in_arena(to_csubstr(ws2)); _showtrees(2); test_compare(actual2, expected); emitrs(actual2, &ws3); } { SCOPED_TRACE("actual3"); Tree actual3 = parse_in_arena(to_csubstr(ws3)); _showtrees(3); test_compare(actual3, expected); emitrs(actual3, &ws4); } { SCOPED_TRACE("actual4"); Tree actual4 = parse_in_arena(to_csubstr(ws4)); _showtrees(4); test_compare(actual4, expected); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(style, noflags) { Tree expected = parse_in_arena("{}"); NodeRef r = expected.rootref(); r["normal"] |= MAP; r["normal"]["singleline"] = "foo"; r["normal"]["multiline"] |= MAP; r["normal"]["multiline"]["____________"] = "foo"; r["normal"]["multiline"]["____mid_____"] = "foo\nbar"; r["normal"]["multiline"]["____mid_end1"] = "foo\nbar\n"; r["normal"]["multiline"]["____mid_end2"] = "foo\nbar\n\n"; r["normal"]["multiline"]["____mid_end3"] = "foo\nbar\n\n\n"; r["normal"]["multiline"]["____________"] = "foo"; r["normal"]["multiline"]["____________"] = "foo bar"; r["normal"]["multiline"]["________end1"] = "foo bar\n"; r["normal"]["multiline"]["________end2"] = "foo bar\n\n"; r["normal"]["multiline"]["________end3"] = "foo bar\n\n\n"; r["normal"]["multiline"]["beg_________"] = "\nfoo"; r["normal"]["multiline"]["beg_mid_____"] = "\nfoo\nbar"; r["normal"]["multiline"]["beg_mid_end1"] = "\nfoo\nbar\n"; r["normal"]["multiline"]["beg_mid_end2"] = "\nfoo\nbar\n\n"; r["normal"]["multiline"]["beg_mid_end3"] = "\nfoo\nbar\n\n\n"; r["leading_ws"] |= MAP; r["leading_ws"]["singleline"] |= MAP; r["leading_ws"]["singleline"]["space"] = " foo"; r["leading_ws"]["singleline"]["tab"] = "\tfoo"; r["leading_ws"]["singleline"]["space_and_tab0"] = " \tfoo"; r["leading_ws"]["singleline"]["space_and_tab1"] = "\t foo"; r["leading_ws"]["multiline"] |= MAP; r["leading_ws"]["multiline"]["beg_________"] = "\n \tfoo"; r["leading_ws"]["multiline"]["beg_mid_____"] = "\n \tfoo\nbar"; r["leading_ws"]["multiline"]["beg_mid_end1"] = "\n \tfoo\nbar\n"; r["leading_ws"]["multiline"]["beg_mid_end2"] = "\n \tfoo\nbar\n\n"; r["leading_ws"]["multiline"]["beg_mid_end3"] = "\n \tfoo\nbar\n\n\n"; check_same_emit(expected); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #ifdef WIP TEST(style, scalar_retains_style_after_parse) { { Tree t = parse_in_arena("foo"); EXPECT_TRUE(t.rootref().type().val_marked_plain()); EXPECT_FALSE(t.rootref().type().val_marked_squo()); EXPECT_FALSE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("foo\n")); } { Tree t = parse_in_arena("'foo'"); EXPECT_FALSE(t.rootref().type().val_marked_plain()); EXPECT_TRUE(t.rootref().type().val_marked_squo()); EXPECT_FALSE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n")); } { Tree t = parse_in_arena("'foo'"); EXPECT_FALSE(t.rootref().type().val_marked_plain()); EXPECT_FALSE(t.rootref().type().val_marked_squo()); EXPECT_TRUE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n")); } { Tree t = parse_in_arena("[foo, 'baz', \"bat\"]"); EXPECT_TRUE(t.rootref().type().marked_flow()); EXPECT_TRUE(t[0].type().val_marked_plain()); EXPECT_FALSE(t[0].type().val_marked_squo()); EXPECT_FALSE(t[0].type().val_marked_dquo()); EXPECT_FALSE(t[0].type().val_marked_literal()); EXPECT_FALSE(t[0].type().val_marked_folded()); EXPECT_FALSE(t[1].type().val_marked_plain()); EXPECT_TRUE(t[1].type().val_marked_squo()); EXPECT_FALSE(t[1].type().val_marked_dquo()); EXPECT_FALSE(t[1].type().val_marked_literal()); EXPECT_FALSE(t[1].type().val_marked_folded()); EXPECT_FALSE(t[2].type().val_marked_plain()); EXPECT_FALSE(t[2].type().val_marked_squo()); EXPECT_TRUE(t[2].type().val_marked_dquo()); EXPECT_FALSE(t[2].type().val_marked_literal()); EXPECT_FALSE(t[2].type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("foo")); } } #endif //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(scalar, base) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_EQ(tree[0].key(), csubstr("this is the key")); EXPECT_EQ(tree[0].val(), csubstr("this is the multiline \"val\" with\n'empty' lines")); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } TEST(scalar, block_literal) { Tree tree = parse_in_arena(scalar_yaml); { SCOPED_TRACE("val only"); EXPECT_FALSE(tree[0].type().key_marked_literal()); EXPECT_FALSE(tree[0].type().val_marked_literal()); tree._add_flags(tree[0].id(), _WIP_VAL_LITERAL); EXPECT_FALSE(tree[0].type().key_marked_literal()); EXPECT_TRUE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_LITERAL); EXPECT_TRUE(tree[0].type().key_marked_literal()); EXPECT_TRUE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(? |- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_LITERAL); EXPECT_TRUE(tree[0].type().key_marked_literal()); EXPECT_FALSE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(? |- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, block_folded) { Tree tree = parse_in_arena(scalar_yaml); { SCOPED_TRACE("val only"); EXPECT_FALSE(tree[0].type().key_marked_folded()); EXPECT_FALSE(tree[0].type().val_marked_folded()); tree._add_flags(tree[0].id(), _WIP_VAL_FOLDED); EXPECT_FALSE(tree[0].type().key_marked_folded()); EXPECT_TRUE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(this is the key: >- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_FOLDED); EXPECT_TRUE(tree[0].type().key_marked_folded()); EXPECT_TRUE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(? >- this is the key : >- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("val only"); tree._rem_flags(tree[0].id(), _WIP_VAL_FOLDED); EXPECT_TRUE(tree[0].type().key_marked_folded()); EXPECT_FALSE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(? >- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, squot) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_squo()); EXPECT_FALSE(tree[0].type().val_marked_squo()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_SQUO); EXPECT_FALSE(tree[0].type().key_marked_squo()); EXPECT_TRUE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"(this is the key: 'this is the multiline "val" with ''empty'' lines' )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_SQUO); EXPECT_TRUE(tree[0].type().key_marked_squo()); EXPECT_TRUE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"('this is the key': 'this is the multiline "val" with ''empty'' lines' )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_SQUO); EXPECT_TRUE(tree[0].type().key_marked_squo()); EXPECT_FALSE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"('this is the key': |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, dquot) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_dquo()); EXPECT_FALSE(tree[0].type().val_marked_dquo()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_DQUO); EXPECT_FALSE(tree[0].type().key_marked_dquo()); EXPECT_TRUE(tree[0].type().val_marked_dquo()); // visual studio fails to compile this string when used inside // the EXPECT_EQ() macro below. So we declare it separately // instead: csubstr yaml = R"(this is the key: "this is the multiline \"val\" with 'empty' lines" )"; EXPECT_EQ(emit2str(tree), yaml); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_DQUO); EXPECT_TRUE(tree[0].type().key_marked_dquo()); EXPECT_TRUE(tree[0].type().val_marked_dquo()); // visual studio fails to compile this string when used inside // the EXPECT_EQ() macro below. So we declare it separately // instead: csubstr yaml = R"("this is the key": "this is the multiline \"val\" with 'empty' lines" )"; EXPECT_EQ(emit2str(tree), yaml); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_DQUO); EXPECT_TRUE(tree[0].type().key_marked_dquo()); EXPECT_FALSE(tree[0].type().val_marked_dquo()); EXPECT_EQ(emit2str(tree), R"("this is the key": |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, plain) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_plain()); EXPECT_FALSE(tree[0].type().val_marked_plain()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_PLAIN); EXPECT_FALSE(tree[0].type().key_marked_plain()); EXPECT_TRUE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_PLAIN); EXPECT_TRUE(tree[0].type().key_marked_plain()); EXPECT_TRUE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_PLAIN); EXPECT_TRUE(tree[0].type().key_marked_plain()); EXPECT_FALSE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(stream, block) { Tree tree = parse_in_arena(R"( --- scalar %YAML 1.2 --- foo --- bar )"); EXPECT_TRUE(tree.rootref().is_stream()); EXPECT_TRUE(tree.docref(0).is_doc()); EXPECT_TRUE(tree.docref(0).is_val()); EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(seq, block) { Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]"); EXPECT_EQ(emit2str(tree), R"(- 1 - 2 - 3 - 4 - 5 - 6 )"); } TEST(seq, flow_sl) { Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"([1,2,3,4,5,6])"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(keyseq, block) { Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}"); EXPECT_TRUE(tree.rootref().type().default_block()); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - 2 - 3 - 4 - 5 - 6 )"); tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}"); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - - 2 - 3 - 4 - - 5 - 6 )"); } TEST(keyseq, flow_sl) { Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}"); EXPECT_TRUE(tree.rootref().type().default_block()); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_EQ(emit2str(tree), R"({foo: [1,2,3,4,5,6]})"); // tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: [1,[2,3],4,[5,6]]})"); // tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - [2,3] - 4 - [5,6] )"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(map, block) { Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}"); EXPECT_EQ(emit2str(tree), R"(1: 10 2: 10 3: 10 4: 10 5: 10 6: 10 )"); } TEST(map, flow_sl) { Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({1: 10,2: 10,3: 10,4: 10,5: 10,6: 10})"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(keymap, block) { Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}"); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: 10 3: 10 4: 10 5: 10 6: 10 )"); } TEST(keymap, flow_sl) { Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: 10,3: 10,4: 10,5: 10,6: 10}})"); // tree = parse_in_arena("{foo: {1: 10, 2: {2: 10, 3: 10}, 4: 10, 5: {5: 10, 6: 10}}}"); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: 2: 10 3: 10 4: 10 5: 5: 10 6: 10 )"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: {2: 10,3: 10},4: 10,5: {5: 10,6: 10}}})"); tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: {2: 10,3: 10} 4: 10 5: {5: 10,6: 10} )"); } //------------------------------------------- // this is needed to use the test case library Case const* get_case(csubstr /*name*/) { return nullptr; } } // namespace yml } // namespace c4
19,771
7,710
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/device/llcpp/fidl.h> #include <fuchsia/fshost/llcpp/fidl.h> #include <lib/devmgr-integration-test/fixture.h> #include <lib/driver-integration-test/fixture.h> #include <lib/fdio/cpp/caller.h> #include <lib/fdio/directory.h> #include <lib/fdio/watcher.h> #include <zircon/assert.h> #include <zircon/device/block.h> #include <zircon/hw/gpt.h> #include <ramdevice-client/ramdisk.h> #include <zxtest/zxtest.h> #include "block-device-interface.h" #include "block-watcher-test-data.h" #include "encrypted-volume-interface.h" namespace { using devmgr_integration_test::RecursiveWaitForFile; using driver_integration_test::IsolatedDevmgr; class MockBlockDevice : public devmgr::BlockDeviceInterface { public: disk_format_t GetFormat() override = 0; void SetFormat(disk_format_t format) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } bool Netbooting() override { return false; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = 0; info.block_size = 512; info.block_count = 1024; *out_info = info; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t AttachDriver(const std::string_view& driver) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t UnsealZxcrypt() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t FormatZxcrypt() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } bool ShouldCheckFilesystems() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t CheckFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t FormatFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t MountFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } }; // Tests adding a device which has no GUID and an unknown format. TEST(AddDeviceTestCase, AddUnknownDevice) { class UnknownDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { return ZX_ERR_NOT_SUPPORTED; } }; UnknownDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device with an unknown GUID and unknown format. TEST(AddDeviceTestCase, AddUnknownPartition) { class UnknownDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_EMPTY_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } }; UnknownDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device which is smaller than the expected header size TEST(AddDeviceTestCase, AddSmallDevice) { class SmallDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { return ZX_ERR_NOT_SUPPORTED; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = 0; info.block_size = 512; info.block_count = 1; *out_info = info; return ZX_OK; } }; SmallDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device with a GPT format. TEST(AddDeviceTestCase, AddGPTDevice) { class GptDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_GPT; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kGPTDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; GptDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with an FVM format. TEST(AddDeviceTestCase, AddFVMDevice) { class FvmDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_FVM; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kFVMDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; FvmDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with an MBR format. TEST(AddDeviceTestCase, AddMBRDevice) { class MbrDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MBR; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kMBRDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; MbrDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with a factory GUID but an unknown disk format. TEST(AddDeviceTestCase, AddUnformattedBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: // in FCT mode we need to be able to bind the block-verity driver to devices that don't yet // have detectable magic, so Add relies on the gpt guid. disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data()); attached = true; return ZX_OK; } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) final { EXPECT_STR_EQ("/mutable/block", expected_path.data()); *is_path = false; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GPT_FACTORY_TYPE_GUID; return ZX_OK; } bool attached = false; }; BlockVerityDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with a factory GUID but an unknown disk format with the topological path // suffix /mutable/block TEST(AddDeviceTestCase, AddUnformattedMutableBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t AttachDriver(const std::string_view& driver) final { ADD_FATAL_FAILURE("Should not attach a driver"); return ZX_OK; } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) final { EXPECT_STR_EQ("/mutable/block", expected_path.data()); *is_path = true; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GPT_FACTORY_TYPE_GUID; return ZX_OK; } }; BlockVerityDevice device; EXPECT_OK(device.Add()); } // Tests adding a device with the block-verity disk format. TEST(AddDeviceTestCase, AddFormattedBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOCK_VERITY; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; BlockVerityDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding blobfs which does not not have a valid type GUID. TEST(AddDeviceTestCase, AddNoGUIDBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GUID_TEST_VALUE; return ZX_OK; } zx_status_t CheckFilesystem() final { ADD_FATAL_FAILURE("Should not check filesystem"); return ZX_OK; } zx_status_t MountFilesystem() final { ADD_FATAL_FAILURE("Should not mount filesystem"); return ZX_OK; } }; BlobDevice device; EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add()); } // Tests adding blobfs with a valid type GUID, but invalid metadata. TEST(AddDeviceTestCase, AddInvalidBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_ERR_BAD_STATE; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; BlobDevice device; EXPECT_EQ(ZX_ERR_BAD_STATE, device.Add()); EXPECT_TRUE(device.checked); EXPECT_FALSE(device.formatted); EXPECT_FALSE(device.mounted); } // Tests adding blobfs with a valid type GUID and valid metadata. TEST(AddDeviceTestCase, AddValidBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_OK; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; BlobDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.checked); EXPECT_FALSE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding minfs which does not not have a valid type GUID. TEST(AddDeviceTestCase, AddNoGUIDMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GUID_TEST_VALUE; return ZX_OK; } zx_status_t CheckFilesystem() final { ADD_FATAL_FAILURE("Should not check filesystem"); return ZX_OK; } zx_status_t MountFilesystem() final { ADD_FATAL_FAILURE("Should not mount filesystem"); return ZX_OK; } }; MinfsDevice device; EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add()); } // Tests adding minfs with a valid type GUID and invalid metadata. Observe that // the filesystem reformats itself. TEST(AddDeviceTestCase, AddInvalidMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_ERR_BAD_STATE; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; MinfsDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.checked); EXPECT_TRUE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding minfs with a valid type GUID and invalid format. Observe that // the filesystem reformats itself. TEST(AddDeviceTestCase, AddUnknownFormatMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return format; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t CheckFilesystem() final { return ZX_OK; } zx_status_t MountFilesystem() final { EXPECT_TRUE(formatted); mounted = true; return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = true; return ZX_OK; } void SetFormat(disk_format_t f) final { format = f; } disk_format_t format = DISK_FORMAT_UNKNOWN; bool formatted = false; bool mounted = false; }; MinfsDevice device; EXPECT_FALSE(device.formatted); EXPECT_FALSE(device.mounted); EXPECT_OK(device.Add()); EXPECT_TRUE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding zxcrypt with a valid type GUID and invalid format. Observe that // the partition reformats itself. TEST(AddDeviceTestCase, AddUnknownFormatZxcryptDevice) { class ZxcryptDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return format; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t FormatZxcrypt() final { formatted_zxcrypt = true; return ZX_OK; } zx_status_t FormatFilesystem() final { formatted_filesystem = true; return ZX_OK; } zx_status_t CheckFilesystem() final { return ZX_OK; } zx_status_t UnsealZxcrypt() final { return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = false; return ZX_OK; } void SetFormat(disk_format_t f) final { format = f; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kZxcryptDriverPath, driver.data()); return ZX_OK; } disk_format_t format = DISK_FORMAT_UNKNOWN; bool formatted_zxcrypt = false; bool formatted_filesystem = false; }; ZxcryptDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.formatted_zxcrypt); EXPECT_FALSE(device.formatted_filesystem); } // Tests adding a boot partition device with unknown format can be added with // the correct driver. TEST(AddDeviceTestCase, AddUnknownFormatBootPartitionDevice) { class BootPartDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = BLOCK_FLAG_BOOTPART; info.block_size = 512; info.block_count = 1024; *out_info = info; return ZX_OK; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBootpartDriverPath, driver.data()); return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = false; checked_unsealed_zxcrypt = true; return ZX_OK; } bool checked_unsealed_zxcrypt = false; }; BootPartDevice device; EXPECT_OK(device.Add()); EXPECT_FALSE(device.checked_unsealed_zxcrypt); } TEST(AddDeviceTestCase, AddPermanentlyMiskeyedZxcryptVolume) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Simulate a device where we've lost the key -- can't unlock until we // format the device with a new key, but can afterwards. if (formatted) { postformat_unseal_attempt_count++; return ZX_OK; } else { preformat_unseal_attempt_count++; return ZX_ERR_ACCESS_DENIED; } } zx_status_t Format() final { formatted = true; return ZX_OK; } int preformat_unseal_attempt_count = 0; int postformat_unseal_attempt_count = 0; bool formatted = false; }; ZxcryptVolume volume; EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_TRUE(volume.preformat_unseal_attempt_count > 1); EXPECT_TRUE(volume.formatted); EXPECT_EQ(volume.postformat_unseal_attempt_count, 1); } TEST(AddDeviceTestCase, AddTransientlyMiskeyedZxcryptVolume) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Simulate a transient error -- fail the first time we try to unseal the // volume, but succeed on a retry or any subsequent attempt. unseal_attempt_count++; if (unseal_attempt_count > 1) { return ZX_OK; } else { return ZX_ERR_ACCESS_DENIED; } } zx_status_t Format() final { // We expect this to never be called. formatted = true; return ZX_OK; } int unseal_attempt_count = 0; bool formatted = false; }; ZxcryptVolume volume; EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_FALSE(volume.formatted); EXPECT_EQ(volume.unseal_attempt_count, 2); } TEST(AddDeviceTestCase, AddFailingZxcryptVolumeShouldNotFormat) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Errors that are not ZX_ERR_ACCESS_DENIED should not trigger // formatting. return ZX_ERR_INTERNAL; } zx_status_t Format() final { // Expect this to not be called. formatted = true; return ZX_OK; } bool formatted = false; }; ZxcryptVolume volume; EXPECT_EQ(ZX_ERR_INTERNAL, volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_FALSE(volume.formatted); } class BlockWatcherTest : public zxtest::Test { protected: BlockWatcherTest() { // Launch the isolated devmgr. IsolatedDevmgr::Args args; args.driver_search_paths.push_back("/boot/driver"); args.path_prefix = "/pkg/"; args.disable_block_watcher = false; ASSERT_OK(IsolatedDevmgr::Create(&args, &devmgr_)); fbl::unique_fd fd; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "misc/ramctl", &fd)); zx::channel remote; ASSERT_OK(zx::channel::create(0, &watcher_chan_, &remote)); ASSERT_OK(fdio_service_connect_at(devmgr_.fshost_outgoing_dir().get(), "/svc/fuchsia.fshost.BlockWatcher", remote.release())); } void CreateGptRamdisk(ramdisk_client** client) { zx::vmo ramdisk_vmo; ASSERT_OK(zx::vmo::create(kTestDiskSectors * kBlockSize, 0, &ramdisk_vmo)); // Write the GPT into the VMO. ASSERT_OK(ramdisk_vmo.write(kTestGptProtectiveMbr, 0, sizeof(kTestGptProtectiveMbr))); ASSERT_OK(ramdisk_vmo.write(kTestGptBlock1, kBlockSize, sizeof(kTestGptBlock1))); ASSERT_OK(ramdisk_vmo.write(kTestGptBlock2, 2 * kBlockSize, sizeof(kTestGptBlock2))); ASSERT_OK( ramdisk_create_at_from_vmo(devmgr_.devfs_root().get(), ramdisk_vmo.release(), client)); } void PauseWatcher() { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Pause(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_OK(result->status); } void ResumeWatcher() { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_OK(result->status); } void WaitForBlockDevice(int number) { auto path = fbl::StringPrintf("class/block/%03d", number); fbl::unique_fd fd; ASSERT_NO_FATAL_FAILURES(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); } // Check that the number of block devices bound by the block watcher // matches what we expect. Can only be called while the block watcher is running. // // This works by adding a new block device with a valid GPT. // We then wait for that block device to appear at class/block/|next_device_number|. // The block watcher should then bind the GPT driver to that block device, causing // another entry in class/block to appear representing the only partition on the GPT. // // We make sure that this entry's toplogical path corresponds to it being the first partition // of the block device we added. void CheckEventsDropped(int* next_device_number, ramdisk_client** client) { ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(client)); // Wait for the basic block driver to be bound auto path = fbl::StringPrintf("class/block/%03d", *next_device_number); *next_device_number += 1; fbl::unique_fd fd; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); // And now, wait for the GPT driver to be bound, and the first // partition to appear. path = fbl::StringPrintf("class/block/%03d", *next_device_number); *next_device_number += 1; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); // Figure out the expected topological path of the last block device. std::string expected_path(ramdisk_get_path(*client)); expected_path = "/dev/" + expected_path + "/part-000/block"; zx_handle_t handle; ASSERT_OK(fdio_get_service_handle(fd.release(), &handle)); zx::channel channel(handle); // Get the actual topological path of the block device. auto result = llcpp::fuchsia::device::Controller::Call::GetTopologicalPath(channel.borrow()); ASSERT_OK(result.status()); ASSERT_FALSE(result->result.is_err()); auto actual_path = std::string(result->result.response().path.begin(), result->result.response().path.size()); // Make sure expected path matches the actual path. ASSERT_EQ(expected_path, actual_path); } IsolatedDevmgr devmgr_; zx::channel watcher_chan_; }; TEST_F(BlockWatcherTest, TestBlockWatcherDisable) { ASSERT_NO_FATAL_FAILURES(PauseWatcher()); int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ramdisk_client* client2; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client2)); ASSERT_OK(ramdisk_destroy(client)); ASSERT_OK(ramdisk_destroy(client2)); } TEST_F(BlockWatcherTest, TestBlockWatcherAdd) { int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; ASSERT_NO_FATAL_FAILURES(PauseWatcher()); fbl::unique_fd fd; // Look for the first partition of the device we just added. ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "class/block/001", &fd)); ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ASSERT_OK(ramdisk_destroy(client)); } TEST_F(BlockWatcherTest, TestBlockWatcherUnmatchedResume) { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_STATUS(result->status, ZX_ERR_BAD_STATE); } TEST_F(BlockWatcherTest, TestMultiplePause) { ASSERT_NO_FATAL_FAILURES(PauseWatcher()); ASSERT_NO_FATAL_FAILURES(PauseWatcher()); int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; // Resume once. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ramdisk_client* client2; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client2)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; fbl::unique_fd fd; RecursiveWaitForFile(devmgr_.devfs_root(), ramdisk_get_path(client2), &fd); // Resume again. The block watcher should be running again. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); // Make sure neither device was seen by the watcher. ramdisk_client* client3; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client3)); // Pause again. ASSERT_NO_FATAL_FAILURES(PauseWatcher()); ramdisk_client* client4; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client4)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; // Resume again. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); // Make sure the last device wasn't added. ramdisk_client* client5; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client5)); ASSERT_OK(ramdisk_destroy(client)); ASSERT_OK(ramdisk_destroy(client2)); ASSERT_OK(ramdisk_destroy(client3)); ASSERT_OK(ramdisk_destroy(client4)); ASSERT_OK(ramdisk_destroy(client5)); } } // namespace
26,091
9,364
#include "./audio-source-impl.hpp" #include "./audio-engine-impl.hpp" using namespace lava::flow; AudioSource::Impl::Impl(AudioEngine::Impl& engine) : m_engine(engine) { } void AudioSource::Impl::playing(bool playing) { m_playing = playing; playing ? restart() : finish(); } void AudioSource::Impl::looping(bool looping) { m_looping = looping; } void AudioSource::Impl::removeOnFinish(bool removeOnFinish) { m_removeOnFinish = removeOnFinish; } // ----- Sub-class API void AudioSource::Impl::finish() { m_playing = false; if (m_removeOnFinish) { m_engine.remove(*this); } else if (m_looping) { m_playing = true; restart(); } }
700
252
#include "term_buffer.h" #include "term_window.h" #include "term_network.h" #include "cap_manager.h" #include "term_cell.h" #include "string_utils.h" #include <string.h> #include <iostream> #include <sstream> #include <iterator> DEFINE_CAP(osc_selection_request); void osc_selection_request(term_data_context_s & term_context, const term_data_param_list & params){ if (params[0] == 52) { std::string buffer_index = "0"; std::string ss_data; std::string v = params[1].str_value; auto pos = v.find(";"); if (pos != std::string::npos) { buffer_index = v.substr(0, pos); ss_data = v.substr(pos + 1); } if (ss_data == "?") { std::string sel_data = term_context.term_window->GetSelectionData(); std::stringstream ss; ss << "\033]52;" << buffer_index << ";" << sel_data << "\007"; send(term_context, ss.str().c_str()); } else{ term_context.term_window->SetSelectionData(ss_data); } } }
1,095
371
#include "std.h" #include "expr_item_if.h" //////////////////////////////////////////////////////////////////////////////// // TOperandNode类 KC::TOperandNode::TOperandNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : m_work(wk), m_pd(pd), m_pBeginPtr(syn.GetBeginPtr()), m_pEndPtr(syn.GetEndPtr()), m_LineID(pd.GetLineID(syn)) { } // 得到行号 int KC::TOperandNode::GetLineID(void) const { return m_LineID; } //////////////////////////////////////////////////////////////////////////////// // TUnaryNode类 KC::TUnaryNode::TUnaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : TOperandNode(wk, pd, syn) { } // 获取值 boost::any KC::TUnaryNode::GetValue(IKCActionData& act) { // 操作数 IOperandNode *pOperand = dynamic_cast<IOperandNode*>(OperandPtr.get()); if (nullptr == pOperand) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); // 获取操作数的值 boost::any val = pOperand->GetValue(act); // 返回计算结果 return this->Calculate(val); } //////////////////////////////////////////////////////////////////////////////// // TBinaryNode类 KC::TBinaryNode::TBinaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : TOperandNode(wk, pd, syn) { } // 获取值 boost::any KC::TBinaryNode::GetValue(IKCActionData& act) { // 左操作数 IOperandNode *pOperandL = dynamic_cast<IOperandNode*>(OperandPtrL.get()); if (nullptr == pOperandL) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_left_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); boost::any valL = pOperandL->GetValue(act); // 右操作数 IOperandNode *pOperandR = dynamic_cast<IOperandNode*>(OperandPtrR.get()); if (nullptr == pOperandR) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_right_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); boost::any valR = pOperandR->GetValue(act); // 返回计算结果 return this->Calculate(valL, valR); } // 得到自适应类型的左值 boost::any KC::TBinaryNode::GetLValueNewType(boost::any& lv, boost::any& rv) { if (lv.empty()) { if (rv.empty()) return string(""); else if (rv.type() == typeid(int)) return (int)0; else if (rv.type() == typeid(double)) return (double)0; else if (rv.type() == typeid(bool)) return false; else return string(""); } else if (rv.empty() || lv.type() == rv.type()) return lv; else if (lv.type() == typeid(bool)) { if (rv.type() == typeid(int)) return boost::any_cast<bool>(lv) ? (int)1 : (int)0; if (rv.type() == typeid(double)) return boost::any_cast<bool>(lv) ? (double)1 : (double)0; else return boost::any_cast<bool>(lv) ? string("true") : string("false"); } else if (lv.type() == typeid(int)) { if (rv.type() == typeid(bool)) return lv; else if (rv.type() == typeid(double)) return (double)boost::any_cast<int>(lv); else return lexical_cast<string>(boost::any_cast<int>(lv)); } else if (lv.type() == typeid(double)) { if (rv.type() == typeid(bool) || rv.type() == typeid(int)) return lv; else return lexical_cast<string>(boost::any_cast<double>(lv)); } else if (lv.type() == typeid(TKcWebInfVal)) return boost::any_cast<TKcWebInfVal>(lv).str(); else return lv; }
3,699
1,329
#include "time.hpp" timeStamp programStart; timeStamp getCurrentTimeMicro(){ return time_point_cast<microseconds>(steady_clock::now()); } timeStamp getTimeInFuture(uint64_t usec){ return time_point_cast<microseconds>(steady_clock::now()) + std::chrono::microseconds(usec); } int64_t getTimeDifference(timeStamp t0, timeStamp t1){ return duration_cast<microseconds>(t0 - t1).count(); } int64_t timeSince(timeStamp t0){ return duration_cast<microseconds>(getCurrentTimeMicro() - t0).count(); } int64_t timeTo(timeStamp t0){ return duration_cast<microseconds>(t0-getCurrentTimeMicro()).count(); } int64_t timeSinceStart(timeStamp t0){ return duration_cast<microseconds>(t0 - programStart).count(); } int64_t unixTime(timeStamp t0){ return duration_cast<seconds>(t0.time_since_epoch()).count(); } /* #include "time.hpp" timeStamp programStart; nanoseconds timespecToDuration(timespec ts){ auto duration = seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec}; return duration_cast<nanoseconds>(duration); } time_point<system_clock, nanoseconds>timespecToTimePoint(timespec ts){ return time_point<system_clock, nanoseconds>{duration_cast<system_clock::duration>(timespecToDuration(ts))}; } timeStamp getCurrentTimeMicro(){ timeStamp ts; timespec_get(&ts.time, TIME_UTC); return ts; } timeStamp getTimeInFuture(uint64_t usec){ timeStamp ts = getCurrentTimeMicro(); return ts + usec; } int64_t timeSince(timeStamp t0){ timeStamp ts = getCurrentTimeMicro() - t0; int64_t since = ts.time.tv_sec * 1000000 + ts.time.tv_nsec / 1000; return since; } int64_t timeTo(timeStamp t0){ return t0.micros(); } int64_t getTimeDifference(timeStamp t0, timeStamp t1){ } int64_t timeSinceStart(timeStamp t0){ } int64_t unixTime(timeStamp t0); */
1,826
709
/* * Copyright (C) 2018 The Android Open Source Project * Copyright (C) 2015-2020 STMicroelectronics * * 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 <stdint.h> #include <fcntl.h> #include <assert.h> #include <string.h> #include <signal.h> #include <unistd.h> #include "SensorBase.h" namespace stm { namespace core { static IConsole &console { IConsole::getInstance() }; SensorBase::SensorBase(const char *name, int handle, const STMSensorType &type, int module) : sensor_t_data(type), threadsRunning(true), sensorsCallback(nullptr), moduleId(module) { int i, err, pipe_fd[2]; if (strlen(name) + 1 > SENSOR_BASE_ANDROID_NAME_MAX) { memcpy(android_name, name, SENSOR_BASE_ANDROID_NAME_MAX - 1); android_name[SENSOR_BASE_ANDROID_NAME_MAX - 1] = '\0'; } else { memcpy(android_name, name, strlen(name) + 1); } valid_class = true; memset(&push_data, 0, sizeof(dependencies_t)); memset(&dependencies, 0, sizeof(push_data_t)); //memset(&sensor_t_data, 0, sizeof(struct sensor_t)); // memset(&sensor_event, 0, sizeof(sensors_event_t)); memset(sensors_pollrates, 0, ST_HAL_IIO_MAX_DEVICES * sizeof(int64_t)); for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { sensors_timeout[i] = INT64_MAX; } sensor_event.version = sizeof(sensors_event_t); sensor_event.sensor = handle; if (!type.isInternal()) { sensor_event.type = static_cast<SensorType>(type); } sensor_t_data.name = android_name; sensor_t_data.handle = handle; //sensor_t_data.type = type; sensor_t_data.vendor = "STMicroelectronics"; last_data_timestamp = 0; enabled_sensors_mask = 0; current_real_pollrate = 0; sample_in_processing_timestamp = 0; current_min_pollrate = 0; current_min_timeout = INT64_MAX; sensor_global_enable = 0; sensor_global_disable = 1; sensor_my_enable = 0; sensor_my_disable = 1; decimator = 1; samples_counter = 0; injection_mode = SENSOR_INJECTION_NONE; write_pipe_fd = -EINVAL; read_pipe_fd = -EINVAL; pthread_mutex_init(&enable_mutex, NULL); pthread_mutex_init(&sample_in_processing_mutex, NULL); err = pipe(pipe_fd); if (err < 0) { console.error(GetName() + std::string(": Failed to create pipe file.")); goto invalid_the_class; } fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK); write_pipe_fd = pipe_fd[1]; read_pipe_fd = pipe_fd[0]; return; invalid_the_class: InvalidThisClass(); } SensorBase::~SensorBase() { threadsRunning = false; close(write_pipe_fd); close(read_pipe_fd); if (dataThread && dataThread->joinable()) dataThread->join(); if (eventsThread && eventsThread->joinable()) eventsThread->join(); } DependencyID SensorBase::GetDependencyIDFromHandle(int handle) { return handle_remapping_ID[handle]; } void SensorBase::SetDependencyIDOfHandle(int handle, DependencyID id) { handle_remapping_ID[handle] = id; } void SensorBase::InvalidThisClass() { valid_class = false; } bool SensorBase::IsValidClass() { return valid_class; } int SensorBase::GetHandle() { return sensor_t_data.handle; } STMSensorType SensorBase::GetType() { return sensor_t_data.type; } int SensorBase::GetMaxFifoLenght() { return sensor_t_data.fifoMaxEventCount; } int SensorBase::GetFdPipeToRead() { return read_pipe_fd; } void SensorBase::SetBitEnableMask(int handle) { enabled_sensors_mask |= (1ULL << handle); } void SensorBase::ResetBitEnableMask(int handle) { enabled_sensors_mask &= ~(1ULL << handle); } int SensorBase::AddNewPollrate(int64_t timestamp, int64_t pollrate) { return odr_stack.writeElement(timestamp, pollrate); } int SensorBase::CheckLatestNewPollrate(int64_t *timestamp, int64_t *pollrate) { *timestamp = odr_stack.readLastElement(pollrate); if (*timestamp < 0) { return -EINVAL; } return 0; } void SensorBase::DeleteLatestNewPollrate() { odr_stack.removeLastElement(); } bool SensorBase::ValidDataToPush(int64_t timestamp) { if (sensor_my_enable > sensor_my_disable) { if (timestamp > sensor_my_enable) { return true; } } else { if ((timestamp > sensor_my_enable) && (timestamp < sensor_my_disable)) { return true; } } return false; } bool SensorBase::GetDependencyMaxRange(STMSensorType type, float *maxRange) { bool found; unsigned int i; float maxRange_priv = 0; if (sensor_t_data.type == type) { *maxRange = sensor_t_data.maxRange; return true; } for (i = 0; i < dependencies.num; i++) { found = dependencies.sb[i]->GetDependencyMaxRange(type, &maxRange_priv); if (found) { *maxRange = maxRange_priv; return true; } } return false; } char* SensorBase::GetName() { return (char *)sensor_t_data.name; } selftest_status SensorBase::ExecuteSelfTest() { return NOT_AVAILABLE; } int SensorBase::Enable(int handle, bool enable, bool lock_en_mutex) { int err = 0; unsigned int i = 0; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } if ((handle == sensor_t_data.handle) && (enable == GetStatusOfHandle(handle))) { goto enable_unlock_mutex; } if ((enable && !GetStatus(false)) || (!enable && !GetStatusExcludeHandle(handle))) { if (enable) { SetBitEnableMask(handle); flush_stack.resetBuffer(); lastDecimatedPollrate = 0; } else { err = SetDelay(handle, 0, INT64_MAX, false); if (err < 0) { goto enable_unlock_mutex; } ResetBitEnableMask(handle); } for (i = 0; i < dependencies.num; i++) { err = dependencies.sb[i]->Enable(sensor_t_data.handle, enable, true); if (err < 0) { goto restore_enable_dependencies; } } if (enable) { console.debug(GetName() + std::string(": power-on")); } else { console.debug(GetName() + std::string(": power-off")); } } else { if (enable) { SetBitEnableMask(handle); } else { err = SetDelay(handle, 0, INT64_MAX, false); if (err < 0) { goto enable_unlock_mutex; } ResetBitEnableMask(handle); } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return 0; restore_enable_dependencies: while (i > 0) { i--; dependencies.sb[i]->Enable(sensor_t_data.handle, !enable, true); } if (enable) { ResetBitEnableMask(handle); } else { SetBitEnableMask(handle); } enable_unlock_mutex: if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return err; } bool SensorBase::GetStatusExcludeHandle(int handle) { return (enabled_sensors_mask & ~(1ULL << handle)) > 0 ? true : false; } bool SensorBase::GetStatusOfHandle(int handle) { return (enabled_sensors_mask & (1ULL << handle)) > 0 ? true : false; } bool SensorBase::GetStatusOfHandle(int handle, bool lock_en_mutex) { bool status; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } status = (enabled_sensors_mask & (1ULL << handle)) > 0 ? true : false; if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return status; } bool SensorBase::GetStatus(bool lock_en_mutex) { bool status; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } status = enabled_sensors_mask > 0 ? true : false; if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return status; } int SensorBase::SetDelay(int handle, int64_t period_ns, int64_t timeout, bool lock_en_mutex) { int err, i; int64_t restore_min_timeout, restore_min_period_ms; if ((timeout > 0) && (timeout < INT64_MAX) && (sensor_t_data.fifoMaxEventCount == 0)) { return -EINVAL; } if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } restore_min_timeout = sensors_timeout[handle]; restore_min_period_ms = sensors_pollrates[handle]; sensors_pollrates[handle] = period_ns; sensors_timeout[handle] = timeout; for (i = 0; i < (int)dependencies.num; i++) { err = dependencies.sb[i]->SetDelay(sensor_t_data.handle, GetMinPeriod(false), GetMinTimeout(false), true); if (err < 0) { goto restore_delay_dependencies; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return 0; restore_delay_dependencies: sensors_pollrates[handle] = restore_min_period_ms; sensors_timeout[handle] = restore_min_timeout; for (i--; i >= 0; i--) { dependencies.sb[i]->SetDelay(sensor_t_data.handle, GetMinPeriod(false), GetMinTimeout(false), true); } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return err; } const std::vector<STMSensorType>& SensorBase::GetDepenciesTypeList(void) const { return dependencies_type_list; } int SensorBase::AllocateBufferForDependencyData(DependencyID id, unsigned int max_fifo_len) { circular_buffer_data[id] = new CircularBuffer(max_fifo_len < 2 ? 10 : 10 * max_fifo_len); if (!circular_buffer_data[id]) { console.error(GetName() + std::string(": Failed to allocate circular buffer data.")); return -ENOMEM; } return 0; } void SensorBase::DeAllocateBufferForDependencyData(DependencyID id) { delete circular_buffer_data[id]; } int SensorBase::AddSensorToDataPush(SensorBase *t) { if (push_data.num >= SENSOR_DEPENDENCY_ID_MAX) { console.error(android_name + std::string(": Failed to add dependency data, too many sensors to push data.")); return -ENOMEM; } push_data.sb[push_data.num] = t; push_data.num++; return 0; } void SensorBase::RemoveSensorToDataPush(SensorBase *t) { unsigned int i; for (i = 0; i < push_data.num; i++) { if (t == push_data.sb[i]) { break; } } if (i == push_data.num) { return; } for (; i < push_data.num - 1; i++) { push_data.sb[i] = push_data.sb[i + 1]; } push_data.num--; } int SensorBase::AddSensorDependency(SensorBase *p) { int err; unsigned int dependency_id; if (dependencies.num >= SENSOR_DEPENDENCY_ID_MAX) { console.error(android_name + std::string(": Failed to add dependency, too many dependencies.")); return -ENOMEM; } dependency_id = dependencies.num; SetDependencyIDOfHandle(p->GetHandle(), (DependencyID)dependency_id); err = p->AddSensorToDataPush(this); if (err < 0) { return err; } struct sensor_t dependecy_data = p->GetSensor_tData(); sensor_t_data.power += dependecy_data.power; dependencies.sb[dependency_id] = p; dependencies.num++; return dependency_id; } void SensorBase::RemoveSensorDependency(SensorBase *p) { unsigned int i; for (i = 0; i < dependencies.num; i++) { if (p == dependencies.sb[i]) { break; } } if (i == dependencies.num) { return; } p->RemoveSensorToDataPush(this); for (; i < dependencies.num - 1; i++) { dependencies.sb[i] = dependencies.sb[i + 1]; } dependencies.num--; } int SensorBase::startThreads(void) { if (hasDataChannels()) { dataThread = std::make_unique<std::thread>(ThreadDataWork, this, std::ref(threadsRunning)); } if (hasEventChannels()) { eventsThread = std::make_unique<std::thread>(ThreadEventsWork, this, std::ref(threadsRunning)); } return 0; } void SensorBase::stopThreads(void) { } struct sensor_t SensorBase::GetSensor_tData(void) { struct sensor_t data(sensor_t_data); return data; } void SensorBase::WriteOdrChangeEventToPipe(int64_t timestamp, int64_t pollrate) { sensors_event_t odr_change_event_data; odr_change_event_data.sensor = sensor_t_data.handle; odr_change_event_data.timestamp = timestamp; odr_change_event_data.type = SensorType::ODR_SWITCH_INFO; odr_change_event_data.data.dataLen = 1; odr_change_event_data.data.data2[0] = pollrate; auto err = write(write_pipe_fd, &odr_change_event_data, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write odr change event data to pipe.")); } } void SensorBase::WriteFlushEventToPipe() { int err; sensors_event_t flush_event_data; // memset(&flush_event_data, 0, sizeof(sensors_event_t)); flush_event_data.sensor = sensor_t_data.handle; flush_event_data.timestamp = 0; // flush_event_data.data_new[0] = // flush_event_data.meta_data.sensor = sensor_t_data.handle; //flush_event_data.meta_data.what = META_DATA_FLUSH_COMPLETE; flush_event_data.type = SensorType::META_DATA; //flush_event_data.version = META_DATA_VERSION; console.debug(GetName() + std::string(": write flush event to pipe")); err = write(write_pipe_fd, &flush_event_data, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write flush event data to pipe.")); } } void SensorBase::WriteDataToPipe(int64_t __attribute__((unused))hw_pollrate) { int err; if (ValidDataToPush(sensor_event.timestamp)) { if (sensor_event.timestamp > last_data_timestamp) { err = write(write_pipe_fd, &sensor_event, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write sensor data to pipe.")); return; } last_data_timestamp = sensor_event.timestamp; } } } void SensorBase::ProcessData(SensorBaseData *data) { unsigned int i; for (int i = 0; i < data->flushEventsNum; ++i) { if (data->flushEventHandles[i] == sensor_t_data.handle) { WriteFlushEventToPipe(); } } for (i = 0; i < push_data.num; i++) { push_data.sb[i]->ReceiveDataFromDependency(sensor_t_data.handle, data); } } void SensorBase::ReceiveDataFromDependency(int handle, SensorBaseData *data) { bool fill_buffer = false; if (sensor_global_enable > sensor_global_disable) { if (data->timestamp > sensor_global_enable) { fill_buffer = true; } } else { if ((data->timestamp > sensor_global_enable) && (data->timestamp < sensor_global_disable)) { fill_buffer = true; } } if (fill_buffer) { circular_buffer_data[GetDependencyIDFromHandle(handle)]->writeElement(data); } } int SensorBase::GetLatestValidDataFromDependency(int dependency_id, SensorBaseData *data, int64_t timesync) { return circular_buffer_data[dependency_id]->readSyncElement(data, timesync); } int64_t SensorBase::GetMinTimeout(bool lock_en_mutex) { int i; int64_t min = INT64_MAX; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { if ((sensors_timeout[i] < min) && (sensors_timeout[i] < INT64_MAX)) { min = sensors_timeout[i]; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return min; } int64_t SensorBase::GetMinPeriod(bool lock_en_mutex) { int i; int64_t min = INT64_MAX; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { if ((sensors_pollrates[i] < min) && (sensors_pollrates[i] > 0)) { min = sensors_pollrates[i]; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return min == INT64_MAX ? 0 : min; } void *SensorBase::ThreadDataWork(void *context, std::atomic<bool>& threadsRunning) { SensorBase *mypointer = (SensorBase *)context; mypointer->ThreadDataTask(threadsRunning); return mypointer; } void SensorBase::ThreadDataTask(std::atomic<bool>& threadsRunning) { (void)threadsRunning; } void *SensorBase::ThreadEventsWork(void *context, std::atomic<bool>& threadsRunning) { SensorBase *mypointer = (SensorBase *)context; mypointer->ThreadEventsTask(threadsRunning); return mypointer; } void SensorBase::ThreadEventsTask(std::atomic<bool>& threadsRunning) { (void)threadsRunning; } int SensorBase::InjectionMode(bool __attribute__((unused))enable) { return 0; } int SensorBase::InjectSensorData(const sensors_event_t __attribute__((unused))*data) { return -EINVAL; } bool SensorBase::hasEventChannels() { return false; } bool SensorBase::hasDataChannels() { return false; } void SensorBase::setCallbacks(const ISTMSensorsCallback &sensorsCallback) { this->sensorsCallback = (ISTMSensorsCallback *)&sensorsCallback; } int SensorBase::getHandleOfMyTrigger(void) const { return -1; } } // namespace core } // namespace stm
17,693
6,351
// 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 "ui/gl/gl_implementation.h" #include <algorithm> #include <string> #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" #include "ui/gl/gl_bindings.h" namespace gfx { namespace { const struct { const char* name; GLImplementation implementation; } kGLImplementationNamePairs[] = { { kGLImplementationDesktopName, kGLImplementationDesktopGL }, { kGLImplementationOSMesaName, kGLImplementationOSMesaGL }, #if defined(OS_MACOSX) { kGLImplementationAppleName, kGLImplementationAppleGL }, #endif { kGLImplementationEGLName, kGLImplementationEGLGLES2 }, { kGLImplementationMockName, kGLImplementationMockGL } }; typedef std::vector<base::NativeLibrary> LibraryArray; GLImplementation g_gl_implementation = kGLImplementationNone; LibraryArray* g_libraries; GLGetProcAddressProc g_get_proc_address; void CleanupNativeLibraries(void* unused) { if (g_libraries) { for (LibraryArray::iterator it = g_libraries->begin(); it != g_libraries->end(); ++it) { base::UnloadNativeLibrary(*it); } delete g_libraries; g_libraries = NULL; } } bool ExportsCoreFunctionsFromGetProcAddress(GLImplementation implementation) { switch (GetGLImplementation()) { case kGLImplementationDesktopGL: case kGLImplementationOSMesaGL: case kGLImplementationAppleGL: case kGLImplementationMockGL: return true; case kGLImplementationEGLGLES2: return false; default: NOTREACHED(); return true; } } } GLApi* g_current_gl_context; OSMESAApi* g_current_osmesa_context; #if defined(OS_WIN) EGLApi* g_current_egl_context; WGLApi* g_current_wgl_context; #elif defined(USE_X11) EGLApi* g_current_egl_context; GLXApi* g_current_glx_context; #elif defined(OS_ANDROID) EGLApi* g_current_egl_context; #endif GLImplementation GetNamedGLImplementation(const std::string& name) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) { if (name == kGLImplementationNamePairs[i].name) return kGLImplementationNamePairs[i].implementation; } return kGLImplementationNone; } const char* GetGLImplementationName(GLImplementation implementation) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) { if (implementation == kGLImplementationNamePairs[i].implementation) return kGLImplementationNamePairs[i].name; } return "unknown"; } void SetGLImplementation(GLImplementation implementation) { g_gl_implementation = implementation; } GLImplementation GetGLImplementation() { return g_gl_implementation; } bool HasDesktopGLFeatures() { return kGLImplementationDesktopGL == g_gl_implementation || kGLImplementationOSMesaGL == g_gl_implementation || kGLImplementationAppleGL == g_gl_implementation; } void AddGLNativeLibrary(base::NativeLibrary library) { DCHECK(library); if (!g_libraries) { g_libraries = new LibraryArray; base::AtExitManager::RegisterCallback(CleanupNativeLibraries, NULL); } g_libraries->push_back(library); } void UnloadGLNativeLibraries() { CleanupNativeLibraries(NULL); } void SetGLGetProcAddressProc(GLGetProcAddressProc proc) { DCHECK(proc); g_get_proc_address = proc; } void* GetGLCoreProcAddress(const char* name) { DCHECK(g_gl_implementation != kGLImplementationNone); if (g_libraries) { for (size_t i = 0; i < g_libraries->size(); ++i) { void* proc = base::GetFunctionPointerFromNativeLibrary((*g_libraries)[i], name); if (proc) return proc; } } if (ExportsCoreFunctionsFromGetProcAddress(g_gl_implementation) && g_get_proc_address) { void* proc = g_get_proc_address(name); if (proc) return proc; } return NULL; } void* GetGLProcAddress(const char* name) { DCHECK(g_gl_implementation != kGLImplementationNone); void* proc = GetGLCoreProcAddress(name); if (!proc && g_get_proc_address) { proc = g_get_proc_address(name); if (proc) return proc; } return proc; } } // namespace gfx
4,259
1,454
/* * Copyright © 2015 Intel Corporation * * 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 (including the next * paragraph) 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 <gtest/gtest.h> #include "brw_fs.h" #include "brw_cfg.h" #include "program/program.h" using namespace brw; class cmod_propagation_test : public ::testing::Test { virtual void SetUp(); public: struct brw_compiler *compiler; struct gen_device_info *devinfo; struct gl_context *ctx; struct brw_wm_prog_data *prog_data; struct gl_shader_program *shader_prog; fs_visitor *v; }; class cmod_propagation_fs_visitor : public fs_visitor { public: cmod_propagation_fs_visitor(struct brw_compiler *compiler, struct brw_wm_prog_data *prog_data, nir_shader *shader) : fs_visitor(compiler, NULL, NULL, NULL, &prog_data->base, (struct gl_program *) NULL, shader, 8, -1) {} }; void cmod_propagation_test::SetUp() { ctx = (struct gl_context *)calloc(1, sizeof(*ctx)); compiler = (struct brw_compiler *)calloc(1, sizeof(*compiler)); devinfo = (struct gen_device_info *)calloc(1, sizeof(*devinfo)); compiler->devinfo = devinfo; prog_data = ralloc(NULL, struct brw_wm_prog_data); nir_shader *shader = nir_shader_create(NULL, MESA_SHADER_FRAGMENT, NULL, NULL); v = new cmod_propagation_fs_visitor(compiler, prog_data, shader); devinfo->gen = 4; } static fs_inst * instruction(bblock_t *block, int num) { fs_inst *inst = (fs_inst *)block->start(); for (int i = 0; i < num; i++) { inst = (fs_inst *)inst->next; } return inst; } static bool cmod_propagation(fs_visitor *v) { const bool print = getenv("TEST_DEBUG"); if (print) { fprintf(stderr, "= Before =\n"); v->cfg->dump(v); } bool ret = v->opt_cmod_propagation(); if (print) { fprintf(stderr, "\n= After =\n"); v->cfg->dump(v); } return ret; } TEST_F(cmod_propagation_test, basic) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null dest 0.0f * * = After = * 0: add.ge.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, cmp_nonzero) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg nonzero(brw_imm_f(1.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), dest, nonzero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null dest 1.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, non_cmod_instruction) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::uint_type); fs_reg src0 = v->vgrf(glsl_type::uint_type); fs_reg zero(brw_imm_ud(0u)); bld.FBL(dest, src0); bld.CMP(bld.null_reg_ud(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: fbl(8) dest src0 * 1: cmp.ge.f0(8) null dest 0u * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_FBL, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_write) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), src2, zero, BRW_CONDITIONAL_GE); bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null src2 0.0f * 2: cmp.ge.f0(8) null dest 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_read) { const fs_builder &bld = v->bld; fs_reg dest0 = v->vgrf(glsl_type::float_type); fs_reg dest1 = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest0, src0, src1); set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero)); bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f * 2: cmp.ge.f0(8) null dest0 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_dest_write) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::vec4_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::vec2_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(offset(dest, bld, 2), src0, src1); bld.emit(SHADER_OPCODE_TEX, dest, src2) ->size_written = 4 * REG_SIZE; bld.CMP(bld.null_reg_f(), offset(dest, bld, 2), zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest+2 src0 src1 * 1: tex(8) rlen 4 dest+0 src2 * 2: cmp.ge.f0(8) null dest+2 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(SHADER_OPCODE_TEX, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_read_same_value) { const fs_builder &bld = v->bld; fs_reg dest0 = v->vgrf(glsl_type::float_type); fs_reg dest1 = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); set_condmod(BRW_CONDITIONAL_GE, bld.ADD(dest0, src0, src1)); set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero)); bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add.ge.f0(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f * 2: cmp.ge.f0(8) null dest0 0.0f * * = After = * 0: add.ge.f0(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate); } TEST_F(cmod_propagation_test, negate) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); dest.negate = true; bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null -dest 0.0f * * = After = * 0: add.le.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_LE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, movnz) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); bld.CMP(dest, src0, src1, BRW_CONDITIONAL_GE); set_condmod(BRW_CONDITIONAL_NZ, bld.MOV(bld.null_reg_f(), dest)); /* = Before = * * 0: cmp.ge.f0(8) dest src0 src1 * 1: mov.nz.f0(8) null dest * * = After = * 0: cmp.ge.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, different_types_cmod_with_zero) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::int_type); fs_reg src1 = v->vgrf(glsl_type::int_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), retype(dest, BRW_REGISTER_TYPE_F), zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest:D src0:D src1:D * 1: cmp.ge.f0(8) null:F dest:F 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, andnz_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg one(brw_imm_d(1)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_NZ, bld.AND(bld.null_reg_d(), dest, one)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.nz.f0(8) null:D dest:D 1D * * = After = * 0: cmp.l.f0(8) dest:F src0:F 0F */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_TRUE(retype(dest, BRW_REGISTER_TYPE_F) .equals(instruction(block0, 0)->dst)); } TEST_F(cmod_propagation_test, andnz_non_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg nonone(brw_imm_d(38)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_NZ, bld.AND(bld.null_reg_d(), dest, nonone)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.nz.f0(8) null:D dest:D 38D * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NZ, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, andz_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg one(brw_imm_d(1)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_Z, bld.AND(bld.null_reg_d(), dest, one)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.z.f0(8) null:D dest:D 1D * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_EQ, instruction(block0, 1)->conditional_mod); }
17,048
7,748
#include "VertexArray.h" #include <Engine/Render/API.h> using namespace Render; VertexArray::VertexArray() : indexArraySize(0) { glGenVertexArrays(1, &handle); glGenBuffers(1, &indexArrayID); } VertexArray::~VertexArray() { for(auto vbo : buffers) { deleteBuffer(vbo.id); } glDeleteBuffers(1, &indexArrayID); glDeleteVertexArrays(1, &handle); } int VertexArray::createBufferEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint) { // Create a new, null buffer buffers.push_back({0, 0}); // Get a reference to it auto& newVBO = buffers.back(); // Generate a buffer on its ID glGenBuffers(1, &newVBO.id); glBindBuffer(GL_ARRAY_BUFFER, newVBO.id); glBufferData(GL_ARRAY_BUFFER, sizeElement * numElements, data, usageHint); // Set the buffer size property newVBO.count = numElements; // And return the buffer's index in the array (last position) return buffers.size()-1; } int VertexArray::deleteBuffer(int vbo) { if(vbo >= 0 and vbo < (int)buffers.size()) { glDeleteBuffers(1, &buffers[vbo].id); buffers.erase(buffers.begin() + vbo); return vbo; } else { return -1; } } int VertexArray::getBufferCount() const { return (int)buffers.size(); } void VertexArray::setIndexArrayEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint) { if(data) { glBindVertexArray(handle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexArrayID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeElement * numElements, data, usageHint); indexArraySize = numElements; } else { indexArraySize = 0; } } void VertexArray::addAttrib(GLuint index, int vbo, GLuint size, GLenum type, GLvoid* offset, GLint stride) { glBindVertexArray(handle); glEnableVertexAttribArray(index); glBindBuffer(GL_ARRAY_BUFFER, buffers[vbo].id); glVertexAttribPointer(index, size, type, GL_FALSE, stride, offset); } void VertexArray::removeAttrib(GLuint index) { glBindVertexArray(handle); glDisableVertexAttribArray(index); } void VertexArray::drawElements(GLenum mode) { glBindVertexArray(handle); if(indexArraySize) { glDrawElements(mode, indexArraySize, GL_UNSIGNED_INT, NULL); } else { glDrawArrays(mode, 0, buffers[0].count); } }
2,444
841
#include "program_defs.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #include <stdint.h> #include <vector> #include <random> #ifdef WIN32 #define PCG_LITTLE_ENDIAN 1 #endif #include "pcg_random.hpp" // NOTE: Include order is a bit brittle due to some of these appearing exactly as they are int he RTG2 chapter. #include "functions.h" #include "balance_heuristic.h" // In article #include "sample_lights.h" // In article #include "sample_lights_pdf.h" // In article //#include "material_lambert.h" #include "material_rough.h" #include "direct_light.h" // In article #include "direct_cos.h" // In article #include "direct_mat.h" // In article #include "direct_mis.h" // In article #include "pathtrace_mis.h" // In article #include "pathtrace.h" #include "trace_wrappers.h" // Add camera-trace to functions so they can be used struct Random { pcg32 rng; std::uniform_real_distribution<float> uniform; Random() { pcg_extras::seed_seq_from<std::random_device> seed_source; rng.seed(seed_source); }; }; thread_local Random random; // NOTE: uniform is thread-safe since random generator is in a thread_local variable float uniform() { return random.uniform(random.rng); } // NOTE: This function only applies gamma. uint32_t convert_sRGB(vec3 color) { float r = color.x, g = color.y, b = color.z; r = min(max(r, 0.0), 1.0); g = min(max(g, 0.0), 1.0); b = min(max(b, 0.0), 1.0); // TODO: Is this correct? Validate r = powf(r, 1.0f/2.2f); g = powf(g, 1.0f/2.2f); b = powf(b, 1.0f/2.2f); uint8_t rb = floor(r * 255.0f); uint8_t gb = floor(g * 255.0f); uint8_t bb = floor(b * 255.0f); return 0xFF000000|(bb<<16)|(gb<<8)|rb; } inline vec3 camera_direction(float2 uv, int w, int h, float fov_horizontal_degrees) { float aspect = float(h) / float(w); float fov_factor = tanf(fov_horizontal_degrees * (float)(2.0 * PI / 360.0 * 0.5)); vec3 camera_forward = vec3(0.0f, 0.0f, 1.0f); vec3 camera_right = vec3(1.0f, 0.0f, 0.0f); vec3 camera_up = vec3(0.0f, 1.0f, 0.0f); return normalize(camera_forward + camera_right * ((uv.x * 2.0 - 1.0) * fov_factor) + camera_up * ((uv.y * 2.0 - 1.0) * fov_factor * aspect)); } typedef vec3(*renderFunction)(vec3 pos, vec3 normal); void render(const std::string &dir, const std::string &filename, const renderFunction per_pixel, int subpixels, int w = 800, int h = 600, const std::string &filename_variance = "") { printf("Rendering %s%s\n", dir.c_str(), filename.c_str()); int ws = subpixels, hs = subpixels; // Camera definition vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f); std::vector<uint32_t> result(w*h); std::vector<uint32_t> result_variance; if (!filename_variance.empty()) { result_variance.resize(w * h); } #pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { vec3 mean = vec3(0); vec3 M2 = vec3(0); int N = 0; for (int sy=0; sy<hs; sy++) { for (int sx=0; sx<ws; sx++) { float xc = (x + (sx + uniform()) / ws) * (1.0f / w); float yc = (y + (sy + uniform()) / hs) * (1.0f / h); yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left // NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel. vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f); vec3 color = per_pixel(camera_pos, dir); // Welford's online algorithm so we get variance as well // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance N++; vec3 delta = color - mean; mean += delta/N; vec3 delta2 = color - mean; M2 += delta * delta2; } } vec3 variance = M2/(N-1)/N; // Sample variance from Welford's online algorithm result[y*w+x]= convert_sRGB(mean); if (!result_variance.empty()) { if (y<8) { // Fill top-most 8 lines with pink so we don't mix the images result_variance[y * w + x] = convert_sRGB(vec3(1.0, 0.0, 1.0)); } else { result_variance[y * w + x] = convert_sRGB(vec3(sqrtf(variance.x), sqrtf(variance.y), sqrtf(variance.z))); } } } } stbi_write_png((dir+filename).c_str(), w, h, 4, result.data(), w*4); if (!filename_variance.empty()) { stbi_write_png((dir + filename_variance).c_str(), w, h, 4, result_variance.data(), w * 4); } } void render_mis_weights(const std::string& dir, const std::string &filename, int subpixels, int w = 800, int h = 600, const char* const filename_variance = nullptr) { printf("Rendering %s%s\n", dir.c_str(), filename.c_str()); int ws = subpixels, hs = subpixels; // Camera definition vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f); std::vector<uint32_t> result(w*h); #pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { vec3 mean_light = vec3(0); vec3 mean_material = vec3(0); int N = 0; for (int sy=0; sy<hs; sy++) { for (int sx=0; sx<ws; sx++) { float xc = (x + (sx + uniform()) / ws) * (1.0f / w); float yc = (y + (sy + uniform()) / hs) * (1.0f / h); yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left // NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel. vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f); vec3 color_light = trace_direct_mis_light(camera_pos, dir); vec3 color_material = trace_direct_mis_material(camera_pos, dir); mean_light += color_light / (ws*hs); mean_material += color_material / (ws*hs); } } vec3 mean_full = mean_light + mean_material; float a = dot(mean_light, mean_full); float b = dot(mean_material, mean_full); vec3 full = mean_light + mean_material; mean_light.x /= full.x; mean_light.y /= full.y; mean_light.z /= full.z; mean_material.x /= full.x; mean_material.y /= full.y; mean_material.z /= full.z; float l = a/(a+b); float m = b/(a+b); vec3 color = vec3(m,0,0) + vec3(0,l,0); result[y*w+x]= convert_sRGB(color); } } stbi_write_png((dir + filename).c_str(), w, h, 4, result.data(), w*4); } void rtg2_figures(const char * const dir) { // This is the code that was used to generate the images in the RTG2 chapter int w = 512, h = 300; // Direct light sampling int direct_N = 10; render(dir, "direct_light_sampling.png", { trace_direct_light_sampling}, direct_N, w, h); render(dir, "direct_material_sampling.png", {trace_direct_material_sampling }, direct_N, w, h); render(dir, "direct_cos_sampling.png", { trace_direct_cos_sampling }, direct_N, w, h); render(dir, "direct_mis.png", { trace_direct_mis }, direct_N, w, h); render(dir, "direct_mis_light.png", { trace_direct_mis_light<2> }, direct_N, w, h); render(dir, "direct_mis_material.png", { trace_direct_mis_material<2> }, direct_N, w, h); render(dir, "scene_description.png", { show_scene }, direct_N, w, h); // Path tracing int pathtrace_N = 15; render(dir, "pathtrace_mis.png", { pathtrace_mis_helper }, pathtrace_N, w, h); render(dir, "pathtrace_light_sampling.png", { pathtrace<direct_light> }, pathtrace_N, w, h); //render(dir, "pathtrace_material_sampling.png", { pathtrace<direct_mat> }, pathtrace_N, w, h); //render(dir, "pathtrace_hemisphere_sampling.png", { pathtrace<direct_hemi> }, pathtrace_N, w, h); // Weight image for direct MIS render_mis_weights(dir, "direct_mis_weights.png", 35, w, h); } int main(void) { rtg2_figures("../figures/"); }
7,562
3,319
/** * @file tests/tests.cpp * @brief Mega SDK main test file * * (c) 2013 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "gtest/gtest.h" using namespace mega; TEST(PayCrypter, allFeatures) { char BASE64_IV[] = "7XS3jX8CrWh6gpZIavQamA"; char BASE64_ENCKEY[] = "IcfMNKnMLJNJAH-XPMDShw"; char BASE64_HMACKEY[] = "rChwtATCap-CXO-KGxbEKZLL88lVfdZPZfZcdnMtj8o"; char KEYS[] = "IcfMNKnMLJNJAH-XPMDSh6wocLQEwmqfglzvihsWxCmSy_PJVX3WT2X2XHZzLY_K"; char CONTENT[] = "{\"first_name\": \"First\", \"last_name\": \"Last\"," " \"card_number\": \"4532646653175959\"," " \"expiry_date_month\": \"10\", \"expiry_date_year\": \"2020\"," " \"cv2\": \"123\", \"address1\": \"120 Albert St\"," " \"address2\": \"Auckland Central\", \"city\": \"Auckland\"," " \"province\": \"Auckland\", \"postal_code\": \"1010\"," " \"country_code\": \"NZ\"}"; char CIPHER_BYTES[] = "Btu6B6YxQV1oeMRij4Fn0Que9FfIE1LJyYdacVbNBM1bS-GZAtwQh5" "ZTtsakK6v_mMZGiQ3egRFSTNHzQU0jVa0GYZJ087NhlKlGtVO6PvBKmTkxpcnZpy1im" "S6uzKLccQU-IxKm1XnBF7gB7McbXDxb-j_s3-sjMJo_npDBOR3hUePGSyN-jmed7mvO" "K_fNY8DHqodpdVk7vy2PL8_iAY2SefttWGCD8DwiyxXx42KAjUaRHiYJqgdkZheF_Rp" "9l-KxgW8krDdkHsQu-nqeciezk5iA5OlylUmCfc57AKztBElyd4KIfz4B7kprmTeiiH" "8lhTCq7xZ64GdABzwfQghkf-fM9NJUD9bHfbTYfnnDRSvDrdJtD1gRVrkxnHNNVKhd6" "rtKToreM2bFhfUpcw"; char HMAC[] = "C7WRAdge50wzsAMqdM2_BVhntsP_OUYxaDMkPtRvewg"; //The same as the Javascript example char SDK_PUBKEY[] = "CACmWnYy7M5dqH7shqrj4jERfhhCfzoU5uDycAof1o8JyHu_F47b0aAB9KhKsIVKv90" "nbuea7wGuWsc0pxlrR5kKOnqMEcIQrLysFupSleqwilIgp5MUBvkPTdsn22Qc9Qldwm" "p_cbBNVfTrUVFSifv0QjDnbl7t9sLF5GgFMfYhWqMxAr3D3072cQF9eTbDLCbPD7RrC" "vUiTdqI1bT79e_187YSzCdjeVq_tZb5YnhLPHlgNQffmFJj41itSwpqrEYN8e5kIvsE" "INpHiLtXIIBBnld6NZu55U37sHeYkn5PB6cMi3ZEm90uIB7MT5CyHYLaEbJ9RkzJNRc" "xJAC2w4CnABEBAAE"; //From the Javascript example, disabling random padding (padding with 0) char CRYPT_GORT_SAYS[] = "AQB4PLTVCTdrPFXPWWCWZA3LdkjsIQgr7Ug8WBqFQlGqDR0YX0heatGVudAEb3TBOwvuoYsbOwVLOya22pqDJP6E-RUYDxbYC0dA02K7TSs97A9ZqnxnL6jvjW95X3BuR8YjStQJyy-a3FyAhrjyT9TnLOfKuUwIMLHf1eZB8H4JlAJ8VEQq9-SlusubiQZGZpYMeu2SBFJN-HI-93PEw2U3k-K6h7YYdhM-kIJ4-d2LuPWfyvuyjhs5fncgDgqPGZhq_4XOmV5Xh76aoqx8SBrPsotFvxE_CxOydivXhBMRaN6b6iL7MhuQXXDbOjvVis9uV2HnWraCxHbFwmUxoD6K"; char CRYPT_KEYS_BYTES[] = "AQB1FZOZJiEviXTXeBEOjyM6F9odENY6q4wzt73X0vVCbGBZyubKzHrNzHLaNkwGubd1RQ6wTuH3ypbK5wdM3QsyTcLq6DMv7O3JsH2R3MynRLuPGzHiNmZq2VkAMvELOo-XBeUknxrAstHZhWNQJImH4DBtnY57Mid1o-BTz7xKvRIUQvsj217CqE4CnVV6lxaloq6jvlenWATzCdEa1Q6Y8XN7hftn4Hl5ZrnAltIblBI0_fq2bkhqzZolpURbhypAg0oTFpnmj82QEBy4vwwdCOaQ8_lQjqQhsd3ah4O9gSkpYa6YoAtV9eBu338skJbhjprUVq04qi62Er_iichx"; //Initialize values byte enckey[sizeof(BASE64_ENCKEY)]; Base64::atob(BASE64_ENCKEY, enckey, sizeof(enckey)); byte iv[sizeof(BASE64_IV)]; int ivLen = Base64::atob(BASE64_IV, iv, sizeof(iv)); byte hmacKey[sizeof(BASE64_HMACKEY)]; int hmacKeyLen = Base64::atob(BASE64_HMACKEY, hmacKey, sizeof(hmacKey)); char keys[sizeof(KEYS)]; int keysLen = Base64::atob(KEYS, (byte *)keys, sizeof(keys)); byte pubkdata[sizeof(SDK_PUBKEY)]; int pubkdatalen = Base64::atob(SDK_PUBKEY, (byte *)pubkdata, sizeof(pubkdata)); ////////////////////// //Test AES-CBC encryption string result; string input = CONTENT; SymmCipher sym(enckey); sym.cbc_encrypt_pkcs_padding(&input, iv, &result); //Check result char* base64Result = new char[result.size()*4/3+4]; Base64::btoa((const byte *)result.data(), result.size(), base64Result); ASSERT_STREQ(base64Result, CIPHER_BYTES); ////////////////////// //Test AES-CBC decryption string plain; sym.cbc_decrypt_pkcs_padding(&result, iv, &plain); //Check result ASSERT_STREQ(input.c_str(), plain.c_str()); ////////////////////// //Test HMAC-SHA256 string toAuth; toAuth.assign((char *)iv, ivLen); toAuth.append(result); string mac; mac.resize(32); HMACSHA256 hmacProcessor(hmacKey, hmacKeyLen); hmacProcessor.add((byte *)toAuth.data(), toAuth.size()); hmacProcessor.get((byte *)mac.data()); //Check result char* macResult = new char[mac.size()*4/3+4]; Base64::btoa((const byte *)mac.data(), mac.size(), macResult); ASSERT_STREQ(macResult, HMAC); ////////////////////// //Test PayCrypter:encryptPayload() PrnGen rng; string payCrypterResult; PayCrypter payCrypter(rng); payCrypter.setKeys(enckey, hmacKey, iv); ASSERT_TRUE(payCrypter.encryptPayload(&input, &payCrypterResult)); //Prepare the expected result string CRYPT_PAYLOAD = mac; CRYPT_PAYLOAD.append((char *)iv, ivLen); CRYPT_PAYLOAD.append(result); char* expectedPayload = new char[CRYPT_PAYLOAD.size()*4/3+4]; Base64::btoa((const byte *)CRYPT_PAYLOAD.data(), CRYPT_PAYLOAD.size(), expectedPayload); //Check result char* encryptPayloadResult = new char[payCrypterResult.size()*4/3+4]; Base64::btoa((const byte *)payCrypterResult.data(), payCrypterResult.size(), encryptPayloadResult); ASSERT_STREQ(expectedPayload, encryptPayloadResult); ////////////////////// //Test PayCrypter:rsaEncryptKeys(), disabling random padding to get known results string message = "Klaatu barada nikto."; string rsaRes; ASSERT_TRUE(payCrypter.rsaEncryptKeys(&message, pubkdata, pubkdatalen, &rsaRes, false)); //Check result char* rsaResult = new char[rsaRes.size()*4/3+4]; Base64::btoa((const byte *)rsaRes.data(), rsaRes.size(), rsaResult); ASSERT_STREQ(rsaResult, CRYPT_GORT_SAYS); ////////////////////// //Test PayCrypter:rsaEncryptKeys() with a binary input, disabling random padding to get known results string cryptKeysBytesBin; message.assign(keys, keysLen); ASSERT_TRUE(payCrypter.rsaEncryptKeys(&message, pubkdata, pubkdatalen, &cryptKeysBytesBin, false)); //Check result char* cryptKeysBytes = new char[cryptKeysBytesBin.size()*4/3+4]; Base64::btoa((const byte *)cryptKeysBytesBin.data(), cryptKeysBytesBin.size(), cryptKeysBytes); ASSERT_STREQ(cryptKeysBytes, CRYPT_KEYS_BYTES); ////////////////////// //Test PayCrypter:hybridEncrypt() string finalResult; string contentString = CONTENT; ASSERT_TRUE(payCrypter.hybridEncrypt(&contentString, pubkdata, pubkdatalen, &finalResult, false)); //Prepare the expected result string expectedResult = cryptKeysBytesBin; expectedResult.append(CRYPT_PAYLOAD); char* expectedBase64Result = new char[expectedResult.size()*4/3+4]; Base64::btoa((const byte *)expectedResult.data(), expectedResult.size(), expectedBase64Result); //Check result char* finalCheck = new char[finalResult.size()*4/3+4]; Base64::btoa((const byte *)finalResult.data(), finalResult.size(), finalCheck); ASSERT_STREQ(finalCheck, expectedBase64Result); ////////////////////// delete[] finalCheck; delete[] expectedBase64Result; delete[] cryptKeysBytes; delete[] rsaResult; delete[] base64Result; delete[] macResult; delete[] expectedPayload; delete[] encryptPayloadResult; }
7,893
3,609
// // Example for calculating AccurateRip checksums from each track of an album, // represented by a CUESheet and a single losslessly encoded audio file. // #include <cstdint> // for uint32_t etc. #include <cstdio> // for fopen, fclose, FILE #include <iomanip> // for setw, setfill, hex #include <iostream> // for cerr, cout #include <stdexcept> // for runtime_error #include <string> // for string extern "C" { #include <libcue/libcue.h> // libcue for parsing the CUEsheet } #include <sndfile.hh> // libsndfile for reading the audio file #ifndef __LIBARCSTK_CALCULATE_HPP__ // libarcstk: calculate ARCSs #include <arcstk/calculate.hpp> #endif #ifndef __LIBARCSTK_SAMPLES_HPP__ // libarcstk: normalize input samples #include <arcstk/samples.hpp> #endif #ifndef __LIBARCSTK_LOGGING_HPP__ // libarcstk: log what you do #include <arcstk/logging.hpp> #endif // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // NOTE! THIS IS EXAMPLE CODE! IT IS INTENDED TO DEMONSTRATE HOW LIBARCSTK COULD // BE USED. IT IS NOT INTENDED TO BE USED IN REAL LIFE PRODUCTION. IT IS IN NO // WAY TESTED FOR PRODUCTION. TAKE THIS AS A STARTING POINT TO YOUR OWN // SOLUTION, NOT AS A TOOL. // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! /** * \brief Parse a CUEsheet and return offsets and implicitly the track count. * * This method is implemented without any use of libarcstk. It just has to be * available for parsing the CUESheet. * * @param[in] cuefilename Name of the CUEsheet file to parse * * @return STL-like container with a size_type holding offsets */ auto parse_cuesheet(const std::string &cuefilename) { FILE* f = std::fopen(cuefilename.c_str(), "r"); if (!f) { std::cerr << "Failed to open CUEsheet: " << cuefilename << std::endl; throw std::runtime_error("Failed to open CUEsheet"); } ::Cd* cdinfo = ::cue_parse_file(f); if (std::fclose(f)) { std::cerr << "Failed to close CUEsheet: " << cuefilename << std::endl; } f = nullptr; if (!cdinfo) { std::cerr << "Failed to parse CUEsheet: " << cuefilename << std::endl; throw std::runtime_error("Failed to parse CUEsheet"); } const auto track_count = ::cd_get_ntrack(cdinfo); std::vector<int> offsets; offsets.reserve(static_cast<decltype(offsets)::size_type>(track_count)); ::Track* track = nullptr; for (auto i = int { 1 }; i <= track_count; ++i) { track = ::cd_get_track(cdinfo, i); if (!track) { offsets.emplace_back(0); continue; } offsets.emplace_back(::track_get_start(track)); } ::cd_delete(cdinfo); return offsets; } int main(int argc, char* argv[]) { if (argc != 3) { std::cout << "Usage: albumcalc <cuesheet> <audiofile>" << std::endl; return EXIT_SUCCESS; } // Of course you would validate your input parameters in production code. const auto cuefilename { std::string { argv[1] }}; const auto audiofilename { std::string { argv[2] }}; // If you like, you can activate the internal logging of libarcstk to // see what's going on behind the scenes. We provide an appender for stdout. arcstk::Logging::instance().add_appender( std::make_unique<arcstk::Appender>("stdout", stdout)); // 'INFO' means you should probably not see anything unless you give // libarcstk unexpected input. Try 'DEBUG' or 'DEBUG1' if you want to // see more about what libarcstk is doing with your input. arcstk::Logging::instance().set_level(arcstk::LOGLEVEL::INFO); // Define input block size in number of samples, where 'sample' means a // 32 bit unsigned integer holding a pair of PCM 16 bit stereo samples. const auto samples_per_block { 16777216 }; // == 64 MB block size // libsndfile API provides the file handle for the audio file SndfileHandle audiofile(audiofilename, SFM_READ); // Skip any sanity checks you would do in production code... // Calculation will have to distinguish the tracks in the audiofile. // To identify the track bounds, we need the TOC, precisely: // 1. the number of tracks // 2. the track offset for each track // 3. the leadout frame // We derive 1. total number of tracks and 2. actual track offsets from // parsing the CUEsheet. We skip the details here for libarcstk does not // provide this functionality and the author just did a quick hack with // libcue. (Just consult the implementation of function parse_cuesheet() // if you are interested in the details, but this is libcue, not libarcstk.) const auto offsets { parse_cuesheet(cuefilename) }; // Skip santiy checks and everything you could do with try/catch ... // Two completed, one to go. Since the CUEsheet usually does not know the // length of the last track, we have to derive the leadout frame from the // audio data. We could do this quite convenient by using libarcstk's // AudioReader::acquire_size() method. But thanks to libsndfile, this is // not even necessary: the information is conveniently provided by the // audiofile handle: auto total_samples { arcstk::AudioSize { audiofile.frames(), arcstk::AudioSize::UNIT::SAMPLES } }; // Remark: what libsndfile calls "frames" is what libarcstk calls // "PCM 32 bit samples" or just "samples". Our "sample" represents a pair of // 16 bit stereo samples as a single 32 bit unsigned int (left/right). // Libsndfile's frame encodes the same information as 2 signed 16 bit // integers, one per channel. // We now have derived all relevant metadata from our input files. // Let's print it one last time before starting with the real business: for (decltype(offsets)::size_type i = 1; i < offsets.size(); ++i) { std::cout << "Track " << std::setw(2) << std::setfill(' ') << i << " offset: " << std::setw(6) << std::setfill(' ') << offsets[i-1] << std::endl; } std::cout << "Track count: " << offsets.size() << std::endl; std::cout << "Leadout: " << total_samples.leadout_frame() << std::endl; // Step 1: Use libarcstk to construct the TOC. auto toc { std::unique_ptr<arcstk::TOC> { nullptr }}; try { // This validates the parsed toc data and will throw if the parsed data // is inconsistent. toc = arcstk::make_toc(offsets, total_samples.leadout_frame()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return 1; } // Step 2: Create a context from the TOC and the name of the audiofile. // The context represents the configuration of the calculation process along // with the necessary metadata. auto context { arcstk::make_context(toc, audiofilename) }; // Step 3: Create a Calculation and provide it with the context. // We do not specify a checksum type, thus the Calculation will provide // ARCSv1 as well as ARCSv2 values as default result. auto calculation { arcstk::Calculation { std::move(context) }}; // Let's enumerate the blocks in the output. This is just to give some // informative logging. auto total_blocks { 1 + (total_samples.total_samples() - 1) / samples_per_block }; std::cout << "Expect " << total_blocks << " blocks" << std::endl; // Provide simple input buffer for libsndfile's genuine sample/frame format. // We decide to want 16 bit signed integers. const auto buffer_len { samples_per_block * 2 }; std::vector<int16_t> buffer(buffer_len); const auto samples_total { calculation.context().audio_size().total_samples() }; auto ints_in_block { int32_t { 0 }}; // Count ints read in single operation auto samples_read { int64_t { 0 }}; // Count total samples actually read // The input buffer 'buffer' holds each 16 bit sample in a single integer. // Since we have stereo audio, there are two channels, which makes one // 16 bit integer per sample for each channel in interleaved (== not planar) // order, where the 16 bit sample for the left channel makes the start. // Libarcstk is not interested in those details, so we provide the samples // via a SampleSequence that abstracts the concrete format away: arcstk::InterleavedSamples<int16_t> sequence; // NOTE: These prerequisites are just provided by libsndfile at this // site in the code. In production code, you would of course verify // things... If the channel order is switched, the sample format is // changed or the sequence is planar, the example code will screw up! // Main loop: let libsndfile read the sample in its own format, normalize it // and update the prepared Calculation with the samples read in the current // loop run. while ((ints_in_block = audiofile.read(&buffer[0], buffer_len))) { // Check whether we have read the expected amount of samples in this run if (buffer_len != ints_in_block) { // Ok, no! So, this must be the last block. Check! const auto samples_in_block { ints_in_block / arcstk::CDDA::NUMBER_OF_CHANNELS }; const auto samples_expected { samples_total - samples_read }; if (samples_in_block != samples_expected) { // Unexpected number of samples for the last block. // This is an unrecoverable error, act accordingly here. std::cerr << "Expected " << buffer_len << " integers but got " << ints_in_block << ". Bail out." << std::endl; return EXIT_FAILURE; } // Adjust buffer size of the read buffer buffer.resize( static_cast<decltype(buffer)::size_type>(ints_in_block)); } std::cout << "Read block " << (1 + samples_read / samples_per_block) << "/" << total_blocks << " (" << (buffer.size() / 2) << " samples)" << std::endl; // Wrap buffer in a reusable SampleSequence sequence.wrap_int_buffer(&buffer[0], buffer.size()); // Count PCM 32 bit stereo samples processed. samples_read += sequence.size(); // We could also compute the number of samples ourselves: // buffer.size() / static_cast<unsigned int>(CDDA::NUMBER_OF_CHANNELS) // Note: since libsndfile has told us the total sample count, we were // able to configure the context with the correct leadout. // Otherwise, we would not yet know the leadout frame number. If that // were the case we would have to provide our Calculation with this // information manually by doing: // // calculation.update_audiosize(samples_read); // // _before_ we send the last block of samples to it. This is absolutely // essential since otherwise the Calculation will not know when to stop // and eventually fail. It is sufficient to update the audio size // just before the last block of samples is passed to Calculation. Since // we can recognize the last block as demonstrated above, we can also // count the total number of samples read before the last update. // Update calculation with next portion of normalized samples. calculation.update(sequence.begin(), sequence.end()); } // Ok, no more samples. We demonstrate that the Calculation is complete: if (calculation.complete()) { std::cout << "Calculation complete" << std::endl; } else { std::cerr << "Error, calculation incomplete" << std::endl; } std::cout << "Read " << samples_read << " samples" << std::endl; // Let's finally get us the result! auto checksums { calculation.result() }; // And now, the time has come: print the actual checksums. std::cout << "Track ARCSv1 ARCSv2" << std::endl; auto trk_no { 1 }; for (const auto& track_values : checksums) { std::cout << std::dec << " " << std::setw(2) << std::setfill(' ') << trk_no << " " << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << track_values.get(arcstk::checksum::type::ARCS1).value() << " " << std::setw(8) << std::setfill('0') << track_values.get(arcstk::checksum::type::ARCS2).value() << std::endl; ++trk_no; } }
11,646
3,988
/* You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. */ /* * Win if n is not divisible by 4 */ #include "helper.h" class Solution { public: bool canWinNim(int n) { return n % 4 != 0; } }; int main() { Solution s; cout << s.canWinNim(4) << endl; return 0; }
853
257
#include <sstream> #include <unordered_map> #include "ast.hpp" class CodeGen : public Listener { public: explicit inline CodeGen() { builder = {}; indentLevel = 1; builder << "// Generated by bfc\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n"; builder << " unsigned char* memory = (unsigned char*) malloc(80000);\n memset(memory, 0, 80000);\n long long current = 40000;\n"; } inline auto toString() -> std::string { indentation(); builder << "free(memory);\n}"; return builder.str(); } protected: auto visitPrintStatement(const PrintStatement& printStatement) -> void override; auto visitInputStatement(const InputStatement& inputStatement) -> void override; auto visitShiftLeftStatement(const ShiftLeftStatement& shiftLeftStatement) -> void override; auto visitShiftRightStatement(const ShiftRightStatement& shiftLeftStatement) -> void override; auto visitIncrementStatement(const IncrementStatement& incrementStatement) -> void override; auto visitDecrementStatement(const DecrementStatement& decrementStatement) -> void override; auto enterLoopStatement(const LoopStatement& loopStatement) -> void override; auto exitLoopStatement(const LoopStatement& loopStatement) -> void override; private: std::ostringstream builder; ulong indentLevel; inline auto indentation() -> void { for (auto i = 0; i < indentLevel; ++i) builder << " "; } };
1,522
429
#include "hasmember.hpp" #include <iostream> #include <vector> #include <utility> DEFINE_HAS_MEMBER(size); DEFINE_HAS_MEMBER(first); int main() { std::cout << "int::size: " << HasMemberT_size<int>::value << '\n'; std::cout << "std::vector<int>::size: " << HasMemberT_size<std::vector<int>>::value << '\n'; std::cout << "std::pair<int,int>::first: " << HasMemberT_first<std::pair<int,int>>::value << '\n'; }
452
172
/* <base/file_reader.test.cc> ---------------------------------------------------------------------------- Copyright 2017 Dave Peterson <dave@dspeterson.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---------------------------------------------------------------------------- Unit test for <base/file_reader.h>. */ #include <base/file_reader.h> #include <cstring> #include <fstream> #include <string> #include <base/error_util.h> #include <base/tmp_file.h> #include <gtest/gtest.h> using namespace Base; namespace { class TFileReaderSimpleTest : public ::testing::Test { protected: TFileReaderSimpleTest() { } virtual ~TFileReaderSimpleTest() { } virtual void SetUp() { } virtual void TearDown() { } }; // TFileReaderSimpleTest /* The fixture for testing class TFileReader. */ class TFileReaderTest : public ::testing::Test { protected: TFileReaderTest() : FileContents("a bunch of junk"), TmpFile("/tmp/file_reader_test.XXXXXX", true /* delete_on_destroy */), Reader(TmpFile.GetName().c_str()) { } virtual ~TFileReaderTest() { } virtual void SetUp() { std::ofstream f(TmpFile.GetName().c_str(), std::ios_base::out); f << FileContents; } virtual void TearDown() { } std::string FileContents; TTmpFile TmpFile; TFileReader Reader; }; // TFileReaderTest TEST_F(TFileReaderSimpleTest, TestNoSuchFile) { TFileReader reader("/blah/this_file_should_not_exist"); bool threw = false; try { reader.GetSize(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; char buf[16]; try { reader.ReadIntoBuf(buf, sizeof(buf)); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; std::string s; try { reader.ReadIntoString(s); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; try { reader.ReadIntoString(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; std::vector<char> v; try { reader.ReadIntoBuf(v); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; try { reader.ReadIntoBuf<char>(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); } TEST_F(TFileReaderTest, TestGetSize) { ASSERT_EQ(Reader.GetSize(), FileContents.size()); /* Make sure a second GetSize() operation with the same reader works. */ ASSERT_EQ(Reader.GetSize(), FileContents.size()); } TEST_F(TFileReaderTest, TestCallerSuppliedBuf) { char buf[2 * FileContents.size()]; std::fill(buf, buf + sizeof(buf), 'x'); size_t byte_count = Reader.ReadIntoBuf(buf, sizeof(buf)); ASSERT_EQ(byte_count, FileContents.size()); ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)), 0); std::fill(buf, buf + sizeof(buf), 'x'); byte_count = Reader.ReadIntoBuf(buf, 7); ASSERT_EQ(byte_count, 7U); ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)), 0); } TEST_F(TFileReaderTest, TestCallerSuppliedBuf2) { char buf[2 * FileContents.size()]; std::fill(buf, buf + sizeof(buf), 'x'); size_t byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, sizeof(buf)); ASSERT_EQ(byte_count, FileContents.size()); ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)), 0); std::fill(buf, buf + sizeof(buf), 'x'); byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, 7); ASSERT_EQ(byte_count, 7U); ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)), 0); } TEST_F(TFileReaderTest, TestReadIntoString) { std::string s; Reader.ReadIntoString(s); ASSERT_EQ(s, FileContents); ASSERT_EQ(Reader.ReadIntoString(), FileContents); } TEST_F(TFileReaderTest, TestReadIntoString2) { std::string s; ReadFileIntoString(TmpFile.GetName(), s); ASSERT_EQ(s, FileContents); ASSERT_EQ(ReadFileIntoString(TmpFile.GetName()), FileContents); } TEST_F(TFileReaderTest, TestReadIntoVector) { std::vector<char> v1; Reader.ReadIntoBuf(v1); ASSERT_EQ(v1.size(), FileContents.size()); ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0); std::vector<char> v2 = Reader.ReadIntoBuf<char>(); ASSERT_EQ(v2, v1); } TEST_F(TFileReaderTest, TestReadIntoVector2) { std::vector<char> v1; ReadFileIntoBuf(TmpFile.GetName(), v1); ASSERT_EQ(v1.size(), FileContents.size()); ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0); std::vector<char> v2 = ReadFileIntoBuf<char>(TmpFile.GetName()); ASSERT_EQ(v2, v1); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); DieOnTerminate(); return RUN_ALL_TESTS(); }
5,650
2,039
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "TestDefinitions.h" #include "LocalDeploymentManager.h" #include "SpatialCommandUtils.h" #include "SpatialGDKDefaultLaunchConfigGenerator.h" #include "SpatialGDKDefaultWorkerJsonGenerator.h" #include "SpatialGDKEditorSettings.h" #include "CoreMinimal.h" #define LOCALDEPLOYMENT_TEST(TestName) \ GDK_TEST(Services, LocalDeployment, TestName) namespace { // TODO: UNR-1969 - Prepare LocalDeployment in CI pipeline const double MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION = 20.0; // TODO: UNR-1964 - Move EDeploymentState enum to LocalDeploymentManager enum class EDeploymentState { IsRunning, IsNotRunning }; const FName AutomationWorkerType = TEXT("AutomationWorker"); const FString AutomationLaunchConfig = TEXT("Improbable/AutomationLaunchConfig.json"); FLocalDeploymentManager* GetLocalDeploymentManager() { FSpatialGDKServicesModule& GDKServices = FModuleManager::GetModuleChecked<FSpatialGDKServicesModule>("SpatialGDKServices"); FLocalDeploymentManager* LocalDeploymentManager = GDKServices.GetLocalDeploymentManager(); return LocalDeploymentManager; } bool GenerateWorkerAssemblies() { FString BuildConfigArgs = TEXT("worker build build-config"); FString WorkerBuildConfigResult; int32 ExitCode; SpatialCommandUtils::ExecuteSpatialCommandAndReadOutput(BuildConfigArgs, FSpatialGDKServicesModule::GetSpatialOSDirectory(), WorkerBuildConfigResult, ExitCode, false); const int32 ExitCodeSuccess = 0; return (ExitCode == ExitCodeSuccess); } bool GenerateWorkerJson() { const FString WorkerJsonDir = FSpatialGDKServicesModule::GetSpatialOSDirectory(TEXT("workers/unreal")); FString JsonPath = FPaths::Combine(WorkerJsonDir, TEXT("spatialos.UnrealAutomation.worker.json")); if (!FPaths::FileExists(JsonPath)) { bool bRedeployRequired = false; return GenerateDefaultWorkerJson(JsonPath, AutomationWorkerType.ToString(), bRedeployRequired); } return true; } } DEFINE_LATENT_AUTOMATION_COMMAND(FStartDeployment); bool FStartDeployment::Update() { if (const USpatialGDKEditorSettings* SpatialGDKSettings = GetDefault<USpatialGDKEditorSettings>()) { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); const FString LaunchConfig = FPaths::Combine(FPaths::ConvertRelativePathToFull(FPaths::ProjectIntermediateDir()), AutomationLaunchConfig); const FString LaunchFlags = SpatialGDKSettings->GetSpatialOSCommandLineLaunchFlags(); const FString SnapshotName = SpatialGDKSettings->GetSpatialOSSnapshotToLoad(); AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager, LaunchConfig, LaunchFlags, SnapshotName] { if (!GenerateWorkerJson()) { return; } if (!GenerateWorkerAssemblies()) { return; } FSpatialLaunchConfigDescription LaunchConfigDescription(AutomationWorkerType); if (!GenerateDefaultLaunchConfig(LaunchConfig, &LaunchConfigDescription)) { return; } if (LocalDeploymentManager->IsLocalDeploymentRunning()) { return; } LocalDeploymentManager->TryStartLocalDeployment(LaunchConfig, LaunchFlags, SnapshotName, TEXT(""), FLocalDeploymentManager::LocalDeploymentCallback()); }); } return true; } DEFINE_LATENT_AUTOMATION_COMMAND(FStopDeployment); bool FStopDeployment::Update() { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (!LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping()) { return true; } if (!LocalDeploymentManager->IsDeploymentStopping()) { AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager] { LocalDeploymentManager->TryStopLocalDeployment(); }); } return true; } DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FWaitForDeployment, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState); bool FWaitForDeployment::Update() { const double NewTime = FPlatformTime::Seconds(); if (NewTime - StartTime >= MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION) { return true; } FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (LocalDeploymentManager->IsDeploymentStopping()) { return false; } else { return (ExpectedDeploymentState == EDeploymentState::IsRunning) ? LocalDeploymentManager->IsLocalDeploymentRunning() : !LocalDeploymentManager->IsLocalDeploymentRunning(); } } DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckDeploymentState, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState); bool FCheckDeploymentState::Update() { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (ExpectedDeploymentState == EDeploymentState::IsRunning) { Test->TestTrue(TEXT("Deployment is running"), LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping()); } else { Test->TestFalse(TEXT("Deployment is not running"), LocalDeploymentManager->IsLocalDeploymentRunning() || LocalDeploymentManager->IsDeploymentStopping()); } return true; } /* // UNR-1975 after fixing the flakiness of these tests, and investigating how they can be run in CI (UNR-1969), re-enable them LOCALDEPLOYMENT_TEST(GIVEN_no_deployment_running_WHEN_deployment_started_THEN_deployment_running) { // GIVEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); // WHEN ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning)); // THEN ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsRunning)); // Cleanup ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); return true; } LOCALDEPLOYMENT_TEST(GIVEN_deployment_running_WHEN_deployment_stopped_THEN_deployment_not_running) { // GIVEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning)); // WHEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); // THEN ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsNotRunning)); return true; }*/
6,583
2,259
#ifndef STATIC_TARGET_3_HPP_ #define STATIC_TARGET_3_HPP_ #include <iostream> #include <InterfaceTarget3/InterfaceTarget3.hpp> #include <InterfaceTarget2/InterfaceTarget2.hpp> #include <InterfaceTarget4/InterfaceTarget4.hpp> #include <StaticTarget1/StaticTarget1.hpp> #include <StaticTarget2/StaticTarget2.hpp> /** * @brief Shared target 3 public class * */ struct CStaticTarget3 : IInterfaceTarget3, IInterfaceTarget4 { /** * @brief Function 3. * */ virtual void fun_interface3() override; /** * @brief Function 4. * */ virtual void fun_interface4() override; /** * @brief Get the Interface Target2 object * * @return IInterfaceTarget2& */ IInterfaceTarget2& getInterfaceTarget2(); /** * @brief Get the Static Target1 object * * @return CStaticTarget1& */ CStaticTarget1& getStaticTarget1(); /** * @brief Get the Static Target2 object * * @return CStaticTarget2& */ CStaticTarget2& getStaticTarget2(); }; #endif // STATIC_TARGET_3_HPP_
1,003
373