text:
#include <fstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <boost/bind.hpp>

#include "TGLWidget.h"
#include "TGMsgBox.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TStopwatch.h"
#include "TTimer.h"
#include "TEveManager.h"
#include "TPRegexp.h"

#include "Fireworks/Core/interface/CmsShowMainBase.h"
#include "Fireworks/Core/interface/ActionsList.h"
#include "Fireworks/Core/interface/CSGAction.h"
#include "Fireworks/Core/interface/CSGContinuousAction.h"
#include "Fireworks/Core/interface/CmsShowMainFrame.h"
#include "Fireworks/Core/interface/CmsShowSearchFiles.h"
#include "Fireworks/Core/interface/Context.h"
#include "Fireworks/Core/interface/FWColorManager.h"
#include "Fireworks/Core/interface/FWConfigurationManager.h"
#include "Fireworks/Core/interface/FWEveViewManager.h"
#include "Fireworks/Core/interface/FWEventItemsManager.h"
#include "Fireworks/Core/interface/FWGUIManager.h"
#include "Fireworks/Core/interface/FWJobMetadataManager.h"
#include "Fireworks/Core/interface/FWMagField.h"
#include "Fireworks/Core/interface/FWBeamSpot.h"
#include "Fireworks/Core/interface/FWModelChangeManager.h"
#include "Fireworks/Core/interface/FWNavigatorBase.h"
#include "Fireworks/Core/interface/FWSelectionManager.h"
#include "Fireworks/Core/interface/FWTableViewManager.h"
#include "Fireworks/Core/interface/FWTriggerTableViewManager.h"
#include "Fireworks/Core/interface/FWGeometryTableViewManager.h"
#include "Fireworks/Core/interface/FWViewManagerManager.h"
#include "Fireworks/Core/src/CmsShowTaskExecutor.h"
#include "Fireworks/Core/src/FWColorSelect.h"
#include "Fireworks/Core/src/SimpleSAXParser.h"
#include "Fireworks/Core/interface/CmsShowCommon.h"
#include "Fireworks/Core/interface/fwLog.h"
#include "Fireworks/Core/interface/fwPaths.h"
#include "Fireworks/Core/interface/FWPartialConfig.h"

CmsShowMainBase::CmsShowMainBase()
    : m_changeManager(new FWModelChangeManager),
      m_colorManager(new FWColorManager(m_changeManager.get())),
      m_configurationManager(new FWConfigurationManager),
      m_eiManager(new FWEventItemsManager(m_changeManager.get())),
      m_guiManager(nullptr),
      m_selectionManager(new FWSelectionManager(m_changeManager.get())),
      m_startupTasks(new CmsShowTaskExecutor),
      m_viewManager(new FWViewManagerManager(m_changeManager.get(), m_colorManager.get())),
      m_autoLoadTimer(new SignalTimer()),
      m_navigatorPtr(nullptr),
      m_metadataManagerPtr(nullptr),
      m_contextPtr(nullptr),
      m_autoSaveAllViewsHeight(-1),
      m_autoLoadTimerRunning(kFALSE),
      m_forward(true),
      m_isPlaying(false),
      m_loop(false),
      m_playDelay(3.f) {
  sendVersionInfo();
}

CmsShowMainBase::~CmsShowMainBase() noexcept(false) {}

void CmsShowMainBase::setupActions() {
  m_guiManager->writeToPresentConfigurationFile_.connect(
      sigc::mem_fun(*this, &CmsShowMainBase::writeToCurrentConfigFile));

  // init TGSlider state before signals are connected
  m_guiManager->setDelayBetweenEvents(m_playDelay);

  m_navigatorPtr->newEvent_.connect(boost::bind(&CmsShowMainBase::eventChangedSlot, this));
  if (m_guiManager->getAction(cmsshow::sNextEvent) != nullptr)
    m_guiManager->getAction(cmsshow::sNextEvent)->activated.connect(sigc::mem_fun(*this, &CmsShowMainBase::doNextEvent));
  if (m_guiManager->getAction(cmsshow::sPreviousEvent) != nullptr)
    m_guiManager->getAction(cmsshow::sPreviousEvent)
        ->activated.connect(sigc::mem_fun(*this, &CmsShowMainBase::doPreviousEvent));
  if (m_guiManager->getAction(cmsshow::sGotoFirstEvent) != nullptr)
    m_guiManager->getAction(cmsshow::sGotoFirstEvent)
        ->activated.connect(sigc::mem_fun(*this, &CmsShowMainBase::doFirstEvent));
  if (m_guiManager->getAction(cmsshow::sGotoLastEvent) != nullptr)
    m_guiManager->getAction(cmsshow::sGotoLastEvent)
        ->activated.connect(sigc::mem_fun(*this, &CmsShowMainBase::doLastEvent));
  if (m_guiManager->getAction(cmsshow::sQuit) != nullptr)
    m_guiManager->getAction(cmsshow::sQuit)->activated.connect(sigc::mem_fun(*this, &CmsShowMainBase::quit));

  m_guiManager->changedEventId_.connect(boost::bind(&CmsShowMainBase::goToRunEvent, this, _1, _2, _3));
  m_guiManager->playEventsAction()->started_.connect(sigc::mem_fun(*this, &CmsShowMainBase::playForward));
  m_guiManager->playEventsBackwardsAction()->started_.connect(sigc::mem_fun(*this, &CmsShowMainBase::playBackward));
  m_guiManager->loopAction()->started_.connect(sigc::mem_fun(*this, &CmsShowMainBase::setPlayLoopImp));
  m_guiManager->loopAction()->stopped_.connect(sigc::mem_fun(*this, &CmsShowMainBase::unsetPlayLoopImp));
  m_guiManager->changedDelayBetweenEvents_.connect(boost::bind(&CmsShowMainBase::setPlayDelay, this, _1));
  m_guiManager->playEventsAction()->stopped_.connect(sigc::mem_fun(*this, &CmsShowMainBase::stopPlaying));
  m_guiManager->playEventsBackwardsAction()->stopped_.connect(sigc::mem_fun(*this, &CmsShowMainBase::stopPlaying));

  m_autoLoadTimer->timeout_.connect(boost::bind(&CmsShowMainBase::autoLoadNewEvent, this));
}

void CmsShowMainBase::setupViewManagers() {
  guiManager()->updateStatus("Setting up view manager...");

  std::shared_ptr<FWViewManagerBase> eveViewManager = std::make_shared<FWEveViewManager>(guiManager());
  eveViewManager->setContext(m_contextPtr);
  viewManager()->add(eveViewManager);

  auto tableViewManager = std::make_shared<FWTableViewManager>(guiManager());
  configurationManager()->add(std::string("Tables"), tableViewManager.get());
  viewManager()->add(tableViewManager);
  eiManager()->goingToClearItems_.connect(boost::bind(&FWTableViewManager::removeAllItems, tableViewManager.get()));

  auto triggerTableViewManager = std::make_shared<FWTriggerTableViewManager>(guiManager());
  configurationManager()->add(std::string("TriggerTables"), triggerTableViewManager.get());
  configurationManager()->add(std::string("L1TriggerTables"),
                              triggerTableViewManager.get());  // AMT: added for backward compatibilty
  triggerTableViewManager->setContext(m_contextPtr);
  viewManager()->add(triggerTableViewManager);

  auto geoTableViewManager =
      std::make_shared<FWGeometryTableViewManager>(guiManager(), m_simGeometryFilename, m_TGeoName);
  geoTableViewManager->setContext(m_contextPtr);
  viewManager()->add(geoTableViewManager);

  // Unfortunately, due to the plugin mechanism, we need to delay
  // until here the creation of the FWJobMetadataManager, because
  // otherwise the supportedTypesAndRepresentations map is empty.
  // FIXME: should we have a signal for whenever the above mentioned map
  //        changes? Can that actually happer (maybe if we add support
  //        for loading plugins on the fly??).
  m_metadataManagerPtr->initReps(viewManager()->supportedTypesAndRepresentations());
}

void CmsShowMainBase::eventChangedSlot() { eventChangedImp(); }

void CmsShowMainBase::eventChangedImp() { guiManager()->eventChangedCallback(); }

void CmsShowMainBase::doFirstEvent() {
  m_navigatorPtr->firstEvent();
  checkPosition();
  draw();
}

void CmsShowMainBase::doNextEvent() {
  m_navigatorPtr->nextEvent();
  checkPosition();
  draw();
}

void CmsShowMainBase::doPreviousEvent() {
  m_navigatorPtr->previousEvent();
  checkPosition();
  draw();
}
void CmsShowMainBase::doLastEvent() {
  m_navigatorPtr->lastEvent();
  checkPosition();
  draw();
}

void CmsShowMainBase::goToRunEvent(edm::RunNumber_t run, edm::LuminosityBlockNumber_t lumi, edm::EventNumber_t event) {
  m_navigatorPtr->goToRunEvent(run, lumi, event);
  checkPosition();
  draw();
}

void CmsShowMainBase::draw() {
  m_guiManager->updateStatus("loading event ...");

  if (m_contextPtr->getField()->getSource() != FWMagField::kUser) {
    m_contextPtr->getField()->checkFieldInfo(m_navigatorPtr->getCurrentEvent());
  }
  m_contextPtr->getBeamSpot()->checkBeamSpot(m_navigatorPtr->getCurrentEvent());

  TStopwatch sw;
  m_viewManager->eventBegin();
  m_eiManager->newEvent(m_navigatorPtr->getCurrentEvent());
  m_viewManager->eventEnd();
  sw.Stop();
  fwLog(fwlog::kDebug) << "CmsShowMainBase::draw CpuTime " << sw.CpuTime() << " RealTime " << sw.RealTime()
                       << std::endl;

  if (!m_autoSaveAllViewsFormat.empty()) {
    m_guiManager->updateStatus("auto saving images ...");
    m_guiManager->exportAllViews(m_autoSaveAllViewsFormat, m_autoSaveAllViewsHeight);
  }
  m_guiManager->clearStatus();
}

void CmsShowMainBase::setup(FWNavigatorBase *navigator,
                            fireworks::Context *context,
                            FWJobMetadataManager *metadataManager) {
  m_navigatorPtr = navigator;
  m_contextPtr = context;
  m_metadataManagerPtr = metadataManager;

  m_colorManager->initialize();
  m_contextPtr->initEveElements();
  m_guiManager.reset(new FWGUIManager(m_contextPtr, m_viewManager.get(), m_navigatorPtr));

  m_eiManager->newItem_.connect(boost::bind(&FWModelChangeManager::newItemSlot, m_changeManager.get(), _1));

  m_eiManager->newItem_.connect(boost::bind(&FWViewManagerManager::registerEventItem, m_viewManager.get(), _1));
  m_configurationManager->add("EventItems", m_eiManager.get());
  m_configurationManager->add("GUI", m_guiManager.get());
  m_configurationManager->add("EventNavigator", m_navigatorPtr);
  m_configurationManager->add("CommonPreferences",
                              m_contextPtr->commonPrefs());  // must be after GUIManager in alphabetical order

  m_guiManager->writeToConfigurationFile_.connect(boost::bind(&CmsShowMainBase::writeToConfigFile, this, _1));

  m_guiManager->loadFromConfigurationFile_.connect(boost::bind(&CmsShowMainBase::reloadConfiguration, this, _1));
  m_guiManager->loadPartialFromConfigurationFile_.connect(
      boost::bind(&CmsShowMainBase::partialLoadConfiguration, this, _1));

  m_guiManager->writePartialToConfigurationFile_.connect(
      boost::bind(&CmsShowMainBase::partialWriteToConfigFile, this, _1));

  std::string macPath(gSystem->Getenv("CMSSW_BASE"));
  macPath += "/src/Fireworks/Core/macros";
  const char *base = gSystem->Getenv("CMSSW_RELEASE_BASE");
  if (nullptr != base) {
    macPath += ":";
    macPath += base;
    macPath += "/src/Fireworks/Core/macros";
  }
  gROOT->SetMacroPath((std::string("./:") + macPath).c_str());

  m_startupTasks->tasksCompleted_.connect(boost::bind(&FWGUIManager::clearStatus, m_guiManager.get()));
}

void CmsShowMainBase::writeToConfigFile(const std::string &name) {
  m_configFileName = name;
  m_configurationManager->writeToFile(m_configFileName);
}

void CmsShowMainBase::writeToCurrentConfigFile() { m_configurationManager->writeToFile(m_configFileName); }

void CmsShowMainBase::partialWriteToConfigFile(const std::string &name) {
  std::string p = (name == "current") ? m_configFileName.c_str() : name.c_str();
  new FWPartialConfigSaveGUI(p.c_str(), m_configFileName.c_str(), m_configurationManager.get());
}

void CmsShowMainBase::reloadConfiguration(const std::string &config) {
  if (config.empty())
    return;

  m_configFileName = config;

  std::string msg = "Reloading configuration " + config + "...";
  fwLog(fwlog::kDebug) << msg << std::endl;
  m_guiManager->updateStatus(msg.c_str());
  m_guiManager->subviewDestroyAll();
  m_eiManager->clearItems();
  m_configFileName = config;
  try {
    gEve->DisableRedraw();
    m_configurationManager->readFromFile(config);
    gEve->EnableRedraw();
  } catch (SimpleSAXParser::ParserError &e) {
    Int_t chosen;
    new TGMsgBox(gClient->GetDefaultRoot(),
                 gClient->GetDefaultRoot(),
                 "Bad configuration",
                 ("Configuration " + config + " cannot be parsed: " + e.error()).c_str(),
                 kMBIconExclamation,
                 kMBCancel,
                 &chosen);
  } catch (...) {
    Int_t chosen;
    new TGMsgBox(gClient->GetDefaultRoot(),
                 gClient->GetDefaultRoot(),
                 "Bad configuration",
                 ("Configuration " + config + " cannot be parsed.").c_str(),
                 kMBIconExclamation,
                 kMBCancel,
                 &chosen);
  }

  m_guiManager->updateStatus("");
}

void CmsShowMainBase::partialLoadConfiguration(const std::string &name) {
  new FWPartialConfigLoadGUI(name.c_str(), m_configurationManager.get(), m_eiManager.get());
}

void CmsShowMainBase::setupAutoLoad(float x) {
  m_playDelay = x;
  m_guiManager->setDelayBetweenEvents(m_playDelay);
  if (!m_guiManager->playEventsAction()->isEnabled())
    m_guiManager->playEventsAction()->enable();

  m_guiManager->playEventsAction()->switchMode();
}

void CmsShowMainBase::startAutoLoadTimer() {
  m_autoLoadTimer->SetTime((Long_t)(m_playDelay * 1000));
  m_autoLoadTimer->Reset();
  m_autoLoadTimer->TurnOn();
  m_autoLoadTimerRunning = kTRUE;
}

void CmsShowMainBase::stopAutoLoadTimer() {
  m_autoLoadTimer->TurnOff();
  m_autoLoadTimerRunning = kFALSE;
}

void CmsShowMainBase::setupConfiguration() {
  m_guiManager->updateStatus("Setting up configuration...");

  try {
    gEve->DisableRedraw();
    if (m_configFileName.empty()) {
      m_configFileName = m_configurationManager->guessAndReadFromFile(m_metadataManagerPtr);
    } else {
      char *whereConfig = gSystem->Which(TROOT::GetMacroPath(), m_configFileName.c_str(), kReadPermission);
      m_configFileName = whereConfig;
      delete[] whereConfig;
      m_configurationManager->readFromFile(m_configFileName);
    }
    gEve->EnableRedraw();
  } catch (SimpleSAXParser::ParserError &e) {
    fwLog(fwlog::kError) << "Unable to load configuration file '" << m_configFileName << "': " << e.error()
                         << std::endl;
    exit(1);
  } catch (std::runtime_error &e) {
    fwLog(fwlog::kError) << "Unable to load configuration file '" << m_configFileName
                         << "' which was specified on command line. Quitting." << std::endl;
    exit(1);
  }
}

void CmsShowMainBase::setPlayDelay(Float_t val) { m_playDelay = val; }

void CmsShowMainBase::setupDebugSupport() {
  m_guiManager->updateStatus("Setting up Eve debug window...");
  m_guiManager->openEveBrowserForDebugging();
}

void CmsShowMainBase::setPlayLoop() {
  if (!m_loop) {
    setPlayLoopImp();
    m_guiManager->loopAction()->activated();
  }
}

void CmsShowMainBase::unsetPlayLoop() {
  if (m_loop) {
    unsetPlayLoopImp();
    m_guiManager->loopAction()->stop();
  }
}

void CmsShowMainBase::setPlayLoopImp() { m_loop = true; }

void CmsShowMainBase::unsetPlayLoopImp() { m_loop = false; }

void CmsShowMainBase::registerPhysicsObject(const FWPhysicsObjectDesc &iItem) { m_eiManager->add(iItem); }

void CmsShowMainBase::stopPlaying() {
  m_isPlaying = false;
  checkKeyBindingsOnPLayEventsStateChanged();
}

void CmsShowMainBase::playForward() {
  m_forward = true;
  m_isPlaying = true;
  guiManager()->enableActions(kFALSE);
  checkKeyBindingsOnPLayEventsStateChanged();
  startAutoLoadTimer();
}

void CmsShowMainBase::playBackward() {
  m_forward = false;
  m_isPlaying = true;
  guiManager()->enableActions(kFALSE);
  startAutoLoadTimer();
  checkKeyBindingsOnPLayEventsStateChanged();
}

void CmsShowMainBase::loadGeometry() {  // prepare geometry service
  // ATTN: this should be made configurable
  try {
    guiManager()->updateStatus("Loading geometry...");
    m_geom.loadMap(m_geometryFilename.c_str());
    m_contextPtr->setGeom(&m_geom);
  } catch (const std::runtime_error &iException) {
    fwLog(fwlog::kError) << "CmsShowMain::loadGeometry() caught exception: \n"
                         << m_geometryFilename << " " << iException.what() << std::endl;
    exit(0);
  }
}

void CmsShowMainBase::sendVersionInfo() {
  // Send version info to xrootd.t2.ucsd.edu receiver on port 9698.

  // receiver
  struct hostent *h = gethostbyname("xrootd.t2.ucsd.edu");
  if (!h)
    return;

  struct sockaddr_in remoteServAddr;
  remoteServAddr.sin_family = h->h_addrtype;
  memcpy((char *)&remoteServAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
  remoteServAddr.sin_port = htons(9698);

  // socket creation
  int sd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sd < 0) {
    // std::cout << "can't create socket \n";
    return;
  }
  // bind any port
  // printf("bind port\n");
  struct sockaddr_in cliAddr;
  cliAddr.sin_family = AF_INET;
  cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  cliAddr.sin_port = htons(0);

  int rc = bind(sd, (struct sockaddr *)&cliAddr, sizeof(cliAddr));
  if (rc < 0) {
    //  std::cout << "can't bind port %d " << rc << std::endl;
    return;
  }

  // get OSX version
  TString osx_version;
  try {
    std::ifstream infoFile("/System/Library/CoreServices/SystemVersion.plist");
    osx_version.ReadFile(infoFile);
    TPMERegexp re("ProductVersion\\</key\\>\\n\\t\\<string\\>(10.*)\\</string\\>");
    re.Match(osx_version);
    osx_version = re[1];
  } catch (...) {
  }

  // send data
  SysInfo_t sInfo;
  gSystem->GetSysInfo(&sInfo);
  char msg[128];

  if (gSystem->Getenv("CMSSW_VERSION")) {
    snprintf(msg, 64, "%s %s %s", gSystem->Getenv("CMSSW_VERSION"), sInfo.fOS.Data(), osx_version.Data());
  } else {
    TString versionFileName("data/version.txt");
    fireworks::setPath(versionFileName);
    std::ifstream fs(versionFileName);
    TString infoText;
    infoText.ReadLine(fs);
    fs.close();
    snprintf(msg, 64, "Standalone %s %s %s", infoText.Data(), sInfo.fOS.Data(), osx_version.Data());
  }

  int flags = 0;
  sendto(sd, msg, strlen(msg), flags, (struct sockaddr *)&remoteServAddr, sizeof(remoteServAddr));
}

max_stars_repo_name: NTrevisani/cmssw

max_issues_repo_name: NTrevisani/cmssw

max_forks_repo_name: NTrevisani/cmssw


text:
#include <boost/lockfree/detail/tagged_ptr.hpp>

#include <climits>
#define BOOST_TEST_MODULE lockfree_tests
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_CASE( tagged_ptr_test )
{
    using namespace boost::lockfree;
    int a(1), b(2);

    {
        tagged_ptr<int> i (&a, 0);
        tagged_ptr<int> j (&b, 1);

        i = j;

        BOOST_REQUIRE_EQUAL(i.get_ptr(), &b);
        BOOST_REQUIRE_EQUAL(i.get_tag(), 1);
    }

    {
        tagged_ptr<int> i (&a, 0);
        tagged_ptr<int> j (i);

        BOOST_REQUIRE_EQUAL(i.get_ptr(), j.get_ptr());
        BOOST_REQUIRE_EQUAL(i.get_tag(), j.get_tag());
    }

}

ext: cpp


text:
// Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include <algorithm>
#include <chrono>
#include <iterator>
#include <limits>
#include <numeric>
#include <random>
#include <vector>

#include <boost/functional/hash.hpp>

#include <schedule/shift/error.hpp>
#include <schedule/shift/graphserialization.hpp>

#include <poprithms/schedule/scc/scc.hpp>
#include <poprithms/schedule/shift/filteredschedule.hpp>
#include <poprithms/schedule/shift/graph.hpp>
#include <poprithms/schedule/shift/logging.hpp>
#include <poprithms/schedule/shift/schedulechange.hpp>
#include <poprithms/util/printiter.hpp>
#include <poprithms/util/stringutil.hpp>
#include <poprithms/util/unisort.hpp>

namespace poprithms {
namespace schedule {
namespace shift {

std::vector<std::array<OpAddress, 2>> Graph::getFwdLinks() const {
  std::vector<std::array<OpAddress, 2>> links;
  auto opsWithFwdLinks = getOpsWithFwdLinks();
  links.reserve(opsWithFwdLinks.size());
  for (const auto &op : opsWithFwdLinks) {
    links.push_back({op, getOp(op).getForwardLink()});
  }
  return links;
}

void Graph::updateWeight(AllocAddress aa, const AllocWeight &w) {
  allAllocs[aa].setWeight(w);
}

void Graph::disconnectAlloc(AllocAddress aa) {
  auto &alloc = allAllocs[aa];
  for (auto opAddress : alloc.getOps()) {
    auto &op = allOps[opAddress];
    op.removeAlloc(alloc.getAddress());
  }
  alloc.removeAllOps();
}

OpAddress Graph::insertOp(const std::string &dbs) {
  OpAddress op = nOps();
  allOps.push_back({op, dbs});
  return op;
}

std::vector<OpAddress>
Graph::insertOps(const std::vector<std::string> &dbStrings) {
  std::vector<OpAddress> opAdds;
  opAdds.reserve(dbStrings.size());
  for (const auto &dbs : dbStrings) {
    opAdds.push_back(insertOp(dbs));
  }
  return opAdds;
}

std::vector<std::array<OpAddress, 2>> Graph::getTightPairs() const {

  std::vector<std::array<OpAddress, 2>> tightPairs;
  for (const auto &op : getOps()) {
    if (op.nOuts() == 1UL && getOp(op.getOut(0)).nIns() == 1UL) {
      tightPairs.push_back(
          {op.getAddress(), getOp(op.getOut(0)).getAddress()});
    }
  }
  return tightPairs;
}

std::vector<OpAddress> Graph::tightChainFrom(OpAddress a) const {
  std::vector<OpAddress> chain;
  chain.push_back(a);
  auto crr = a;
  while (getOp(crr).nOuts() == 1 && getOp(getOp(crr).getOut(0)).nIns() == 1) {
    chain.push_back(getOp(crr).getOut(0));
    crr = getOp(crr).getOut(0);
  }
  return chain;
}

std::vector<std::vector<OpAddress>> Graph::getTightChains() const {
  std::vector<std::vector<OpAddress>> tightChains;

  constexpr OpAddress None{std::numeric_limits<OpAddress>::max()};

  std::vector<OpAddress> tightNext(nOps(), None);
  std::vector<OpAddress> tightPrev(nOps(), None);
  for (const auto &op : getOps()) {
    if (op.nOuts() == 1 && getOp(op.getOut(0)).nIns() == 1) {
      tightNext[op.getAddress()] = op.getOut(0);
      tightPrev[op.getOut(0)]    = op.getAddress();
    }
  }

  for (OpAddress add = 0; add < nOps(); ++add) {
    if (tightNext[add] != None && tightPrev[add] == None) {
      auto chainElm = add;
      tightChains.push_back({chainElm, tightNext[chainElm]});
      chainElm = tightNext[chainElm];
      while (tightNext[chainElm] != None) {
        chainElm = tightNext[chainElm];
        tightChains.back().push_back(chainElm);
      }
    }
  }

  return tightChains;
}

void Graph::insertOpAlloc(OpAddress oa, AllocAddress aa) {
  allAllocs[aa].insertOp(oa);
  allOps[oa].insertAlloc(aa);
}

void Graph::insertOpAlloc(const std::vector<OpAddress> &oas,
                          AllocAddress aa) {
  for (auto oa : oas) {
    insertOpAlloc(oa, aa);
  }
}

void Graph::insertBinConstraints(
    const std::vector<std::vector<OpAddress>> &bins,
    const std::string &prefix) {
  OpAddress prev = insertOp(prefix + std::to_string(0));
  for (uint64_t i = 1; i < bins.size(); ++i) {
    // a "bottleneck" Op, which partitions Ops into different bins.
    auto op = insertOp(prefix + std::to_string(i));
    for (auto b : bins[i - 1]) {
      insertConstraint(b, op);
    }
    for (auto a : bins[i]) {
      insertConstraint(op, a);
    }
    insertConstraint(prev, op);
    prev = op;
  }
}

void Graph::insertAttractions(
    const std::vector<std::array<OpAddress, 2>> &knots,
    AllocWeight w) {
  for (const auto &knot : knots) {
    auto allocAddress = insertAlloc(w);
    insertOpAlloc(std::get<0>(knot), allocAddress);
    insertOpAlloc(std::get<1>(knot), allocAddress);
  }
}

void Graph::removeConstraint(OpAddress before, OpAddress after) {
  allOps[before].removeOut(after);
  allOps[after].removeIn(before);
}

void Graph::insertConstraint(OpAddress before, OpAddress after) {
  if (before >= nOps() || after >= nOps()) {
    std::ostringstream oss;
    oss << "Cannot insert constraint " << before << " -> " << after
        << ", as there are only " << nOps() << " Ops in the shift::Graph";
    throw error(oss.str());
  }
  if (!allOps[before].hasOut(after)) {
    allOps[before].insertOut(after);
    allOps[after].insertIn(before);
  }
}

void Graph::insertLink(OpAddress before, OpAddress after) {
  if (!getOp(before).hasOut(after)) {
    insertConstraint(before, after);
  }

  const auto &op0 = getOp(before);
  const auto &op1 = getOp(after);

  if (op0.hasForwardLink() && op0.getForwardLink() != after) {
    std::ostringstream oss;
    oss << "Ops can have at most one link forward. "
        << "Op " << op0 << " already has " << getOp(op0.getForwardLink())
        << " as a forward link, and so " << op1
        << " cannot be added as a forward link.";
    throw error(oss.str());
  }

  if (op1.hasBackwardLink() && op1.getBackwardLink() != before) {
    std::ostringstream oss;
    oss << "Ops can have at most one link backward. "
        << "Op " << op1 << " already has " << getOp(op1.getBackwardLink())
        << " as a backward link, and so " << op0
        << " cannot be added as a backward link.";
    throw error(oss.str());
  }

  allOps[before].insertForwardLink(after);
  allOps[after].insertBackwardLink(before);
}

void Graph::insertConstraints(
    const std::vector<std::array<OpAddress, 2>> &cs) {
  for (const auto &c : cs) {
    insertConstraint(std::get<0>(c), std::get<1>(c));
  }
}

void Graph::append(std::ostream &ost) const {
  for (auto op : getOps()) {
    ost << '\n' << op.getDebugString() << "   <-  [";
    for (auto inAdd : op.getIns()) {
      ost << ' ' << getOp(inAdd).getDebugString() << ' ';
    }
    ost << ']';
  }
}

AllocAddress Graph::insertAlloc(AllocWeight w) {
  AllocAddress a = allAllocs.size();
  allAllocs.push_back({a, w});
  return a;
}

Graph::OpMerged Graph::getLinkMerged() const {
  return getMerged(getLinkChains());
}

Graph::OpMerged Graph::getTightMerged() const {
  return getMerged(getTightChains());
}

Graph::OpMerged
Graph::getMerged(const std::vector<std::vector<OpAddress>> &chains) const {

  Graph childGraph;

  // The Allocs are the same in the child Graph as the parent Graph
  for (const auto &parentAlloc : getAllocs()) {
    childGraph.insertAlloc(parentAlloc.getWeight());
  }

  constexpr OpAddress None{std::numeric_limits<OpAddress>::max()};

  // Map an Op in the parent Graph to its unique Op in the child Graph
  std::vector<OpAddress> parentToChild(nOps(), None);

  // We assign lowest addresses to child Ops which are generated from parent
  // chains, then the remaining addresses are assigned to the unchained Ops
  uint64_t childOpAddress{0};
  while (childOpAddress < chains.size()) {
    for (const auto opAddress : chains[childOpAddress]) {
      parentToChild[opAddress] = childOpAddress;
    }
    ++childOpAddress;
  }

  // Map an Op in the child Graph to its parent(s) in the parent Graph
  ParentGraphOps childToParents = std::move(chains);

  for (uint64_t parentAddress = 0; parentAddress < nOps(); ++parentAddress) {
    if (parentToChild[parentAddress] == None) {
      parentToChild[parentAddress] = childOpAddress;
      ++childOpAddress;
      childToParents.push_back({parentAddress});
    }
  }

  const auto nChildOps = childOpAddress;

  for (uint64_t childAddress = 0; childAddress < nChildOps; ++childAddress) {
    // The child Op's name is a concatenation of the names of the parent Ops
    const auto &parentAddresses = childToParents[childAddress];
    std::ostringstream ossChildName;
    ossChildName << '(';
    for (uint64_t i = 0; i < parentAddresses.size(); ++i) {
      if (i != 0) {
        ossChildName << ' ';
      }
      ossChildName << getOp(parentAddresses[i]).getDebugString();
    }
    ossChildName << ')';
    auto name = ossChildName.str();
    childGraph.insertOp(name);
  }

  for (uint64_t childAddress = 0; childAddress < nChildOps; ++childAddress) {

    // child Op inherits constraints and Allocs from parent(s)
    for (auto parentAddress : childToParents[childAddress]) {
      const auto &parent = getOp(parentAddress);
      for (auto allocAddress : parent.getAllocs()) {
        childGraph.insertOpAlloc(childAddress, allocAddress);
      }
      for (auto outParentAddress : parent.getOuts()) {
        auto outChildAddress = parentToChild[outParentAddress];
        if (outChildAddress != childAddress) {
          childGraph.insertConstraint(childAddress, outChildAddress);
        }
      }
    }
  }

  return {childGraph, childToParents};
}

std::vector<OpAddress> Graph::getOpsWithFwdLinks() const {
  std::vector<OpAddress> ops;
  for (const auto &op : getOps()) {
    if (op.hasForwardLink()) {
      ops.push_back(op.getAddress());
    }
  }
  return ops;
}

std::vector<std::vector<OpAddress>> Graph::getLinkChains() const {

  std::vector<std::vector<OpAddress>> chains;

  for (auto address : getOpsWithFwdLinks()) {
    // start of a chain
    if (!getOp(address).hasBackwardLink()) {
      chains.push_back({});
      auto current = address;
      while (getOp(current).hasForwardLink()) {
        chains.back().push_back(current);
        current = getOp(current).getForwardLink();
      }
      chains.back().push_back(current);
    }
  }

  return chains;
}

std::vector<std::vector<uint64_t>> Graph::getFwdEdges_u64() const {
  std::vector<std::vector<uint64_t>> edges(nOps());
  for (uint64_t from = 0; from < nOps(); ++from) {
    edges[from] = getOp(from).getOuts();
  }
  return edges;
}

std::vector<std::vector<OpAddress>> Graph::getForwardEdges() const {
  std::vector<std::vector<OpAddress>> fwdEdges(nOps());
  for (const auto &op : getOps()) {
    fwdEdges[op.getAddress()] = op.getOuts();
  }
  return fwdEdges;
}

std::vector<OpAddress> Graph::getIdenticalIns(OpAddress a) const {
  std::vector<OpAddress> sameIns;
  const auto &ins = getOp(a).getIns();
  if (ins.empty()) {
    return getInputOps();
  }
  auto in0 = ins[0];
  for (auto out : getOp(in0).getOuts()) {
    if (getOp(out).getIns() == ins) {
      sameIns.push_back(out);
    }
  }
  return sameIns;
}

uint64_t Graph::nConstraints() const {
  return std::accumulate(
      allOps.cbegin(), allOps.cend(), 0ULL, [](uint64_t n, const Op &op) {
        return n + op.nIns();
      });
}

std::ostream &operator<<(std::ostream &ost, const Graph &x) {
  x.append(ost);
  return ost;
}

void Graph::appendSerialization(std::ostream &ost) const {

  constexpr const char *const newline = "\n     ";
  ost << "{\"ops\":[";
  if (nOps() != 0) {
    ost << newline;
    getOp(0).appendSerialization(ost);
  }
  for (uint64_t i = 1; i < nOps(); ++i) {
    ost << ',';
    ost << newline;
    getOp(i).appendSerialization(ost);
  }
  ost << "],\n\"allocs\":[";
  if (nAllocs() != 0) {
    ost << newline;
    getAlloc(0).appendSerialization(ost);
  }
  for (uint64_t i = 1; i < nAllocs(); ++i) {
    ost << ',';
    ost << newline;
    getAlloc(i).appendSerialization(ost);
  }
  ost << "]}";
}

Graph Graph::fromSerializationString(const std::string &s) {
  return serialization::fromSerializationString(s);
}

void Graph::insertStartAttractorsAssert0(uint64_t opAddsSize,
                                         uint64_t priosSize) const {
  if (opAddsSize != priosSize) {
    std::ostringstream oss;
    oss << "Number of opAddresses (" << opAddsSize
        << ") is not the same as the number of priorities (" << priosSize
        << ") in insertStartAttractors.";
    throw error(oss.str());
  }
}

std::string Graph::getSerializationString() const {
  std::ostringstream oss;
  appendSerialization(oss);
  return oss.str();
}

std::vector<std::vector<OpAddress>>
Graph::constraintDiff(const std::vector<std::vector<OpAddress>> &rhs) const {

  if (nOps() != rhs.size()) {
    std::ostringstream oss;
    oss << "Graph::constraintDiff can only be called on "
        << "Edges with the same number of Ops as thisGraph. "
        << "This Graph has " << nOps() << " but \"rhs\" has " << rhs.size();
    throw error(oss.str());
  }

  std::vector<std::vector<OpAddress>> uniqueToThis(nOps());
  for (OpAddress x0 = 0; x0 < nOps(); ++x0) {
    for (OpAddress x1 : getOp(x0).getOuts()) {
      if (std::find(rhs[x0].cbegin(), rhs[x0].cend(), x1) == rhs[x0].cend()) {
        uniqueToThis[x0].push_back(x1);
      }
    }
    uniqueToThis[x0] = util::unisorted(uniqueToThis[x0]);
  }
  return uniqueToThis;
}

std::vector<OpAddress> Graph::getInputOps() const {
  std::vector<OpAddress> inputs;
  for (const auto &op : allOps) {
    if (op.nIns() == 0) {
      inputs.push_back(op.getAddress());
    }
  }
  return inputs;
}

bool Graph::operator==(const Graph &rhs) const {
  // include Op names in the comparison:
  return equalTo(rhs, true);
}
bool Graph::operator!=(const Graph &rhs) const { return !operator==(rhs); }
bool Graph::operator<(const Graph &rhs) const {
  // include Op names in the comparison
  return lessThan(rhs, true);
}
bool Graph::operator<=(const Graph &rhs) const { return !operator>(rhs); }
bool Graph::operator>(const Graph &rhs) const {
  return !operator==(rhs) && !operator<(rhs);
}
bool Graph::operator>=(const Graph &rhs) const { return !operator<(rhs); }

bool Graph::equalTo(const Graph &rhs, bool includeNames) const {
  if (allAllocs != rhs.allAllocs) {
    return false;
  }
  if (includeNames) {
    return allOps == rhs.allOps;
  } else {
    if (allOps.size() != rhs.allOps.size()) {
      return false;
    }
    for (uint64_t i = 0; i < allOps.size(); ++i) {
      if (getOp(i).getGraphComparator() !=
          rhs.getOp(i).getGraphComparator()) {
        return false;
      }
    }
  }
  return true;
}

bool Graph::lessThan(const Graph &rhs, bool includeNames) const {
  if (includeNames) {
    const auto a = std::tuple{getOps(), getAllocs()};
    const auto b = std::tuple{rhs.getOps(), rhs.getAllocs()};
    return a < b;
  }

  else {
    std::vector<Op::GraphComparator> as;
    as.reserve(nOps());
    for (const auto &op : getOps()) {
      as.push_back(op.getGraphComparator());
    }
    const auto A = std::tuple{as, getAllocs()};

    std::vector<Op::GraphComparator> bs;
    bs.reserve(rhs.nOps());
    for (const auto &op : rhs.getOps()) {
      bs.push_back(op.getGraphComparator());
    }
    const auto B = std::tuple{bs, rhs.getAllocs()};

    return A < B;
  }
}

size_t Graph::hash(bool includeNames) const {

  size_t hash = 0u;

  for (const auto &op : getOps()) {
    boost::hash_combine(hash, op.hash(includeNames));
  }

  for (const auto &alloc : getAllocs()) {
    boost::hash_combine(hash, alloc.hash());
  }

  return hash;
}

std::vector<std::vector<OpAddress>> Graph::getAllocPartitioned() const {
  std::vector<bool> visited(nOps(), false);
  std::vector<std::vector<OpAddress>> parts;
  for (uint64_t start = 0; start < nOps(); ++start) {

    // new partition, haven't seen this op yet.
    if (!visited[start]) {
      parts.push_back({});
      std::vector<OpAddress> toProcess{start};
      visited[start] = true;

      // visit all ops with related allocs.
      while (!toProcess.empty()) {
        auto current = toProcess.back();
        toProcess.pop_back();
        parts.back().push_back(current);
        for (auto alloc : getOp(current).getAllocs()) {
          for (auto nxt : getAlloc(alloc).getOps()) {
            if (!visited[nxt]) {
              visited[nxt] = true;
              toProcess.push_back(nxt);
            }
          }
        }
      }
    }
  }

  return parts;
}

std::vector<std::vector<OpAddress>> Graph::getAllocPartitionedBins() const {

  // partition the Ops by allocs. Specifically,
  //
  // op0 \in allocParts[i], and
  // op1 \in allocParts[j], where i != j,
  // means that intersect(op0.allocs(), op1.allocs()) = empty set.
  auto allocParts = getAllocPartitioned();

  // map each op to its allocation partition:
  std::vector<uint64_t> opToPart(nOps(), static_cast<uint64_t>(-1));
  for (uint64_t i = 0; i < allocParts.size(); ++i) {
    for (auto op : allocParts[i]) {
      opToPart[op] = i;
    }
  }

  // get a graph, not necessarily a DAG, where each node is the union of all
  // ops in an alloc partition (above). 'superGraph' is the forward edges of
  // this.
  std::vector<std::vector<uint64_t>> superGraph(allocParts.size());
  for (uint64_t inOpPart = 0; inOpPart < allocParts.size(); ++inOpPart) {
    for (auto inOp : allocParts[inOpPart]) {
      for (auto outOp : getOp(inOp).getOuts()) {
        auto &x        = superGraph[inOpPart];
        auto outOpPart = opToPart[outOp];
        if (inOpPart != outOpPart) {
          if (std::find(x.cbegin(), x.cend(), outOpPart) == x.cend()) {
            x.push_back(outOpPart);
          }
        }
      }
    }
  }

  // merge partition groups which are connected in a cycle, and create bins.
  auto scc = scc::getStronglyConnectedComponents(superGraph);
  std::vector<std::vector<OpAddress>> bins;
  bins.reserve(scc.size());
  for (const auto &comp : scc) {
    bins.push_back({});
    for (auto part : comp) {
      for (auto op : allocParts[part]) {
        bins.back().push_back(op);
      }
    }
  }

  return bins;
}

void Graph::update(AllocAddress aa,
                   const std::vector<OpAddress> &toKeep,
                   const std::vector<OpAddress> &toRemove) {

  if (toKeep.size() + toRemove.size() != allAllocs[aa].nOps()) {
    std::ostringstream oss;
    oss << "Error in Graph::update(AllocAddress = " << aa << ", toKeep = ";
    util::append(oss, toKeep);
    oss << ", toRemove = ";
    util::append(oss, toRemove);
    oss << "). The combined sizes of toKeep and toRemove should be "
        << allAllocs[aa].nOps() << '.';
    throw error("Logic rror, toKeep.size() + toRemove.size() != nOps()");
  }

  for (auto opId : toRemove) {
    allOps[opId].removeAlloc(aa);
  }

  allAllocs[aa].resetOps(toKeep);
}

} // namespace shift
} // namespace schedule
} // namespace poprithms

max_stars_repo_name: graphcore/poprithms

max_issues_repo_name: graphcore/poprithms

max_forks_repo_name: graphcore/poprithms


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_WEBSOCKET_IMPL_TEARDOWN_HPP
#define BOOST_BEAST_WEBSOCKET_IMPL_TEARDOWN_HPP

#include <boost/beast/core/async_op_base.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/stream_traits.hpp>
#include <boost/beast/core/detail/type_traits.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/post.hpp>
#include <memory>

namespace boost {
namespace beast {
namespace websocket {

namespace detail {

template<class Handler>
class teardown_tcp_op
    : public beast::async_op_base<
        Handler, beast::executor_type<
            net::ip::tcp::socket>>
    , public net::coroutine
{
    using socket_type = net::ip::tcp::socket;

    socket_type& s_;
    role_type role_;
    bool nb_;

public:
    template<class Handler_>
    teardown_tcp_op(
        Handler_&& h,
        socket_type& s,
        role_type role)
        : async_op_base<Handler,
            beast::executor_type<
                net::ip::tcp::socket>>(
                    std::forward<Handler_>(h), s.get_executor())
        , s_(s)
        , role_(role)
    {
    }

    void
    operator()(
        error_code ec = {},
        std::size_t bytes_transferred = 0)
    {
        using tcp = net::ip::tcp;
        BOOST_ASIO_CORO_REENTER(*this)
        {
            nb_ = s_.non_blocking();
            s_.non_blocking(true, ec);
            if(! ec)
            {
                if(role_ == role_type::server)
                    s_.shutdown(tcp::socket::shutdown_send, ec);
            }
            if(ec)
            {
                BOOST_ASIO_CORO_YIELD
                net::post(
                    s_.get_executor(),
                    beast::bind_front_handler(std::move(*this), ec, 0));
                goto upcall;
            }
            for(;;)
            {
                {
                    char buf[2048];
                    s_.read_some(
                        net::buffer(buf), ec);
                }
                if(ec == net::error::would_block)
                {
                    BOOST_ASIO_CORO_YIELD
                    s_.async_wait(
                        net::ip::tcp::socket::wait_read,
                            std::move(*this));
                    continue;
                }
                if(ec)
                {
                    if(ec != net::error::eof)
                        goto upcall;
                    ec = {};
                    break;
                }
                if(bytes_transferred == 0)
                {
                    // happens sometimes
                    // https://github.com/boostorg/beast/issues/1373
                    break;
                }
            }
            if(role_ == role_type::client)
                s_.shutdown(tcp::socket::shutdown_send, ec);
            if(ec)
                goto upcall;
            s_.close(ec);
        upcall:
            {
                error_code ignored;
                s_.non_blocking(nb_, ignored);
            }
            this->invoke(ec);
        }
    }
};

} // detail

//------------------------------------------------------------------------------

void
teardown(
    role_type role,
    net::ip::tcp::socket& socket,
    error_code& ec)
{
    if(role == role_type::server)
        socket.shutdown(
            net::ip::tcp::socket::shutdown_send, ec);
    if(ec)
        return;
    for(;;)
    {
        char buf[2048];
        auto const bytes_transferred =
            socket.read_some(net::buffer(buf), ec);
        if(ec)
        {
            if(ec != net::error::eof)
                return;
            ec = {};
            break;
        }
        if(bytes_transferred == 0)
        {
            // happens sometimes
            // https://github.com/boostorg/beast/issues/1373
            break;
        }
    }
    if(role == role_type::client)
        socket.shutdown(
            net::ip::tcp::socket::shutdown_send, ec);
    if(ec)
        return;
    socket.close(ec);
}

template<class TeardownHandler>
void
async_teardown(
    role_type role,
    net::ip::tcp::socket& socket,
    TeardownHandler&& handler)
{
    static_assert(beast::detail::is_invocable<
        TeardownHandler, void(error_code)>::value,
            "TeardownHandler requirements not met");
    detail::teardown_tcp_op<typename std::decay<
        TeardownHandler>::type>(std::forward<
            TeardownHandler>(handler), socket,
                role)();
}

} // websocket
} // beast
} // boost

#endif

ext: hpp

max_stars_repo_name: bebuch/beast

max_issues_repo_name: bebuch/beast

max_forks_repo_name: bebuch/beast


text:
/*
 * File:   main.cpp
 * Author: mlilback
 *
 * Created on February 26, 2015, 2:47 PM
 */

#include <cstdlib>
#include <unistd.h>
#include <signal.h>
#include "RServer.hpp"
#include "tclap/CmdLine.h"
#include "common/RC2Utils.hpp"
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>

using namespace std;
namespace fs = boost::filesystem;

static void event_callback(evutil_socket_t socket, short events, void *objptr);
static void terminate_app(evutil_socket_t socket, short events, void *objptr);

RServer::RServer()
{
	signal(SIGCHLD, SIG_IGN); //auto-reap child processes
	_port = 7714;
	struct event_config *config = event_config_new();
	event_config_require_features(config, EV_FEATURE_FDS);
	_eventBase = event_base_new_with_config(config);
	event_config_free(config);
	//add signal handler event for basic kill signal
	auto evt = event_new(_eventBase, SIGTERM, EV_SIGNAL|EV_PERSIST, terminate_app, this);
	event_add(evt, nullptr);
}

RServer::~RServer()
{
	event_base_free(_eventBase);
}

void
RServer::startRunLoop()
{
	evutil_socket_t listener;
	struct sockaddr_in sin;
	struct event *listener_event;

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = 0;
	sin.sin_port = htons(_port);

	listener = socket(AF_INET, SOCK_STREAM, 0);
	evutil_make_socket_nonblocking(listener);
	int one = 1;
	setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
	if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
		cerr << "error binding socket " << errno << endl;
		exit(-1);
	}
	if (listen(listener, 16) < 0) {
		cerr << "error listening " << errno << endl;
		exit(-1);
	}
	listener_event = event_new(_eventBase, listener, EV_READ|EV_PERSIST, event_callback, this);
	if (nullptr == listener_event) {
		cerr << "failed to create event " << errno << endl;
		exit(-1);
	}
	event_add(listener_event, nullptr);

	cerr << "listening" << endl;

	int drc = event_base_dispatch(_eventBase);
}

void
RServer::handleEvent(evutil_socket_t listener, short events)
{
	const char *libKey = "R_Libs";
	string installLoc = RC2::GetPathForExecutable(getpid());
	string::size_type pos = installLoc.rfind('/');
	string path = installLoc.substr(0, pos) + "/rsession";

	struct sockaddr_in clientAddr;
	socklen_t clientLen = sizeof(clientAddr);
	int clientSock = accept(listener, (struct sockaddr*)&clientAddr, &clientLen);
	if (clientSock == -1) {
		cerr << "Errorr accepting connection: " << errno << endl;
		return;
	}
	_verbose && cout << "client accepted" << endl;
	int option = 1;
	setsockopt(clientSock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
	char pidstr[16];
	sprintf(pidstr, "%d", clientSock);
	const char *args[5];
	args[0] = "rsession";
	args[1] = "-s";
	args[2] = pidstr;
	args[3] = _verbose ? "-v" : nullptr;
	args[4] = nullptr;
	if (_shouldFork) {
		int forkResult = fork();
		if (forkResult == 0) {
			close(_socket); // close our copy of listening socket
			execve(path.c_str(), (char *const *)args, environ);
			//only get here if there was an error with execve
			std::cerr << "Error with execve:" << errno << std::endl;
			exit(1);
		} else if (forkResult == -1) {
			std::cerr << "failed to fork:" << errno << std::endl;
			close(clientSock);
		} else {
			// parent process continuing. close our copy of new socket
			close(clientSock);
		}
	} else {
		execve(path.c_str(), (char *const *)args, environ);
		//only get here if there was an error with execve
		std::cerr << "Error with execve:" << errno << std::endl;
		exit(1);
	}
}

bool
RServer::parseArgs(int argc, char** argv)
{
	try {
		TCLAP::CmdLine cmdLine("Listen for rcompute connections", ' ', "0.1");

		TCLAP::ValueArg<uint32_t> portArg("p", "port", "port to listen on",
			false, 7714, "port", cmdLine);

		TCLAP::SwitchArg switchArg("v", "verbose", "enable logging", cmdLine);
		TCLAP::SwitchArg forkArg("f", "fork", "fork multiple sessions", cmdLine, true);

		cmdLine.parse(argc, argv);
		_port = portArg.getValue();
		_verbose = switchArg.getValue();
		_shouldFork = forkArg.getValue();

	} catch (TCLAP::ArgException &e) {
		std::cerr << "error:" << e.error() << std::endl;
	}
	return true;
}

void
RServer::terminate()
{
	event_base_loopexit(_eventBase, nullptr);
}

static void
terminate_app(evutil_socket_t socket, short events, void *objptr)
{
	RServer *server = static_cast<RServer*>(objptr);
	server->terminate();
}

static void
event_callback(evutil_socket_t socket, short events, void *objptr)
{
	RServer *server = static_cast<RServer*>(objptr);
	server->handleEvent(socket, events);
}


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//  Copyright (c)      2013 Thomas Heller
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx_fwd.hpp>
#include <hpx/exception.hpp>
#include <hpx/util/batch_environment.hpp>

#include <iostream>
#include <fstream>

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/tokenizer.hpp>
#include <boost/format.hpp>

#define BOOST_SPIRIT_USE_PHOENIX_V3

#include <boost/spirit/include/qi.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/phoenix/statement.hpp>
#include <boost/phoenix/stl.hpp>
#include <boost/phoenix/fusion.hpp>
#include <boost/phoenix/scope.hpp>
#include <boost/phoenix/bind.hpp>
#include <boost/fusion/include/pair.hpp>

namespace {
    struct construct_nodes
    {
        typedef void result_type;

        typedef std::vector<std::string> vector_type;

        typedef
            boost::optional<
                std::vector<
                    vector_type
                >
            >
            optional_type;

        typedef
            std::vector<
                boost::fusion::vector<
                    std::string
                  , optional_type
                >
            >
            param_type;

        result_type operator()(std::vector<std::string> & nodes, param_type const & p) const
        {
            typedef param_type::value_type value_type;

            std::vector<std::string> tmp_nodes;

            BOOST_FOREACH(value_type const & value, p)
            {
                std::string const & prefix = boost::fusion::at_c<0>(value);
                optional_type const & ranges = boost::fusion::at_c<1>(value);
                bool push_now = tmp_nodes.empty();
                if(ranges)
                {
                    BOOST_FOREACH(vector_type const & range, *ranges)
                    {
                        if(range.size() == 1)
                        {
                            std::string s(prefix);
                            s += range[0];
                            if(push_now)
                            {
                                tmp_nodes.push_back(s);
                            }
                            else
                            {
                                BOOST_FOREACH(std::string & node, tmp_nodes)
                                {
                                    node += s;
                                }
                            }
                        }
                        else
                        {
                            std::size_t begin = boost::lexical_cast<std::size_t>(range[0]);
                            std::size_t end = boost::lexical_cast<std::size_t>(range[1]);
                            if(begin > end) std::swap(begin, end);

                            std::vector<std::string> vs;

                            for(std::size_t i = begin; i <= end; ++i)
                            {
                                std::string s(prefix);
                                if(i < 10 && range[0].length() > 1)
                                    s += "0";
                                if(i < 100 && range[0].length() > 2)
                                    s += "0";
                                s += boost::lexical_cast<std::string>(i);
                                if(push_now)
                                {
                                    tmp_nodes.push_back(s);
                                }
                                else
                                {
                                    vs.push_back(s);
                                }
                            }
                            if(!push_now)
                            {
                                std::vector<std::string> tmp;
                                std::swap(tmp, tmp_nodes);
                                BOOST_FOREACH(std::string s, tmp)
                                {
                                    BOOST_FOREACH(std::string const & s2, vs)
                                    {
                                        s += s2;
                                        tmp_nodes.push_back(s);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if(push_now)
                    {
                        tmp_nodes.push_back(prefix);
                    }
                    else
                    {
                        BOOST_FOREACH(std::string & node, tmp_nodes)
                        {
                            node += prefix;
                        }
                    }
                }
            }
            nodes.insert(nodes.end(), tmp_nodes.begin(), tmp_nodes.end());
        }
    };

    void add_tasks_per_node(std::size_t idx, std::size_t n, std::vector<std::size_t> & nodes)
    {
        for(std::size_t i = 0; i < n; ++i)
        {
            nodes.push_back(idx);
        }
    }
}

namespace hpx { namespace util
{
    // The function will analyze the current environment and return true
    // if it finds sufficient information to deduce its running as a batch job.
    bool batch_environment::found_batch_environment() const
    {
        // All we have to do for now is to identify SLURM, as PBS does not
        // provide sufficient environment variable to deduce all required
        // information.
        // (https://computing.llnl.gov/linux/slurm/srun.html)
        return std::getenv("SLURM_NODELIST") &&
               std::getenv("SLURM_PROCID");
    }

    // this function tries to read from a PBS node-file, filling our
    // map of nodes and thread counts
    std::string batch_environment::init_from_file(std::string const& nodefile,
        std::string const& agas_host)
    {
        if (!nodefile.empty()) {
            boost::asio::io_service io_service;
            std::ifstream ifs(nodefile.c_str());
            if (ifs.is_open()) {
                if (debug_)
                    std::cerr << "opened: " << nodefile << std::endl;

                bool found_agas_host = false;
                std::size_t agas_node_num = 0;
                std::string line;
                while (std::getline(ifs, line)) {
                    if (!line.empty()) {
                        if (debug_)
                            std::cerr << "read: '" << line << "'" << std::endl;

                        boost::asio::ip::tcp::endpoint ep =
                            util::resolve_hostname(line, 0, io_service);

                        if (!found_agas_host) {
                            if ((agas_host.empty() && nodes_.empty()) ||
                                line == agas_host)
                            {
                                agas_node_ = line;
                                found_agas_host = true;
                                agas_node_num_ = agas_node_num;
                            }

                            if (0 == nodes_.count(ep)) {
                                if (debug_)
                                    std::cerr << "incrementing agas_node_num"
                                              << std::endl;
                                ++agas_node_num;
                            }
                        }

                        std::pair<std::string, std::size_t>& data = nodes_[ep];
                        if (data.first.empty())
                            data.first = line;
                        ++data.second;
                    }
                }

                // if an AGAS host is specified, it needs to be in the list
                // of nodes participating in this run
                if (!agas_host.empty() && !found_agas_host) {
                    throw std::logic_error("Requested AGAS host (" +
                        agas_host + ") not found in node list");
                }

                if (debug_) {
                    if (!agas_node_.empty()) {
                        std::cerr << "using AGAS host: '" << agas_node_
                                  << "' (node number " << agas_node_num_ << ")"
                                  << std::endl;
                    }

                    std::cerr << "Nodes from file:" << std::endl;
                    node_map_type::const_iterator end = nodes_.end();
                    for (node_map_type::const_iterator it = nodes_.begin();
                         it != end; ++it)
                    {
                        std::cerr << (*it).second.first << ": "
                            << (*it).second.second << " (" << (*it).first
                            << ")" << std::endl;
                    }
                }
            }
            else {
                if (debug_)
                    std::cerr << "failed opening: " << nodefile << std::endl;

                // raise hard error if nodefile could not be opened
                throw std::logic_error(boost::str(boost::format(
                    "Could not open nodefile: '%s'") % nodefile));
            }
        }

        return nodefile;
    }

    // this function initializes the map of nodes from the given (space
    // separated) list of nodes
    std::string batch_environment::init_from_nodelist(
        std::vector<std::string> const& nodes,
        std::string const& agas_host)
    {
        if (debug_)
            std::cerr << "got node list" << std::endl;

        boost::asio::io_service io_service;

        bool found_agas_host = false;
        std::size_t agas_node_num = 0;
        std::string nodes_list;
        BOOST_FOREACH(std::string s, nodes)
        {
            if (!s.empty()) {
                if (debug_)
                    std::cerr << "extracted: '" << s << "'" << std::endl;

                boost::asio::ip::tcp::endpoint ep =
                    util::resolve_hostname(s, 0, io_service);

                if (!found_agas_host &&
                    ((agas_host.empty() && nodes_.empty()) || s == agas_host))
                {
                    agas_node_ = s;
                    found_agas_host = true;
                    agas_node_num_ = agas_node_num;
                }

                if (0 == nodes_.count(ep)) {
                    if (debug_)
                        std::cerr << "incrementing agas_node_num" << std::endl;
                    ++agas_node_num;
                }

                std::pair<std::string, std::size_t>& data = nodes_[ep];
                if (data.first.empty())
                    data.first = s;
                ++data.second;

                nodes_list += s + ' ';
            }
        }

        // if an AGAS host is specified, it needs to be in the list
        // of nodes participating in this run
        if (!agas_host.empty() && !found_agas_host) {
            throw std::logic_error("Requested AGAS host (" + agas_host +
                ") not found in node list");
        }

        if (debug_) {
            if (!agas_node_.empty()) {
                std::cerr << "using AGAS host: '" << agas_node_
                    << "' (node number " << agas_node_num_ << ")" << std::endl;
            }

            std::cerr << "Nodes from nodelist:" << std::endl;
            node_map_type::const_iterator end = nodes_.end();
            for (node_map_type::const_iterator it = nodes_.begin();
                 it != end; ++it)
            {
                std::cerr << (*it).second.first << ": "
                    << (*it).second.second << " (" << (*it).first << ")"
                    << std::endl;
            }
        }
        return nodes_list;
    }

    // this function initializes the map of nodes from the environment
    std::string batch_environment::init_from_environment(
        std::string const& agas_host)
    {
        char* slurm_nodelist_env = std::getenv("SLURM_NODELIST");

        /** FIXME: use that info
        char* tasks_per_node_env = std::getenv("SLURM_TASKS_PER_NODE");

        std::vector<std::size_t> tasks_per_node;
        if (tasks_per_node_env)
        {
            if (debug_) {
                std::cerr << "SLURM tasks per node found: " << tasks_per_node_env
                          << std::endl;
            }

            std::string tasks_per_node_str(tasks_per_node_env);
            std::string::iterator begin = tasks_per_node_str.begin();
            std::string::iterator end = tasks_per_node_str.end();
            int i = 0;

            namespace qi = boost::spirit::qi;
            namespace phoenix = boost::phoenix;

            qi::parse(
                begin
              , end
              , (
                    (qi::int_ >> "(x" >> qi::int_ >> ')')[
                        phoenix::bind(::add_tasks_per_node, qi::_1, qi::_2, phoenix::ref(tasks_per_node))
                    ]
                | qi::int_[
                        phoenix::push_back(
                            phoenix::ref(tasks_per_node)
                        , qi::_1
                        )
                  ]
                ) % ','
            );
        }
        **/

        if (slurm_nodelist_env)
        {
            if (debug_) {
                std::cerr << "SLURM nodelist found: " << slurm_nodelist_env
                          << std::endl;
            }

            std::string nodelist_str(slurm_nodelist_env);
            std::string::iterator begin = nodelist_str.begin();
            std::string::iterator end = nodelist_str.end();

            std::vector<std::string> nodes;

            namespace qi = boost::spirit::qi;
            namespace phoenix = boost::phoenix;

            qi::rule<std::string::iterator, std::string()>
                prefix;
            prefix %= +(qi::print - (qi::char_("[") | qi::char_(",")));

            qi::rule<std::string::iterator, std::string()>
                range_str;
            range_str %= +(qi::print - (qi::char_("]") | qi::char_( ",") | qi::char_("-")));

            qi::rule<std::string::iterator, std::vector<std::string>()>
                range;
            range %= range_str >> *('-' >> range_str);

            qi::rule<std::string::iterator,
                    boost::fusion::vector<
                        std::string,
                        boost::optional<std::vector<std::vector<std::string> > >
                    >()>
                ranges;
            ranges %= prefix >> -(qi::lit("[") >> (range % ',') >> qi::lit("]"));

            qi::rule<std::string::iterator>
                hostlist = (+ranges)[
                                phoenix::bind(::construct_nodes(),
                                    phoenix::ref(nodes), qi::_1)
                           ];

            qi::rule<std::string::iterator>
                nodelist = hostlist % ',';

            qi::parse(
                begin
              , end
              , nodelist
            );

            /*
            std::cout << nodelist_str << "\n";
            std::cout << "---\n";
            for(std::string const & s: nodes) std::cout << s << "\n";
            std::cout << "---\n";
            */

            return init_from_nodelist(nodes, agas_host);
        }
        return std::string();
    }

    // The number of threads is either one (if no PBS information was
    // found), or it is the same as the number of times this node has
    // been listed in the node file.
    std::size_t batch_environment::retrieve_number_of_threads() const
    {
        std::size_t result = 1;
        char* slurm_cpus_per_task = std::getenv("SLURM_CPUS_PER_TASK");
        if(slurm_cpus_per_task)
        {
            try {
                std::string value(slurm_cpus_per_task);
                result = boost::lexical_cast<std::size_t>(value);
                if (debug_) {
                    std::cerr << "retrieve_number_of_threads (SLURM_CPUS_PER_TASK): "
                              << result << std::endl;
                }
                return result;
            }
            catch (boost::bad_lexical_cast const&) {
                ; // just ignore the error
            }
        }
        else
        {
            char* slurm_cpus_on_node = std::getenv("SLURM_CPUS_ON_NODE");
            if (slurm_cpus_on_node) {
                try {
                    std::string value(slurm_cpus_on_node);
                    result = boost::lexical_cast<std::size_t>(value);
                    if (debug_) {
                        std::cerr << "retrieve_number_of_threads (SLURM_CPUS_ON_NODE): "
                                  << result << std::endl;
                    }
                    return result;
                }
                catch (boost::bad_lexical_cast const&) {
                    ; // just ignore the error
                }
            }
        }

        if (!nodes_.empty()) {
            // fall back to counting the number of occurrences of this node
            // in the node-file
            boost::asio::io_service io_service;
            boost::asio::ip::tcp::endpoint ep = util::resolve_hostname(
                host_name(), 0, io_service);

            node_map_type::const_iterator it = nodes_.find(ep);
            if (it == nodes_.end()) {
                throw std::logic_error("Cannot retrieve number of OS threads "
                    "for host_name: " + host_name());
            }
            result = (*it).second.second;
        }
        if (debug_)
            std::cerr << "retrieve_number_of_threads: " << result << std::endl;
        return result;
    }

    // The number of localities is either one (if no PBS information
    // was found), or it is the same as the number of distinct node
    // names listed in the node file.
    std::size_t batch_environment::retrieve_number_of_localities() const
    {
        std::size_t result = nodes_.empty() ? 1 : nodes_.size();
        if (debug_) {
            std::cerr << "retrieve_number_of_localities: " << result
                << std::endl;
        }
        return result;
    }

    // Try to retrieve the node number from the PBS environment
    std::size_t batch_environment::retrieve_node_number() const
    {
        char* nodenum_env = std::getenv("PBS_NODENUM");
        if (!nodenum_env)
            nodenum_env = std::getenv("SLURM_PROCID");

        if (nodenum_env) {
            try {
                std::string value(nodenum_env);
                std::size_t result = boost::lexical_cast<std::size_t>(value);
                if (debug_) {
                    std::cerr << "retrieve_node_number (PBS_NODENUM/SLURM_PROCID): "
                              << result << std::endl;
                }
                return result;
            }
            catch (boost::bad_lexical_cast const&) {
                ; // just ignore the error
            }
        }
        if (debug_)
            std::cerr << "retrieve_node_number: -1" << std::endl;

        return std::size_t(-1);
    }

    std::string batch_environment::host_name() const
    {
        std::string hostname = boost::asio::ip::host_name();
        if (debug_)
            std::cerr << "asio host_name: " << hostname << std::endl;
        return hostname;
    }

    std::string batch_environment::host_name(std::string const& def_hpx_name) const
    {
        std::string host = nodes_.empty() ? def_hpx_name : host_name();
        if (debug_)
            std::cerr << "host_name: " << host << std::endl;
        return host;
    }

    // We either select the first host listed in the node file or a given
    // host name to host the AGAS server.
    std::string batch_environment::agas_host_name(std::string const& def_agas) const
    {
        std::string host = agas_node_.empty() ? def_agas : agas_node_;
        if (debug_)
            std::cerr << "agas host_name: " << host << std::endl;
        return host;
    }

    bool batch_environment::run_with_pbs() const
    {
        return std::getenv("PBS_NODENUM") != 0 ? true : false;
    }

    bool batch_environment::run_with_slurm() const
    {
        return std::getenv("SLURM_PROCID") != 0 ? true : false;
    }

    // Return a string containing the name of the batch system
    std::string batch_environment::get_batch_name() const
    {
        if (run_with_pbs())
            return "PBS";
        if (run_with_slurm())
            return "SLURM";
        return "";
    }
}}

max_stars_repo_name: andreasbuhr/hpx

max_issues_repo_name: andreasbuhr/hpx

max_forks_repo_name: andreasbuhr/hpx


text:
/*=============================================================================
    Copyright (c) 2003 Joel de Guzman
    Copyright (c) 2004 Peder Holt

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_ITERATOR_PRIOR_HPP)
#define FUSION_ITERATOR_PRIOR_HPP

#include <boost/spirit/fusion/detail/config.hpp>
#include <boost/spirit/fusion/iterator/as_fusion_iterator.hpp>

namespace boost { namespace fusion
{
    namespace meta
    {
        template <typename Tag>
        struct prior_impl
        {
            template <typename Iterator>
            struct apply {};
        };

        template <typename Iterator>
        struct prior
        {
            typedef as_fusion_iterator<Iterator> converter;
            typedef typename converter::type iter;

            typedef typename
                prior_impl<FUSION_GET_TAG(iter)>::
                    template apply<iter>::type
            type;
        };
    }

    template <typename Iterator>
    inline typename meta::prior<Iterator>::type
    prior(Iterator const& i)
    {
        typedef as_fusion_iterator<Iterator> converter;
        typedef typename converter::type iter;

        return meta::prior_impl<FUSION_GET_TAG(iter)>::
            template apply<iter>::call(converter::convert(i));
    }
}}

#endif

max_stars_repo_name: dstrigl/mcotf

max_issues_repo_name: dstrigl/mcotf

max_forks_repo_name: dstrigl/mcotf


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef GENLIKESNPDATASINK_HPP
#define GENLIKESNPDATASINK_HPP

#include <iostream>
#include <string>
#include <Eigen/Core>
#include "genfile/snp_data_utils.hpp"
#include "genfile/gen.hpp"
#include "genfile/SNPDataSink.hpp"

namespace genfile {
	// This class represents a SNPDataSink which writes its data
	// to a flat file in a GEN-like format.
	// That is, SNP identifying data goes at the start of the line
	// followed by a sequence of numbers representing the data.
	class GenLikeSNPDataSink: public SNPDataSink
	{
	public:
		GenLikeSNPDataSink( std::string const& filename, Chromosome chromosome, CompressionType compression_type ) ;
		SinkPos get_stream_pos() const ;
		void omit_chromosome() ;
		std::string get_spec() const ;

	protected:

		operator bool() const ;
		std::ostream& stream() { return *m_stream_ptr ; }
		std::string const& filename() const { return m_filename ; }
		void write_variant( std::ostream& out, genfile::VariantIdentifyingData const& variant ) ;
		bool write_chromosome_column() const { return m_write_chromosome_column ; }

	private:
		void setup( std::string const& filename, CompressionType compression_type ) ;

		std::string m_filename ;
		std::auto_ptr< std::ostream > m_stream_ptr ;

		Chromosome m_chromosome ;
		bool m_write_chromosome_column ;
		CompressionType m_compression_type ;
	} ;
}

#endif

max_stars_repo_name: gavinband/bingwa

max_issues_repo_name: gavinband/bingwa

max_forks_repo_name: gavinband/bingwa


text:
//
// Created by realngnx on 11/06/2021.
//

#ifndef OPLB_TIMER_HPP
#define OPLB_TIMER_HPP

#include <cstdlib>
#include <map>
#include <boost/asio.hpp>
#include "sharding/node.hpp"
#include "sharding/sharder.hpp"

class timer {
public:
    boost::asio::deadline_timer scheduler;

    timer(boost::asio::io_service &io_service, std::map<std::string, std::string> &configuration);

    void schedule(void (&fun)(const boost::system::error_code & /*e*/, timer *scheduler,
                              std::map<std::string, std::string> &config, ConsistentHash& sharder), ConsistentHash& param);

private:
    std::map<std::string, std::string> &config;

    void set_interval();
};

#endif //OPLB_TIMER_HPP

max_stars_repo_name: oystr-foss/proxy-load-balancer

max_issues_repo_name: oystr-foss/proxy-load-balancer

max_forks_repo_name: oystr-foss/proxy-load-balancer


text:
#define CATCH_CONFIG_RUNNER
#include "../../vendor/catch/catch.hpp"

#include "thread_utility.hpp"
#include "types.hpp"
#include <boost/optional/optional_io.hpp>

TEST_CASE("get_key_code") {
  {
    auto actual = krbn::types::get_key_code(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad),
                                            krbn::hid_usage(kHIDUsage_KeyboardTab));
    REQUIRE(*actual == krbn::key_code(kHIDUsage_KeyboardTab));
  }
  {
    auto actual = krbn::types::get_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorTopCase),
                                            krbn::hid_usage(krbn::kHIDUsage_AV_TopCase_KeyboardFn));
    REQUIRE(*actual == krbn::key_code::fn);
  }
  {
    auto actual = krbn::types::get_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorKeyboard),
                                            krbn::hid_usage(krbn::kHIDUsage_AppleVendorKeyboard_Function));
    REQUIRE(*actual == krbn::key_code::fn);
  }
  {
    auto actual = krbn::types::get_key_code(krbn::hid_usage_page(kHIDPage_Button),
                                            krbn::hid_usage(1));
    REQUIRE(actual == boost::none);
  }
}

TEST_CASE("get_key_code (modifier_flag)") {
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::zero) == boost::none);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::caps_lock) == krbn::key_code::caps_lock);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::left_control) == krbn::key_code::left_control);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::left_shift) == krbn::key_code::left_shift);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::left_option) == krbn::key_code::left_option);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::left_command) == krbn::key_code::left_command);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::right_control) == krbn::key_code::right_control);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::right_shift) == krbn::key_code::right_shift);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::right_option) == krbn::key_code::right_option);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::right_command) == krbn::key_code::right_command);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::fn) == krbn::key_code::fn);
  REQUIRE(krbn::types::get_key_code(krbn::modifier_flag::end_) == boost::none);
}

TEST_CASE("get_modifier_flag") {
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::caps_lock) == krbn::modifier_flag::zero);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::left_control) == krbn::modifier_flag::left_control);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::left_shift) == krbn::modifier_flag::left_shift);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::left_option) == krbn::modifier_flag::left_option);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::left_command) == krbn::modifier_flag::left_command);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::right_control) == krbn::modifier_flag::right_control);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::right_shift) == krbn::modifier_flag::right_shift);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::right_option) == krbn::modifier_flag::right_option);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::right_command) == krbn::modifier_flag::right_command);
  REQUIRE(krbn::types::get_modifier_flag(krbn::key_code::fn) == krbn::modifier_flag::fn);

  REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)) == krbn::modifier_flag::zero);
  REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardErrorRollOver)) == krbn::modifier_flag::zero);
  REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardLeftShift)) == krbn::modifier_flag::left_shift);
  REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::button, krbn::hid_usage(1)) == krbn::modifier_flag::zero);
}

TEST_CASE("make_consumer_key_code") {
  REQUIRE(krbn::types::make_consumer_key_code(krbn::hid_usage_page::consumer, krbn::hid_usage::csmr_mute) == krbn::consumer_key_code::mute);
  REQUIRE(!krbn::types::make_consumer_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)));

  REQUIRE(krbn::types::make_hid_usage_page(krbn::consumer_key_code::mute) == krbn::hid_usage_page::consumer);
  REQUIRE(krbn::types::make_hid_usage(krbn::consumer_key_code::mute) == krbn::hid_usage::csmr_mute);
}

TEST_CASE("get_pointing_button") {
  {
    auto actual = krbn::types::get_pointing_button(krbn::hid_usage_page(kHIDPage_Button),
                                                   krbn::hid_usage(1));
    REQUIRE(*actual == krbn::pointing_button::button1);
  }
  {
    auto actual = krbn::types::get_pointing_button(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad),
                                                   krbn::hid_usage(kHIDUsage_KeyboardTab));
    REQUIRE(actual == boost::none);
  }
}

TEST_CASE("make_new_device_id") {
  auto device_id1 = krbn::types::make_new_device_id(krbn::vendor_id(1234),
                                                    krbn::product_id(5678),
                                                    true,
                                                    false);
  auto device_id2 = krbn::types::make_new_device_id(krbn::vendor_id(2345),
                                                    krbn::product_id(6789),
                                                    false,
                                                    true);

  REQUIRE(krbn::types::find_device_identifiers(device_id1)->get_vendor_id() == krbn::vendor_id(1234));
  REQUIRE(krbn::types::find_device_identifiers(device_id1)->get_product_id() == krbn::product_id(5678));
  REQUIRE(krbn::types::find_device_identifiers(device_id1)->get_is_keyboard() == true);
  REQUIRE(krbn::types::find_device_identifiers(device_id1)->get_is_pointing_device() == false);

  REQUIRE(krbn::types::find_device_identifiers(device_id2)->get_vendor_id() == krbn::vendor_id(2345));
  REQUIRE(krbn::types::find_device_identifiers(device_id2)->get_product_id() == krbn::product_id(6789));
  REQUIRE(krbn::types::find_device_identifiers(device_id2)->get_is_keyboard() == false);
  REQUIRE(krbn::types::find_device_identifiers(device_id2)->get_is_pointing_device() == true);

  REQUIRE(krbn::types::find_device_identifiers(krbn::device_id(-1)) == nullptr);

  krbn::types::detach_device_id(device_id1);
  krbn::types::detach_device_id(krbn::device_id(-1));

  REQUIRE(krbn::types::find_device_identifiers(device_id1) == nullptr);
}

int main(int argc, char* const argv[]) {
  krbn::thread_utility::register_main_thread();
  return Catch::Session().run(argc, argv);
}

max_stars_repo_name: rcmdnk/Karabiner-Elements

max_issues_repo_name: rcmdnk/Karabiner-Elements

max_forks_repo_name: rcmdnk/Karabiner-Elements


text:
#include "Parser.h"
#include "Exceptions.h"

#include <boost/spirit/home/x3.hpp>

namespace x3 = boost::spirit::x3;

void dysysim::Parser::trim(std ::string &str, const std::string &whitespace)
{
   const auto strBegin = str.find_first_not_of(whitespace);
   if (strBegin == std::string::npos) {
      str.clear();
      return;
   }
   const auto strEnd = str.find_last_not_of(whitespace);
   const auto strRange = strEnd - strBegin + 1;

   str = str.substr(strBegin, strRange);
}

void dysysim::Parser::removeSingleLineComment(std::string &str)
{
   size_t pos{str.find("//")};
   if (pos != std::string::npos) {
      str.erase(pos);
   }
}

dysysim::Parser::result_t dysysim::Parser::operator()(int lineNumber,
                                                      std::string &codeLine)
{
   result_t result{-1, "", {}, {}};

   auto set_id = [&result](auto &ctx) {
      // std::cout << "ID = " << x3::_attr(ctx) << "\n";
      std::get<0>(result) = x3::_attr(ctx);
   };

   auto set_type = [&result](auto &ctx) {
      // std::cout << "Type = " << x3::_attr(ctx) << "\n";
      std::get<1>(result) = x3::_attr(ctx);
   };

   auto set_input = [&result](auto &ctx) {
      // std::cout << "Input = " << x3::_attr(ctx) << "\n";
      std::get<2>(result).push_back(x3::_attr(ctx));
   };

   auto set_param = [&result](auto &ctx) {
      // std::cout << "Param = " << x3::_attr(ctx) << "\n";
      std::get<3>(result).push_back(x3::_attr(ctx));
   };

   auto set_t_end = [this](auto &ctx) { t_end_ = x3::_attr(ctx); };

   auto set_delta_t = [this](auto &ctx) { delta_t_ = x3::_attr(ctx); };

   Parser::removeSingleLineComment(codeLine);
   Parser::trim(codeLine, " \t");

   if (!codeLine.empty()) {
      auto iter = begin(codeLine);
      auto iterEnd = end(codeLine);

      auto id = x3::uint_;
      auto type = (+x3::char_("A-Z"));
      auto value = x3::double_;
      auto parameter_name = x3::alpha >> *(x3::alnum | x3::char_('_'));
      auto inputs =
         x3::int_[set_input] >> *(x3::char_(',') >> x3::int_[set_input]);
      auto set_parameter = parameter_name >> '=' >> value[set_param];
      auto set_sim_parameters = x3::lit("delta_t") >> '=' >>
                                value[set_delta_t] >> x3::lit("t_end") >> '=' >>
                                value[set_t_end];
      auto set_simblock_parameters =
         id[set_id] >> type[set_type] >> *(inputs) >> *(set_parameter);

      if (simParametersAreSet_) {
         auto codeline = set_simblock_parameters;
         auto p = x3::phrase_parse(iter, iterEnd, codeline, x3::space);

         if (not(p and iter == iterEnd)) {
            throw dysysim::SyntaxError(lineNumber, codeLine);
         }
      } else {
         auto codeline = set_sim_parameters;
         auto p = x3::phrase_parse(iter, iterEnd, codeline, x3::space);

         if (not(p and iter == iterEnd)) {
            throw dysysim::SyntaxError(lineNumber, codeLine);
         }
         simParametersAreSet_ = true;
      }
   }

   return result;
}

max_stars_repo_name: josokw/Fuzzy

max_issues_repo_name: josokw/Fuzzy

max_forks_repo_name: josokw/Fuzzy


text:
// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.

#include <boost/fusion/include/at_key.hpp>
#include <boost/fusion/include/define_assoc_struct.hpp>

#include <string>
using namespace boost::fusion;

// sample(introspection-then)
namespace keys {
  struct name;
  struct age;
}

BOOST_FUSION_DEFINE_ASSOC_STRUCT(
  /* global scope */, Person,
  (std::string, name, keys::name)
  (int, age, keys::age)
)

int main() {
    Person john{"John", 30};
    std::string name = at_key<keys::name>(john);
    int age = at_key<keys::age>(john);
}
// end-sample


text:
/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionFunctionCollection.h"
#include "mitkNumericTypes.h"

#include <boost/math/special_functions/legendre.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include <boost/version.hpp>
#include <itkPointShell.h>
#include "itkVectorContainer.h"
#include "vnl/vnl_vector.h"
#include <vtkBox.h>
#include <vtkMath.h>
#include <itksys/SystemTools.hxx>
#include <boost/algorithm/string.hpp>

// Intersect a finite line (with end points p0 and p1) with all of the
// cells of a vtkImageData
std::vector< std::pair< itk::Index<3>, double > > mitk::imv::IntersectImage(const itk::Vector<double,3>& spacing, itk::Index<3>& si, itk::Index<3>& ei, itk::ContinuousIndex<float, 3>& sf, itk::ContinuousIndex<float, 3>& ef)
{
  std::vector< std::pair< itk::Index<3>, double > > out;
  if (si == ei)
  {
    double d[3];
    for (int i=0; i<3; ++i)
      d[i] = (sf[i]-ef[i])*spacing[i];
    double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );
    out.push_back(  std::pair< itk::Index<3>, double >(si, len) );
    return out;
  }

  double bounds[6];

  double entrancePoint[3];
  double exitPoint[3];

  double startPoint[3];
  double endPoint[3];

  double t0, t1;
  for (int i=0; i<3; ++i)
  {
    startPoint[i] = sf[i];
    endPoint[i] = ef[i];

    if (si[i]>ei[i])
    {
      int t = si[i];
      si[i] = ei[i];
      ei[i] = t;
    }
  }

  for (int x = si[0]; x<=ei[0]; ++x)
    for (int y = si[1]; y<=ei[1]; ++y)
      for (int z = si[2]; z<=ei[2]; ++z)
      {
        bounds[0] = (double)x - 0.5;
        bounds[1] = (double)x + 0.5;
        bounds[2] = (double)y - 0.5;
        bounds[3] = (double)y + 0.5;
        bounds[4] = (double)z - 0.5;
        bounds[5] = (double)z + 0.5;

        int entryPlane;
        int exitPlane;
        int hit = vtkBox::IntersectWithLine(bounds,
                                            startPoint,
                                            endPoint,
                                            t0,
                                            t1,
                                            entrancePoint,
                                            exitPoint,
                                            entryPlane,
                                            exitPlane);
        if (hit)
        {
          if (entryPlane>=0 && exitPlane>=0)
          {
            double d[3];
            for (int i=0; i<3; ++i)
              d[i] = (exitPoint[i] - entrancePoint[i])*spacing[i];
            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );

            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;
            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );
          }
          else if (entryPlane>=0)
          {
            double d[3];
            for (int i=0; i<3; ++i)
              d[i] = (ef[i] - entrancePoint[i])*spacing[i];
            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );

            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;
            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );
          }
          else if (exitPlane>=0)
          {
            double d[3];
            for (int i=0; i<3; ++i)
              d[i] = (exitPoint[i]-sf[i])*spacing[i];
            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );

            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;
            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );
          }
        }
      }
  return out;
}

//------------------------- SH-function ------------------------------------

double mitk::sh::factorial(int number) {
  if(number <= 1) return 1;
  double result = 1.0;
  for(int i=1; i<=number; i++)
    result *= i;
  return result;
}

void mitk::sh::Cart2Sph(double x, double y, double z, double *spherical)
{
  double phi, th, rad;
  rad = sqrt(x*x+y*y+z*z);
  if( rad < mitk::eps )
  {
    th = itk::Math::pi/2;
    phi = itk::Math::pi/2;
  }
  else
  {
    th = acos(z/rad);
    phi = atan2(y, x);
  }
  spherical[0] = phi;
  spherical[1] = th;
  spherical[2] = rad;
}

vnl_vector_fixed<double, 3> mitk::sh::Sph2Cart(const double& theta, const double& phi, const double& rad)
{
  vnl_vector_fixed<double, 3> dir;
  dir[0] = rad * sin(theta) * cos(phi);
  dir[1] = rad * sin(theta) * sin(phi);
  dir[2] = rad * cos(theta);
  return dir;
}

double mitk::sh::legendre0(int l)
{
  if( l%2 != 0 )
  {
    return 0;
  }
  else
  {
    double prod1 = 1.0;
    for(int i=1;i<l;i+=2) prod1 *= i;
    double prod2 = 1.0;
    for(int i=2;i<=l;i+=2) prod2 *= i;
    return pow(-1.0,l/2.0)*(prod1/prod2);
  }
}

double mitk::sh::Yj(int m, int l, float theta, float phi, bool mrtrix)
{
  if (!mrtrix)
  {
    if (m<0)
      return sqrt(2.0)*::boost::math::spherical_harmonic_r(l, -m, theta, phi);
    else if (m==0)
      return ::boost::math::spherical_harmonic_r(l, m, theta, phi);
    else
      return pow(-1.0,m)*sqrt(2.0)*::boost::math::spherical_harmonic_i(l, m, theta, phi);
  }
  else
  {
    double plm = ::boost::math::legendre_p<float>(l,abs(m),-cos(theta));
    double mag = sqrt((double)(2*l+1)/(4.0*itk::Math::pi)*::boost::math::factorial<float>(l-abs(m))/::boost::math::factorial<float>(l+abs(m)))*plm;
    if (m>0)
      return mag*cos(m*phi);
    else if (m==0)
      return mag;
    else
      return mag*sin(-m*phi);
  }

  return 0;
}

vnl_matrix<float> mitk::sh::CalcShBasisForDirections(int sh_order, vnl_matrix<double> U, bool mrtrix)
{
  vnl_matrix<float> sh_basis  = vnl_matrix<float>(U.cols(), (sh_order*sh_order + sh_order + 2)/2 + sh_order );
  for(unsigned int i=0; i<U.cols(); i++)
  {
    double x = U(0,i);
    double y = U(1,i);
    double z = U(2,i);
    double spherical[3];
    mitk::sh::Cart2Sph(x,y,z,spherical);
    U(0,i) = spherical[0];
    U(1,i) = spherical[1];
    U(2,i) = spherical[2];
  }

  for(unsigned int i=0; i<U.cols(); i++)
  {
    for(int k=0; k<=sh_order; k+=2)
    {
      for(int m=-k; m<=k; m++)
      {
        int j = (k*k + k + 2)/2 + m - 1;
        double phi = U(0,i);
        double th = U(1,i);
        sh_basis(i,j) = mitk::sh::Yj(m,k,th,phi, mrtrix);
      }
    }
  }

  return sh_basis;
}

float mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const double theta, const double phi, const bool mrtrix)
{
  float val = 0;
  for(int k=0; k<=sh_order; k+=2)
  {
    for(int m=-k; m<=k; m++)
    {
      int j = (k*k + k + 2)/2 + m - 1;
      val += coefficients[j] * mitk::sh::Yj(m, k, theta, phi, mrtrix);
    }
  }

  return val;
}

float mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const vnl_vector_fixed<double, 3> &dir, const bool mrtrix)
{
  double spherical[3];
  mitk::sh::Cart2Sph(dir[0], dir[1], dir[2], spherical);

  float val = 0;
  for(int k=0; k<=sh_order; k+=2)
  {
    for(int m=-k; m<=k; m++)
    {
      int j = (k*k + k + 2)/2 + m - 1;
      val += coefficients[j] * mitk::sh::Yj(m, k, spherical[1], spherical[0], mrtrix);
    }
  }

  return val;
}

//------------------------- gradients-function ------------------------------------

mitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::ReadBvalsBvecs(std::string bvals_file, std::string bvecs_file, double& reference_bval)
{
  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();

  std::vector<float> bvec_entries;
  if (!itksys::SystemTools::FileExists(bvecs_file))
    mitkThrow() << "bvecs file not existing: " << bvecs_file;
  else
  {
    std::string line;
    std::ifstream myfile (bvecs_file.c_str());
    if (myfile.is_open())
    {
      while (std::getline(myfile, line))
      {
        std::vector<std::string> strs;
        boost::split(strs,line,boost::is_any_of("\t \n"));
        for (auto token : strs)
        {
          if (!token.empty())
          {
            try
            {
              bvec_entries.push_back(boost::lexical_cast<float>(token));
            }
            catch(...)
            {
              mitkThrow() << "Encountered invalid bvecs file entry >" << token << "<";
            }
          }
        }
      }
      myfile.close();
    }
    else
    {
      mitkThrow() << "bvecs file could not be opened: " << bvals_file;
    }
  }

  reference_bval = -1;
  std::vector<float> bval_entries;
  if (!itksys::SystemTools::FileExists(bvals_file))
    mitkThrow() << "bvals file not existing: " << bvals_file;
  else
  {
    std::string line;
    std::ifstream myfile (bvals_file.c_str());
    if (myfile.is_open())
    {
      while (std::getline(myfile, line))
      {
        std::vector<std::string> strs;
        boost::split(strs,line,boost::is_any_of("\t \n"));
        for (auto token : strs)
        {
          if (!token.empty())
          {
            try {
              bval_entries.push_back(boost::lexical_cast<float>(token));
              if (bval_entries.back()>reference_bval)
                reference_bval = bval_entries.back();
            }
            catch(...)
            {
              mitkThrow() << "Encountered invalid bvals file entry >" << token << "<";
            }
          }
        }
      }
      myfile.close();
    }
    else
    {
      mitkThrow() << "bvals file could not be opened: " << bvals_file;
    }
  }

  for(unsigned int i=0; i<bval_entries.size(); i++)
  {
    double b_val = bval_entries.at(i);

    mitk::gradients::GradientDirectionType vec;
    vec[0] = bvec_entries.at(i);
    vec[1] = bvec_entries.at(i+bval_entries.size());
    vec[2] = bvec_entries.at(i+2*bval_entries.size());

    // Adjust the vector length to encode gradient strength
    double factor = b_val/reference_bval;
    if(vec.magnitude() > 0)
    {
      vec.normalize();
      vec[0] = sqrt(factor)*vec[0];
      vec[1] = sqrt(factor)*vec[1];
      vec[2] = sqrt(factor)*vec[2];
    }

    directioncontainer->InsertElement(i,vec);
  }

  return directioncontainer;
}

void mitk::gradients::WriteBvalsBvecs(std::string bvals_file, std::string bvecs_file, GradientDirectionContainerType::Pointer gradients, double reference_bval)
{
  std::ofstream myfile;
  myfile.open (bvals_file.c_str());
  for(unsigned int i=0; i<gradients->Size(); i++)
  {
    double twonorm = gradients->ElementAt(i).two_norm();
    myfile << std::round(reference_bval*twonorm*twonorm) << " ";
  }
  myfile.close();

  std::ofstream myfile2;
  myfile2.open (bvecs_file.c_str());
  for(int j=0; j<3; j++)
  {
    for(unsigned int i=0; i<gradients->Size(); i++)
    {
      GradientDirectionType direction = gradients->ElementAt(i);
      direction.normalize();
      myfile2 << direction.get(j) << " ";
    }
    myfile2 << std::endl;
  }
}

std::vector<unsigned int> mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType *refGradientsContainer )
{

  IndiciesVector directioncontainer;
  auto mapIterator = refBValueMap.begin();

  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)
    mapIterator++; //skip bzero Values

  for( ; mapIterator != refBValueMap.end(); mapIterator++){

    IndiciesVector currentShell = mapIterator->second;

    while(currentShell.size()>0)
    {
      unsigned int wntIndex = currentShell.back();
      currentShell.pop_back();

      auto containerIt = directioncontainer.begin();
      bool directionExist = false;
      while(containerIt != directioncontainer.end())
      {
        if (fabs(dot_product(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex)))  > 0.9998)
        {
          directionExist = true;
          break;
        }
        containerIt++;
      }
      if(!directionExist)
      {
        directioncontainer.push_back(wntIndex);
      }
    }
  }

  return directioncontainer;
}

bool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer)
{
  auto mapIterator = refBValueMap.begin();

  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)
    mapIterator++; //skip bzero Values

  for( ; mapIterator != refBValueMap.end(); mapIterator++){

    auto mapIterator_2 = refBValueMap.begin();
    if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)
      mapIterator_2++; //skip bzero Values

    for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){

      if(mapIterator_2 == mapIterator) continue;

      IndiciesVector currentShell = mapIterator->second;
      IndiciesVector testShell = mapIterator_2->second;
      for (unsigned int i = 0; i< currentShell.size(); i++)
        if (fabs(dot_product(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i])))  <= 0.9998) { return true; }

    }
  }
  return false;
}

vnl_matrix<double> mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer)
{

  vnl_matrix<double> Q(3, refShell.size());
  Q.fill(0.0);

  for(unsigned int i = 0; i < refShell.size(); i++)
  {
    GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]);
    double x = dir.normalize().get(0);
    double y = dir.normalize().get(1);
    double z = dir.normalize().get(2);
    double cart[3];
    mitk::sh::Cart2Sph(x,y,z,cart);
    Q(0,i) = cart[0];
    Q(1,i) = cart[1];
    Q(2,i) = cart[2];
  }
  return Q;
}

vnl_matrix<double> mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix<double> & QBallReference, const unsigned int & LOrder)
{
  vnl_matrix<double> SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5);
  SHBasisOutput.fill(0.0);
  for(int i=0; i< (int)SHBasisOutput.rows(); i++)
    for(int k = 0; k <= (int)LOrder; k += 2)
      for(int m =- k; m <= k; m++)
      {
        int j = ( k * k + k + 2 ) / 2.0 + m - 1;
        double phi = QBallReference(0,i);
        double th = QBallReference(1,i);
        double val = mitk::sh::Yj(m,k,th,phi);
        SHBasisOutput(i,j) = val;
      }
  return SHBasisOutput;
}

mitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap,
                                                                                const GradientDirectionContainerType *origninalGradentcontainer)
{
  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();
  auto mapIterator = bValueMap.begin();

  if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){
    mapIterator++; //skip bzero Values
    vnl_vector_fixed<double, 3> vec;
    vec.fill(0.0);
    directioncontainer->push_back(vec);
  }

  for( ; mapIterator != bValueMap.end(); mapIterator++){

    IndiciesVector currentShell = mapIterator->second;

    while(currentShell.size()>0)
    {
      unsigned int wntIndex = currentShell.back();
      currentShell.pop_back();

      mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin();
      bool directionExist = false;
      while(containerIt != directioncontainer->End())
      {
        if (fabs(dot_product(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex)))  > 0.9998)
        {
          directionExist = true;
          break;
        }
        containerIt++;
      }
      if(!directionExist)
      {
        GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex));
        directioncontainer->push_back(dir.normalize());
      }
    }
  }

  return directioncontainer;
}

max_stars_repo_name: wyyrepo/MITK

max_issues_repo_name: wyyrepo/MITK

max_forks_repo_name: wyyrepo/MITK


text:
//  Boost checked_delete test program  ---------------------------------------//

//  Copyright Beman Dawes 2001.  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)

//  See http://www.boost.org/libs/utility for documentation.

//  Revision History
//  21 May 01  Initial version (Beman Dawes)

#include <boost/checked_delete.hpp>  // for checked_delete

//  This program demonstrates compiler errors when trying to delete an
//  incomplete type.

namespace
{
    class Incomplete;
}

int main()
{
    Incomplete * p = 0;
    boost::checked_delete(p);          // should cause compile time error
    return 0;
}   // main