<commit_before>#ifndef _SENSOR_NODE_
#define _SENSOR_NODE_

#include <Homie.h>
#include "BME280_Impl.hpp"
#include "DHTxx_Impl.hpp"
#include "SHT30_Impl.hpp"

class Sensor {
  public:
    Sensor();
    virtual ~Sensor();

    void setup();
    bool publish();

  private:
    // taken from adafruit DHT library
    float computeHeatIndex(float temperature, float relativeHumidity) const;
    // Sättigungsdampfdruck in hPa
    double SDD(float temperature) const;
    // Dampfdruck in hPa
    double DD(float temperature, float relativeHumidity) const;
    // Taupunkt in °C
    float TD(float temperature, float relativeHumidity) const;
    // absolute Feuchte in g Wasserdampf pro m3 Luft
    float AF(float temperature, float relativeHumidity) const;
    // check and update the health state. publish health state if it has changed.
    void checkHealth();

    SensorInterface *sensor;
    SensorInterface::SensorState ss;
    unsigned long errors;
    static constexpr char* dht11 = "dht11";
    static constexpr char* dht21 = "dht21";
    static constexpr char* dht22 = "dht22";
    static constexpr char* bme280 = "bme280";
    static constexpr char* sht30 = "sht30";
    HomieSetting<const char*> typeSetting;
    HomieNode *sensorStateNode;
    HomieNode *temperatureNode;
    HomieNode *humidityNode;
    HomieNode *preasureNode;
};

inline Sensor::Sensor()
  : sensor(NULL)
  , ss(SensorInterface::unknown)
  , errors(0)
  , typeSetting("type", "Type of the sensor. Use either  \"dht11\", \"dht21\", \"dht22\", \"bme280\" or \"sht30\"")
  , sensorStateNode(NULL)
  , temperatureNode(NULL)
  , humidityNode(NULL)
  , preasureNode(NULL) {
  typeSetting.setDefaultValue(dht11).setValidator([] (const char* candidate) {
    return (String(candidate) == dht11) ||
           (String(candidate) == dht21) ||
           (String(candidate) == dht22) ||
           (String(candidate) == bme280) ||
           (String(candidate) == sht30);
  });

  sensorStateNode = new HomieNode("healthState", "healthState");
  temperatureNode = new HomieNode("temperature", "temperature");
  humidityNode = new HomieNode("humidity", "humidity");
  preasureNode = new HomieNode("preasure", "preasure");

  sensorStateNode->advertise("health");
  sensorStateNode->advertise("errors");
  temperatureNode->advertise("absolut");
  temperatureNode->advertise("heatindex");
  humidityNode->advertise("relative");
  humidityNode->advertise("absolute");
  preasureNode->advertise("preasure");
}

inline Sensor::~Sensor() {
  delete preasureNode;
  delete humidityNode;
  delete temperatureNode;
  delete sensorStateNode;
  delete sensor;
}

inline float Sensor::computeHeatIndex(float temperature, float percentHumidity) const {
  // Using both Rothfusz and Steadman's equations
  // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml

  // to fahrenheit
  temperature = temperature * 1.8 + 32;

  float hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094));

  if (hi > 79) {
    hi = -42.379 +
          2.04901523 * temperature +
         10.14333127 * percentHumidity +
         -0.22475541 * temperature * percentHumidity +
         -0.00683783 * pow(temperature, 2) +
         -0.05481717 * pow(percentHumidity, 2) +
          0.00122874 * pow(temperature, 2) * percentHumidity +
          0.00085282 * temperature * pow(percentHumidity, 2) +
         -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);

    if ((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0))
      hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);

    else if ((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0))
      hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
  }

  hi = (hi - 32) * 0.55555;
  return hi;
}

inline double Sensor::SDD(float temperature) const {
  float a = (temperature >= 0) ? 7.5 : 7.6;
  float b = (temperature >= 0) ? 237.3 : 240.7;
  float exponent = ((a * temperature) / (b + temperature));
  float sdd = 6.1078 * pow(10, exponent);
  return sdd;
}

inline double Sensor::DD(float temperature, float relativeHumidity) const {
  double dd = relativeHumidity / 100 * SDD(temperature);
  return dd;
}

inline float Sensor::TD(float temperature, float relativeHumidity) const {
  float a = (temperature >= 0) ? 7.5 : 7.6;
  float b = (temperature >= 0) ? 237.3 : 240.7;
  float v = log10(DD(temperature, relativeHumidity) / 6.1078);
  float td = b * v / (a - v);
  return td;
}

inline float Sensor::AF(float temperature, float relativeHumidity) const {
  double dd = DD(temperature, relativeHumidity);
  float af = 216.686912909 * dd / (temperature + 273.15);
  return af;
}

inline void Sensor::checkHealth() {
  SensorInterface::SensorState state = sensor->state();
  String health = [](SensorInterface::SensorState state) {
    if (state == SensorInterface::ok)
      return "ok";
    if (state == SensorInterface::read_error)
      return "read_error";
    return "unknown";
  }(state);

  if (state != ss) {
    ss = state;
    sensorStateNode->setProperty("health").setRetained(true).send(health);
  }
  if (ss != SensorInterface::ok) {
    errors++;
    sensorStateNode->setProperty("errors").setRetained(true).send(String(errors));
  }
}

inline void Sensor::setup() {
  String type(typeSetting.get());
  if (type == dht11) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE11);
  } else if (type == dht21) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE21);
  } else if (type == dht22) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE22);
  } else if (type == bme280) {
    sensor = new BME280_Impl();
  } else if (type == sht30) {
    sensor = new SHT30_Impl();
  } else {
    sensor = new SensorInterface();
  }
}

inline bool Sensor::publish() {
  checkHealth();
  if (ss != SensorInterface::ok) {
    return false;
  }

  float temperature = sensor->temperature();
  float humidity = sensor->humidity();
  float preasure = sensor->preasure();

  String t(temperature);
  String h(humidity);
  String p(preasure);
  String hi(computeHeatIndex(temperature, humidity));
  String sdd(SDD(temperature));
  String dd(DD(temperature, humidity));
  String td(TD(temperature, humidity));
  String af(AF(temperature, humidity));

  Homie.getLogger() << "Sensor reading: " << endl <<
                    "  • errors                : " << errors << endl <<
                    "  • temperature           : " << t      << " °C"   << endl <<
                    "  • preasure              : " << p      << " hPa"  << endl <<
                    "  • relative humidity     : " << h      << " %"    << endl <<
                    "  • heat index:           : " << hi     << " °C"   << endl <<
                    "  • dew point temperature : " << td     << " °C"   << endl <<
                    "  • absolute humidty      : " << af     << " g/m³" << endl;

  temperatureNode->setProperty("absolute").setRetained(false).send(t);
  temperatureNode->setProperty("heatindex").setRetained(false).send(hi);
  humidityNode->setProperty("relative").setRetained(false).send(h);
  humidityNode->setProperty("absolute").setRetained(false).send(af);
  preasureNode->setProperty("preasure").setRetained(false).send(p);

  return true;
}

#endif
<commit_msg>Various fixes<commit_after>#ifndef _SENSOR_NODE_
#define _SENSOR_NODE_

#include <Homie.h>
#include "BME280_Impl.hpp"
#include "DHTxx_Impl.hpp"
#include "SHT30_Impl.hpp"

class Sensor {
  public:
    Sensor();
    virtual ~Sensor();

    void setup();
    bool publish();

  private:
    // taken from adafruit DHT library
    float computeHeatIndex(float temperature, float relativeHumidity) const;
    // Sättigungsdampfdruck in hPa
    double SDD(float temperature) const;
    // Dampfdruck in hPa
    double DD(float temperature, float relativeHumidity) const;
    // Taupunkt in °C
    float TD(float temperature, float relativeHumidity) const;
    // absolute Feuchte in g Wasserdampf pro m3 Luft
    float AF(float temperature, float relativeHumidity) const;
    // check and update the health state. publish health state if it has changed.
    void checkHealth();

    SensorInterface *sensor;
    SensorInterface::SensorState ss;
    unsigned long errors;
    static const constexpr char* dht11 = "dht11";
    static const constexpr char* dht21 = "dht21";
    static const constexpr char* dht22 = "dht22";
    static const constexpr char* bme280 = "bme280";
    static const constexpr char* sht30 = "sht30";
    HomieSetting<const char*> typeSetting;
    HomieNode *sensorStateNode;
    HomieNode *temperatureNode;
    HomieNode *humidityNode;
    HomieNode *pressureNode;
};

inline Sensor::Sensor()
  : sensor(NULL)
  , ss(SensorInterface::unknown)
  , errors(0)
  , typeSetting("type", "Type of the sensor. Use either  \"dht11\", \"dht21\", \"dht22\", \"bme280\" or \"sht30\"")
  , sensorStateNode(NULL)
  , temperatureNode(NULL)
  , humidityNode(NULL)
  , pressureNode(NULL) {
  typeSetting.setDefaultValue(dht11).setValidator([] (const char* candidate) {
    return (String(candidate) == dht11) ||
           (String(candidate) == dht21) ||
           (String(candidate) == dht22) ||
           (String(candidate) == bme280) ||
           (String(candidate) == sht30);
  });

  sensorStateNode = new HomieNode("healthState", "healthState");
  temperatureNode = new HomieNode("temperature", "temperature");
  humidityNode = new HomieNode("humidity", "humidity");
  pressureNode = new HomieNode("pressure", "pressure");

  sensorStateNode->advertise("health");
  sensorStateNode->advertise("errors");
  temperatureNode->advertise("absolut");
  temperatureNode->advertise("heatindex");
  humidityNode->advertise("relative");
  humidityNode->advertise("absolute");
  pressureNode->advertise("pressure");
}

inline Sensor::~Sensor() {
  delete pressureNode;
  delete humidityNode;
  delete temperatureNode;
  delete sensorStateNode;
  delete sensor;
}

inline float Sensor::computeHeatIndex(float temperature, float percentHumidity) const {
  // Using both Rothfusz and Steadman's equations
  // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml

  // to fahrenheit
  temperature = temperature * 1.8 + 32;

  float hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094));

  if (hi > 79) {
    hi = -42.379 +
          2.04901523 * temperature +
         10.14333127 * percentHumidity +
         -0.22475541 * temperature * percentHumidity +
         -0.00683783 * pow(temperature, 2) +
         -0.05481717 * pow(percentHumidity, 2) +
          0.00122874 * pow(temperature, 2) * percentHumidity +
          0.00085282 * temperature * pow(percentHumidity, 2) +
         -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2);

    if ((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0))
      hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);

    else if ((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0))
      hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2);
  }

  hi = (hi - 32) * 0.55555;
  return hi;
}

inline double Sensor::SDD(float temperature) const {
  float a = (temperature >= 0) ? 7.5 : 7.6;
  float b = (temperature >= 0) ? 237.3 : 240.7;
  float exponent = ((a * temperature) / (b + temperature));
  float sdd = 6.1078 * pow(10, exponent);
  return sdd;
}

inline double Sensor::DD(float temperature, float relativeHumidity) const {
  double dd = relativeHumidity / 100 * SDD(temperature);
  return dd;
}

inline float Sensor::TD(float temperature, float relativeHumidity) const {
  float a = (temperature >= 0) ? 7.5 : 7.6;
  float b = (temperature >= 0) ? 237.3 : 240.7;
  float v = log10(DD(temperature, relativeHumidity) / 6.1078);
  float td = b * v / (a - v);
  return td;
}

inline float Sensor::AF(float temperature, float relativeHumidity) const {
  double dd = DD(temperature, relativeHumidity);
  float af = 216.686912909 * dd / (temperature + 273.15);
  return af;
}

inline void Sensor::checkHealth() {
  SensorInterface::SensorState state = SensorInterface::unknown;
  if(sensor) {
    state = sensor->state();
  }
  String health = [](SensorInterface::SensorState state) {
    if (state == SensorInterface::ok)
      return "ok";
    if (state == SensorInterface::read_error)
      return "read_error";
    return "unknown";
  }(state);

  if (state != ss) {
    ss = state;
    sensorStateNode->setProperty("health").setRetained(true).send(health);
  }
  if (ss != SensorInterface::ok) {
    Homie.getLogger() << "Sensor health check failed: " << health << endl;
    errors++;
    sensorStateNode->setProperty("errors").setRetained(true).send(String(errors));
  }
}

inline void Sensor::setup() {
  String type(typeSetting.get());
  if (type == dht11) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE11);
  } else if (type == dht21) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE21);
  } else if (type == dht22) {
    sensor = new DHTxx_Impl(2, DHTxx_Impl::TYPE22);
  } else if (type == bme280) {
    sensor = new BME280_Impl();
  } else if (type == sht30) {
    sensor = new SHT30_Impl();
  } else {
    sensor = new SensorInterface();
  }
}

inline bool Sensor::publish() {
  checkHealth();
  if (ss != SensorInterface::ok) {
    return false;
  }

  float temperature = sensor->temperature();
  float humidity = sensor->humidity();
  float preasure = sensor->preasure();

  String t(temperature);
  String h(humidity);
  String p(preasure);
  String hi(computeHeatIndex(temperature, humidity));
  String sdd(SDD(temperature));
  String dd(DD(temperature, humidity));
  String td(TD(temperature, humidity));
  String af(AF(temperature, humidity));

  Homie.getLogger() << "Sensor reading: " << endl <<
                    "  • errors                : " << errors << endl <<
                    "  • temperature           : " << t      << " °C"   << endl <<
                    "  • pressure              : " << p      << " hPa"  << endl <<
                    "  • relative humidity     : " << h      << " %"    << endl <<
                    "  • heat index:           : " << hi     << " °C"   << endl <<
                    "  • dew point temperature : " << td     << " °C"   << endl <<
                    "  • absolute humidty      : " << af     << " g/m³" << endl;

  temperatureNode->setProperty("absolute").setRetained(false).send(t);
  temperatureNode->setProperty("heatindex").setRetained(false).send(hi);
  humidityNode->setProperty("relative").setRetained(false).send(h);
  humidityNode->setProperty("absolute").setRetained(false).send(af);
  pressureNode->setProperty("pressure").setRetained(false).send(p);

  return true;
}

#endif
<|endoftext|>


<commit_before>
#include "include/Shapes.h"

double sumOfArea(const std::vector<Shape *> & shapes) {

    double total =0;

    for (Shape *shapePoint: shapes)
        total += shapePoint->area();

    return total;

}

double sumOfPerimeter(const std::vector<Shape *> & shapes){

    double total = 0;

    for (Shape *shapePoint: shapes)
        total += shapePoint->perimeter();

    return total;

}

Shape* theLargestArea(const std::vector<Shape *> & shapes){

    Shape *largestShape = nullptr;
    double largestArea = 0;

    for (Shape *shapePoint: shapes)
        if(shapePoint->area() >= largestArea){
            largestArea = shapePoint->area();
            largestShape = shapePoint;
        }

    return largestShape;

}

double distanceOfVertexs(const vertex vertex_1, const vertex vertex_2) {
    double diff_X, diff_Y, distance;

    diff_X = vertex_1.x - vertex_2.x;
    diff_Y = vertex_1.y - vertex_2.y;

    distance = sqrt(((diff_X * diff_X) + (diff_Y * diff_Y)));

    return distance;
}

void sortByDecreasingPerimeter(std::vector<Shape *> & shapes) {
    // use the shakeSort
    int left = 0;
    int right = shapes.size()-1;
    int shift = 0;
    Shape *temp;

    while(left < right){
        for(int i = left; i < right; i++) {
            if(shapes[i]->perimeter() < shapes[i+1]->perimeter()){
                temp = shapes[i];
                shapes[i] = shapes[i+1];
                shapes[i+1] = temp;
                shift = i;
            }
        }
        right = shift;
        for(int i = right; i > left; i--){
            if(shapes[i]->perimeter() > shapes[i-1]->perimeter()){
                temp = shapes[i];
                shapes[i] = shapes[i-1];
                shapes[i-1] = temp;
                shift = i;
            }
        }
        left = shift;
    }
}
<commit_msg>Delete Shapes.cpp<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2015-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <folly/fibers/FiberManagerMap.h>

#include <memory>
#include <unordered_map>

#include <folly/Function.h>
#include <folly/Synchronized.h>
#include <folly/ThreadLocal.h>

namespace folly {
namespace fibers {

namespace {

template <typename EventBaseT>
Function<void()> makeOnEventBaseDestructionCallback(EventBaseT& evb);

template <typename EventBaseT>
class GlobalCache {
 public:
  static FiberManager& get(EventBaseT& evb, const FiberManager::Options& opts) {
    return instance().getImpl(evb, opts);
  }

  static std::unique_ptr<FiberManager> erase(EventBaseT& evb) {
    return instance().eraseImpl(evb);
  }

 private:
  GlobalCache() {}

  // Leak this intentionally. During shutdown, we may call getFiberManager,
  // and want access to the fiber managers during that time.
  static GlobalCache& instance() {
    static auto ret = new GlobalCache();
    return *ret;
  }

  FiberManager& getImpl(EventBaseT& evb, const FiberManager::Options& opts) {
    std::lock_guard<std::mutex> lg(mutex_);

    auto& fmPtrRef = map_[&evb];

    if (!fmPtrRef) {
      auto loopController = std::make_unique<EventBaseLoopController>();
      loopController->attachEventBase(evb);
      evb.runOnDestruction(makeOnEventBaseDestructionCallback(evb));
      fmPtrRef =
          std::make_unique<FiberManager>(std::move(loopController), opts);
    }

    return *fmPtrRef;
  }

  std::unique_ptr<FiberManager> eraseImpl(EventBaseT& evb) {
    std::lock_guard<std::mutex> lg(mutex_);

    DCHECK_EQ(map_.count(&evb), 1u);

    auto ret = std::move(map_[&evb]);
    map_.erase(&evb);
    return ret;
  }

  std::mutex mutex_;
  std::unordered_map<EventBaseT*, std::unique_ptr<FiberManager>> map_;
};

constexpr size_t kEraseListMaxSize = 64;

template <typename EventBaseT>
class ThreadLocalCache {
 public:
  static FiberManager& get(EventBaseT& evb, const FiberManager::Options& opts) {
    return instance()->getImpl(evb, opts);
  }

  static void erase(EventBaseT& evb) {
    for (auto& localInstance : instance().accessAllThreads()) {
      localInstance.eraseInfo_.withWLock([&](auto& info) {
        if (info.eraseList.size() >= kEraseListMaxSize) {
          info.eraseAll = true;
        } else {
          info.eraseList.push_back(&evb);
        }
        localInstance.eraseRequested_ = true;
      });
    }
  }

 private:
  ThreadLocalCache() {}

  struct ThreadLocalCacheTag {};
  using ThreadThreadLocalCache =
      ThreadLocal<ThreadLocalCache, ThreadLocalCacheTag>;

  // Leak this intentionally. During shutdown, we may call getFiberManager,
  // and want access to the fiber managers during that time.
  static ThreadThreadLocalCache& instance() {
    static auto ret =
        new ThreadThreadLocalCache([]() { return new ThreadLocalCache(); });
    return *ret;
  }

  FiberManager& getImpl(EventBaseT& evb, const FiberManager::Options& opts) {
    eraseImpl();

    auto& fmPtrRef = map_[&evb];
    if (!fmPtrRef) {
      fmPtrRef = &GlobalCache<EventBaseT>::get(evb, opts);
    }

    DCHECK(fmPtrRef != nullptr);

    return *fmPtrRef;
  }

  void eraseImpl() {
    if (!eraseRequested_.load()) {
      return;
    }

    eraseInfo_.withWLock([&](auto& info) {
      if (info.eraseAll) {
        map_.clear();
      } else {
        for (auto evbPtr : info.eraseList) {
          map_.erase(evbPtr);
        }
      }

      info.eraseList.clear();
      info.eraseAll = false;
      eraseRequested_ = false;
    });
  }

  std::unordered_map<EventBaseT*, FiberManager*> map_;
  std::atomic<bool> eraseRequested_{false};

  struct EraseInfo {
    bool eraseAll{false};
    std::vector<EventBaseT*> eraseList;
  };

  folly::Synchronized<EraseInfo> eraseInfo_;
};

template <typename EventBaseT>
Function<void()> makeOnEventBaseDestructionCallback(EventBaseT& evb) {
  return [&evb] {
    auto fm = GlobalCache<EventBaseT>::erase(evb);
    DCHECK(fm.get() != nullptr);
    ThreadLocalCache<EventBaseT>::erase(evb);
  };
}

} // namespace

FiberManager& getFiberManager(
    EventBase& evb,
    const FiberManager::Options& opts) {
  return ThreadLocalCache<EventBase>::get(evb, opts);
}

FiberManager& getFiberManager(
    VirtualEventBase& evb,
    const FiberManager::Options& opts) {
  return ThreadLocalCache<VirtualEventBase>::get(evb, opts);
}
} // namespace fibers
} // namespace folly
<commit_msg>Don't hold GlobalCache mutex while scheduling OnDestruction callback<commit_after>/*
 * Copyright 2015-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <folly/fibers/FiberManagerMap.h>

#include <memory>
#include <unordered_map>

#include <folly/Function.h>
#include <folly/ScopeGuard.h>
#include <folly/Synchronized.h>
#include <folly/ThreadLocal.h>

namespace folly {
namespace fibers {

namespace {

template <typename EventBaseT>
Function<void()> makeOnEventBaseDestructionCallback(EventBaseT& evb);

template <typename EventBaseT>
class GlobalCache {
 public:
  static FiberManager& get(EventBaseT& evb, const FiberManager::Options& opts) {
    return instance().getImpl(evb, opts);
  }

  static std::unique_ptr<FiberManager> erase(EventBaseT& evb) {
    return instance().eraseImpl(evb);
  }

 private:
  GlobalCache() {}

  // Leak this intentionally. During shutdown, we may call getFiberManager,
  // and want access to the fiber managers during that time.
  static GlobalCache& instance() {
    static auto ret = new GlobalCache();
    return *ret;
  }

  FiberManager& getImpl(EventBaseT& evb, const FiberManager::Options& opts) {
    bool constructed = false;
    SCOPE_EXIT {
      if (constructed) {
        evb.runOnDestruction(makeOnEventBaseDestructionCallback(evb));
      }
    };

    std::lock_guard<std::mutex> lg(mutex_);

    auto& fmPtrRef = map_[&evb];

    if (!fmPtrRef) {
      constructed = true;
      auto loopController = std::make_unique<EventBaseLoopController>();
      loopController->attachEventBase(evb);
      fmPtrRef =
          std::make_unique<FiberManager>(std::move(loopController), opts);
    }

    return *fmPtrRef;
  }

  std::unique_ptr<FiberManager> eraseImpl(EventBaseT& evb) {
    std::lock_guard<std::mutex> lg(mutex_);

    DCHECK_EQ(map_.count(&evb), 1u);

    auto ret = std::move(map_[&evb]);
    map_.erase(&evb);
    return ret;
  }

  std::mutex mutex_;
  std::unordered_map<EventBaseT*, std::unique_ptr<FiberManager>> map_;
};

constexpr size_t kEraseListMaxSize = 64;

template <typename EventBaseT>
class ThreadLocalCache {
 public:
  static FiberManager& get(EventBaseT& evb, const FiberManager::Options& opts) {
    return instance()->getImpl(evb, opts);
  }

  static void erase(EventBaseT& evb) {
    for (auto& localInstance : instance().accessAllThreads()) {
      localInstance.eraseInfo_.withWLock([&](auto& info) {
        if (info.eraseList.size() >= kEraseListMaxSize) {
          info.eraseAll = true;
        } else {
          info.eraseList.push_back(&evb);
        }
        localInstance.eraseRequested_ = true;
      });
    }
  }

 private:
  ThreadLocalCache() {}

  struct ThreadLocalCacheTag {};
  using ThreadThreadLocalCache =
      ThreadLocal<ThreadLocalCache, ThreadLocalCacheTag>;

  // Leak this intentionally. During shutdown, we may call getFiberManager,
  // and want access to the fiber managers during that time.
  static ThreadThreadLocalCache& instance() {
    static auto ret =
        new ThreadThreadLocalCache([]() { return new ThreadLocalCache(); });
    return *ret;
  }

  FiberManager& getImpl(EventBaseT& evb, const FiberManager::Options& opts) {
    eraseImpl();

    auto& fmPtrRef = map_[&evb];
    if (!fmPtrRef) {
      fmPtrRef = &GlobalCache<EventBaseT>::get(evb, opts);
    }

    DCHECK(fmPtrRef != nullptr);

    return *fmPtrRef;
  }

  void eraseImpl() {
    if (!eraseRequested_.load()) {
      return;
    }

    eraseInfo_.withWLock([&](auto& info) {
      if (info.eraseAll) {
        map_.clear();
      } else {
        for (auto evbPtr : info.eraseList) {
          map_.erase(evbPtr);
        }
      }

      info.eraseList.clear();
      info.eraseAll = false;
      eraseRequested_ = false;
    });
  }

  std::unordered_map<EventBaseT*, FiberManager*> map_;
  std::atomic<bool> eraseRequested_{false};

  struct EraseInfo {
    bool eraseAll{false};
    std::vector<EventBaseT*> eraseList;
  };

  folly::Synchronized<EraseInfo> eraseInfo_;
};

template <typename EventBaseT>
Function<void()> makeOnEventBaseDestructionCallback(EventBaseT& evb) {
  return [&evb] {
    auto fm = GlobalCache<EventBaseT>::erase(evb);
    DCHECK(fm.get() != nullptr);
    ThreadLocalCache<EventBaseT>::erase(evb);
  };
}

} // namespace

FiberManager& getFiberManager(
    EventBase& evb,
    const FiberManager::Options& opts) {
  return ThreadLocalCache<EventBase>::get(evb, opts);
}

FiberManager& getFiberManager(
    VirtualEventBase& evb,
    const FiberManager::Options& opts) {
  return ThreadLocalCache<VirtualEventBase>::get(evb, opts);
}
} // namespace fibers
} // namespace folly
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkGradientDescentObjectOptimizerBase.h"
#include "itkObjectToObjectMetric.h"
#include "itkImage.h"
#include "itkTestingMacros.h"

/* Create a simple metric to use for testing here. */
template< class TFixedObject,  class TMovingObject >
class ITK_EXPORT GradientDescentObjectOptimizerBaseTestMetric:
  public itk::ObjectToObjectMetric
{
public:
  /** Standard class typedefs. */
  typedef GradientDescentObjectOptimizerBaseTestMetric  Self;
  typedef itk::ObjectToObjectMetric                     Superclass;
  typedef itk::SmartPointer< Self >                     Pointer;
  typedef itk::SmartPointer< const Self >               ConstPointer;

  typedef typename Superclass::MeasureType          MeasureType;
  typedef typename Superclass::DerivativeType       DerivativeType;
  typedef typename Superclass::ParametersType       ParametersType;
  typedef typename Superclass::ParametersValueType  ParametersValueType;

  itkTypeMacro(GradientDescentObjectOptimizerBaseTestMetric, ObjectToObjectMetric);

  itkNewMacro(Self);

  // Pure virtual functions that all Metrics must provide
  unsigned int GetNumberOfParameters() const { return 5; }

  using Superclass::GetValue;
  MeasureType GetValue()
    {
    return itk::NumericTraits< MeasureType >::One;
    }

  using Superclass::GetValueAndDerivative;
  void GetValueAndDerivative( MeasureType & value, DerivativeType & derivative )
    {
    value = itk::NumericTraits< MeasureType >::One;
    derivative.Fill( itk::NumericTraits< ParametersValueType >::Zero );
    }

  unsigned int GetNumberOfLocalParameters() const
  { return 0; }

  bool HasLocalSupport() const
  { return false; }

  void UpdateTransformParameters( DerivativeType &, ParametersValueType ) {}

  const ParametersType & GetParameters() const
  { return m_Parameters; }

  void Initialize(void) throw ( itk::ExceptionObject ) {}

  void PrintSelf(std::ostream& os, itk::Indent indent) const
  { Superclass::PrintSelf( os, indent ); }

protected:
  GradientDescentObjectOptimizerBaseTestMetric() {}
  ~GradientDescentObjectOptimizerBaseTestMetric() {}//purposely not implemented

private:
  GradientDescentObjectOptimizerBaseTestMetric( const Self& ); //purposely not implemented
  void operator = ( const Self& ); //purposely not implemented

  ParametersType m_Parameters;
};

/* Define a simple derived optimizer class.
 * \class GradientDescentObjectOptimizerBaseTestOptimizer */
class GradientDescentObjectOptimizerBaseTestOptimizer
  : public itk::GradientDescentObjectOptimizerBase
{
public:
  /** Standard "Self" typedef. */
  typedef GradientDescentObjectOptimizerBaseTestOptimizer Self;
  typedef GradientDescentObjectOptimizerBase              Superclass;
  typedef itk::SmartPointer< Self >                       Pointer;
  typedef itk::SmartPointer< const Self >                 ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro( GradientDescentObjectOptimizerBaseTestOptimizer,
                GradientDescentObjectOptimizerBase);

  /* Provide an override for the pure virtual StartOptimization */
  void StartOptimization()
    {
    std::cout << "StartOptimization called." << std::endl;
    }

  void ResumeOptimization()
    {
    std::cout << "StartOptimization called." << std::endl;
    }

  void ModifyGradient()
    {
    std::cout << "ModifyGradient called." << std::endl;
    }

  void ModifyGradientOverSubRange (const IndexRangeType& )
    {
    std::cout << "ModifyGradientOverSubRange called." << std::endl;
    }

protected:
   GradientDescentObjectOptimizerBaseTestOptimizer(){}
   ~GradientDescentObjectOptimizerBaseTestOptimizer(){}

private:
  GradientDescentObjectOptimizerBaseTestOptimizer(const Self& ); //purposely not implemented
  void operator = (const Self&); //purposely not implemented

};

/**
 */
int itkGradientDescentObjectOptimizerBaseTest(int , char* [])
{
  const int ImageDimension = 2;
  typedef itk::Image<double, ImageDimension>                    ImageType;

  typedef GradientDescentObjectOptimizerBaseTestMetric<ImageType,ImageType> MetricType;

  MetricType::Pointer metric = MetricType::New();
  GradientDescentObjectOptimizerBaseTestOptimizer::Pointer optimizer = GradientDescentObjectOptimizerBaseTestOptimizer::New();

  /* exercise some methods */
  optimizer->SetMetric( metric );
  if( optimizer->GetMetric() != metric )
    {
    std::cerr << "Set/GetMetric failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "value: " << optimizer->GetValue() << std::endl;

  optimizer->SetNumberOfThreads( 1 );

  TRY_EXPECT_NO_EXCEPTION( optimizer->StartOptimization() );

  std::cout << "Printing self.." << std::endl;
  std::cout << optimizer << std::endl;

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>BUG: Fix another error in GradientDescentObjectOptimizerBaseTest.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkGradientDescentObjectOptimizerBase.h"
#include "itkObjectToObjectMetric.h"
#include "itkImage.h"
#include "itkTestingMacros.h"

/* Create a simple metric to use for testing here. */
template< class TFixedObject,  class TMovingObject >
class ITK_EXPORT GradientDescentObjectOptimizerBaseTestMetric:
  public itk::ObjectToObjectMetric
{
public:
  /** Standard class typedefs. */
  typedef GradientDescentObjectOptimizerBaseTestMetric  Self;
  typedef itk::ObjectToObjectMetric                     Superclass;
  typedef itk::SmartPointer< Self >                     Pointer;
  typedef itk::SmartPointer< const Self >               ConstPointer;

  typedef typename Superclass::MeasureType          MeasureType;
  typedef typename Superclass::DerivativeType       DerivativeType;
  typedef typename Superclass::ParametersType       ParametersType;
  typedef typename Superclass::ParametersValueType  ParametersValueType;

  itkTypeMacro(GradientDescentObjectOptimizerBaseTestMetric, ObjectToObjectMetric);

  itkNewMacro(Self);

  // Pure virtual functions that all Metrics must provide
  unsigned int GetNumberOfParameters() const { return 5; }

  MeasureType GetValue() const
    {
    return itk::NumericTraits< MeasureType >::One;
    }

  void GetValueAndDerivative( MeasureType & value, DerivativeType & derivative ) const
    {
    value = itk::NumericTraits< MeasureType >::One;
    derivative.Fill( itk::NumericTraits< ParametersValueType >::Zero );
    }

  unsigned int GetNumberOfLocalParameters() const
  { return 0; }

  bool HasLocalSupport() const
  { return false; }

  void UpdateTransformParameters( DerivativeType &, ParametersValueType ) {}

  const ParametersType & GetParameters() const
  { return m_Parameters; }

  void Initialize(void) throw ( itk::ExceptionObject ) {}

  void PrintSelf(std::ostream& os, itk::Indent indent) const
  { Superclass::PrintSelf( os, indent ); }

protected:
  GradientDescentObjectOptimizerBaseTestMetric() {}
  ~GradientDescentObjectOptimizerBaseTestMetric() {}//purposely not implemented

private:
  GradientDescentObjectOptimizerBaseTestMetric( const Self& ); //purposely not implemented
  void operator = ( const Self& ); //purposely not implemented

  ParametersType m_Parameters;
};

/* Define a simple derived optimizer class.
 * \class GradientDescentObjectOptimizerBaseTestOptimizer */
class GradientDescentObjectOptimizerBaseTestOptimizer
  : public itk::GradientDescentObjectOptimizerBase
{
public:
  /** Standard "Self" typedef. */
  typedef GradientDescentObjectOptimizerBaseTestOptimizer Self;
  typedef GradientDescentObjectOptimizerBase              Superclass;
  typedef itk::SmartPointer< Self >                       Pointer;
  typedef itk::SmartPointer< const Self >                 ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro( GradientDescentObjectOptimizerBaseTestOptimizer,
                GradientDescentObjectOptimizerBase);

  /* Provide an override for the pure virtual StartOptimization */
  void StartOptimization()
    {
    std::cout << "StartOptimization called." << std::endl;
    }

  void ResumeOptimization()
    {
    std::cout << "StartOptimization called." << std::endl;
    }

  void ModifyGradient()
    {
    std::cout << "ModifyGradient called." << std::endl;
    }

  void ModifyGradientOverSubRange (const IndexRangeType& )
    {
    std::cout << "ModifyGradientOverSubRange called." << std::endl;
    }

protected:
   GradientDescentObjectOptimizerBaseTestOptimizer(){}
   ~GradientDescentObjectOptimizerBaseTestOptimizer(){}

private:
  GradientDescentObjectOptimizerBaseTestOptimizer(const Self& ); //purposely not implemented
  void operator = (const Self&); //purposely not implemented

};

/**
 */
int itkGradientDescentObjectOptimizerBaseTest(int , char* [])
{
  const int ImageDimension = 2;
  typedef itk::Image<double, ImageDimension>                    ImageType;

  typedef GradientDescentObjectOptimizerBaseTestMetric<ImageType,ImageType> MetricType;

  MetricType::Pointer metric = MetricType::New();
  GradientDescentObjectOptimizerBaseTestOptimizer::Pointer optimizer = GradientDescentObjectOptimizerBaseTestOptimizer::New();

  /* exercise some methods */
  optimizer->SetMetric( metric );
  if( optimizer->GetMetric() != metric )
    {
    std::cerr << "Set/GetMetric failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "value: " << optimizer->GetValue() << std::endl;

  optimizer->SetNumberOfThreads( 1 );

  TRY_EXPECT_NO_EXCEPTION( optimizer->StartOptimization() );

  std::cout << "Printing self.." << std::endl;
  std::cout << optimizer << std::endl;

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// trance escape_sequence.hpp - Generic Escape Sequence Manipulator
//
// Copyright (c) 2011 - 2011 Kohei Takahashi (Flast)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_
#define IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_

#include <trance/config.hpp>

#include <iosfwd>

#include <boost/cstdint.hpp>

#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/iterate.hpp>

namespace trance
{

namespace iostreams
{

//#define STRING_MANIPS_COUNT 1
//#define STRING_MANIPS     \
//  (                       \
//    ( reset, "\x1b[0m" ), \
//())                       \
//
//#define BOOST_PP_ITERATION_PARAMS_1 \
//  ( 3, ( 0, BOOST_PP_DEC( STRING_MANIPS_COUNT ), <trance/iostreams/detail/manip_string.hpp> ) )
//#include BOOST_PP_ITERATE()
//#undef STRING_MANIPS
//#undef STRING_MANIPS_COUNT

struct attribute
{
  typedef ::boost::uint32_t value_type;

    BOOST_STATIC_CONSTEXPR value_type reset = ~static_cast< ::boost::uint32_t >( 0u ); // [0m

    BOOST_STATIC_CONSTEXPR value_type highlight = 1u << 0; // [1m
    //BOOST_STATIC_CONSTEXPR value_type ???       = 1u << 1; // [2m
    BOOST_STATIC_CONSTEXPR value_type underline = 1u << 3; // [4m
    //BOOST_STATIC_CONSTEXPR value_type blink     = 1u << 4; // [5m
    BOOST_STATIC_CONSTEXPR value_type inverse   = 1u << 6; // [7m
    //BOOST_STATIC_CONSTEXPR value_type invisible = 1u << 7; // [8m or [16m
    BOOST_STATIC_CONSTEXPR value_type _effect_mask = ( 1u << 8 ) - 1;

    BOOST_STATIC_CONSTEXPR value_type black  = 1u <<  8; // [30m
    BOOST_STATIC_CONSTEXPR value_type red    = 1u <<  9; // [31m or [17m
    BOOST_STATIC_CONSTEXPR value_type green  = 1u << 10; // [32m or [18m
    BOOST_STATIC_CONSTEXPR value_type yellow = 1u << 11; // [33m or [19m
    BOOST_STATIC_CONSTEXPR value_type blue   = 1u << 12; // [34m or [20m
    BOOST_STATIC_CONSTEXPR value_type purple = 1u << 13; // [35m or [21m
    BOOST_STATIC_CONSTEXPR value_type cyan   = 1u << 14; // [36m or [22m
    BOOST_STATIC_CONSTEXPR value_type white  = 1u << 15; // [37m or [23m
    BOOST_STATIC_CONSTEXPR value_type _color_mask = ( ( 1u << 8 ) - 1 ) << 8;

    BOOST_STATIC_CONSTEXPR value_type back_black  = 1u << 16; // [40m
    BOOST_STATIC_CONSTEXPR value_type back_red    = 1u << 17; // [41m
    BOOST_STATIC_CONSTEXPR value_type back_green  = 1u << 18; // [42m
    BOOST_STATIC_CONSTEXPR value_type back_yellow = 1u << 19; // [43m
    BOOST_STATIC_CONSTEXPR value_type back_blue   = 1u << 20; // [44m
    BOOST_STATIC_CONSTEXPR value_type back_purple = 1u << 21; // [45m
    BOOST_STATIC_CONSTEXPR value_type back_cyan   = 1u << 22; // [46m
    BOOST_STATIC_CONSTEXPR value_type back_white  = 1u << 23; // [47m
    BOOST_STATIC_CONSTEXPR value_type _backcolor_mask = ( ( 1u << 8 ) - 1 ) << 16;
};

namespace iostreams_detail
{

struct _attribute_forwarder
{ attribute::value_type _M_value; };

inline size_t
_find_ntz( ::boost::uint8_t _x )
{
    ::std::size_t i = 0;
    for ( ; !( _x & 1 ); ++i, _x >>= 1 );
    return i;
}

template < typename _CharT, typename _Traits >
inline ::std::basic_ostream< _CharT, _Traits > &
operator<<( ::std::basic_ostream< _CharT, _Traits > &_ostr,
  const _attribute_forwarder &_af ) TRANCE_NOEXCEPT
{
    _CharT _buf[ 16 ] = { '\x1b', '[' };
    ::std::size_t idx = 2;
    if ( _af._M_value == attribute::reset )
    { _buf[ idx++ ] = '0'; }
    else
    {
        if ( ::boost::uint8_t _tmp = _af._M_value & attribute::_effect_mask )
        {
            _CharT c = '1';
            for ( ; _tmp; _tmp >>= 1, ++c )
            {
                if ( _tmp & 1 )
                {
                    if ( idx != 2 )
                    { _buf[ idx++ ] = ';'; }
                    _buf[ idx++ ] = c;
                }
            }
        }
        if ( ::boost::uint8_t _tmp = ( _af._M_value & attribute::_color_mask ) >> 8 )
        {
            if ( idx != 2 )
            { _buf[ idx++ ] = ';'; }
            _buf[ idx++ ] = '3';
            _buf[ idx++ ] = '0' + _find_ntz( _tmp );
        }
        if ( ::boost::uint8_t _tmp = ( _af._M_value & attribute::_backcolor_mask ) >> 16 )
        {
            if ( idx != 2 )
            { _buf[ idx++ ] = ';'; }
            _buf[ idx++ ] = '4';
            _buf[ idx++ ] = '0' + _find_ntz( _tmp );
        }
    }

    _buf[ idx ] = 'm';
    _ostr << _buf;
    return _ostr;
}

} // iostreams_detail

inline iostreams_detail::_attribute_forwarder
chattr( attribute::value_type attr = attribute::reset ) TRANCE_NOEXCEPT
{ return { attr }; }

} // namespace iostreams

} // namespace trance

#endif // IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_

<commit_msg>code refactoring<commit_after>// trance escape_sequence.hpp - Generic Escape Sequence Manipulator
//
// Copyright (c) 2011 - 2011 Kohei Takahashi (Flast)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_
#define IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_

#include <trance/config.hpp>

#include <iosfwd>

#include <boost/cstdint.hpp>

#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/iterate.hpp>

namespace trance
{

namespace iostreams
{

//#define STRING_MANIPS_COUNT 1
//#define STRING_MANIPS     \
//  (                       \
//    ( reset, "\x1b[0m" ), \
//())                       \
//
//#define BOOST_PP_ITERATION_PARAMS_1 \
//  ( 3, ( 0, BOOST_PP_DEC( STRING_MANIPS_COUNT ), <trance/iostreams/detail/manip_string.hpp> ) )
//#include BOOST_PP_ITERATE()
//#undef STRING_MANIPS
//#undef STRING_MANIPS_COUNT

struct attribute
{
    typedef ::boost::uint32_t value_type;

    BOOST_STATIC_CONSTEXPR value_type reset = ~static_cast< ::boost::uint32_t >( 0u ); // [0m

    BOOST_STATIC_CONSTEXPR value_type highlight = 1u << 0; // [1m
    //BOOST_STATIC_CONSTEXPR value_type ???       = 1u << 1; // [2m
    BOOST_STATIC_CONSTEXPR value_type underline = 1u << 3; // [4m
    //BOOST_STATIC_CONSTEXPR value_type blink     = 1u << 4; // [5m
    BOOST_STATIC_CONSTEXPR value_type inverse   = 1u << 6; // [7m
    //BOOST_STATIC_CONSTEXPR value_type invisible = 1u << 7; // [8m or [16m
    BOOST_STATIC_CONSTEXPR value_type _effect_mask = ( 1u << 8 ) - 1;

    BOOST_STATIC_CONSTEXPR value_type black  = 1u <<  8; // [30m
    BOOST_STATIC_CONSTEXPR value_type red    = 1u <<  9; // [31m or [17m
    BOOST_STATIC_CONSTEXPR value_type green  = 1u << 10; // [32m or [18m
    BOOST_STATIC_CONSTEXPR value_type yellow = 1u << 11; // [33m or [19m
    BOOST_STATIC_CONSTEXPR value_type blue   = 1u << 12; // [34m or [20m
    BOOST_STATIC_CONSTEXPR value_type purple = 1u << 13; // [35m or [21m
    BOOST_STATIC_CONSTEXPR value_type cyan   = 1u << 14; // [36m or [22m
    BOOST_STATIC_CONSTEXPR value_type white  = 1u << 15; // [37m or [23m
    BOOST_STATIC_CONSTEXPR value_type _color_mask = ( ( 1u << 8 ) - 1 ) << 8;

    BOOST_STATIC_CONSTEXPR value_type back_black  = 1u << 16; // [40m
    BOOST_STATIC_CONSTEXPR value_type back_red    = 1u << 17; // [41m
    BOOST_STATIC_CONSTEXPR value_type back_green  = 1u << 18; // [42m
    BOOST_STATIC_CONSTEXPR value_type back_yellow = 1u << 19; // [43m
    BOOST_STATIC_CONSTEXPR value_type back_blue   = 1u << 20; // [44m
    BOOST_STATIC_CONSTEXPR value_type back_purple = 1u << 21; // [45m
    BOOST_STATIC_CONSTEXPR value_type back_cyan   = 1u << 22; // [46m
    BOOST_STATIC_CONSTEXPR value_type back_white  = 1u << 23; // [47m
    BOOST_STATIC_CONSTEXPR value_type _backcolor_mask = ( ( 1u << 8 ) - 1 ) << 16;
};

namespace iostreams_detail
{

struct _attribute_forwarder
{ attribute::value_type _M_value; };

inline size_t
_find_ntz( ::boost::uint8_t _x ) TRANCE_NOEXCEPT
{
    ::std::size_t i = 0;
    for ( ; !( _x & 1 ); ++i, _x >>= 1 );
    return i;
}

inline ::boost::uint8_t
_mask( attribute::value_type _x ) TRANCE_NOEXCEPT
{ return _x & ( ( 1u << 8 ) - 1 ); }

#define INSERT_SEMICOLON_WHEN( begin, itr ) \
  if ( begin == itr ) {} else *itr++ =';'

template < typename _CharT >
inline void
_insert_when( ::boost::uint8_t pred,
  _CharT * const begin, _CharT *&itr, const _CharT value ) TRANCE_NOEXCEPT
{
    if ( !pred )
    { return; }

    INSERT_SEMICOLON_WHEN( begin, itr );
    *itr++ = value;
    *itr++ = '0' + _find_ntz( pred );
}

template < typename _CharT, typename _Traits >
inline ::std::basic_ostream< _CharT, _Traits > &
operator<<( ::std::basic_ostream< _CharT, _Traits > &_ostr,
  const _attribute_forwarder &_af ) TRANCE_NOEXCEPT
{
    _CharT _buf[ 16 ] = { '\x1b', '[' };
    _CharT *itr = _buf + 2;
    if ( _af._M_value == attribute::reset )
    { *itr++ = '0'; }
    else
    {
        if ( ::boost::uint8_t _tmp = _mask( _af._M_value ) )
        {
            for ( _CharT c = '1'; _tmp; _tmp >>= 1, ++c )
            {
                if ( _tmp & ~1 )
                { continue; }

                INSERT_SEMICOLON_WHEN( _buf, itr );
                *itr++ = c;
            }
        }
        _insert_when( _mask( _af._M_value >>  8 ), _buf, itr, '3' );
        _insert_when( _mask( _af._M_value >> 16 ), _buf, itr, '4' );
    }

    *itr = 'm';
    _ostr << _buf;
    return _ostr;
}
#undef INSERT_SEMICOLON_WHEN

} // iostreams_detail

inline iostreams_detail::_attribute_forwarder
chattr( attribute::value_type attr = attribute::reset ) TRANCE_NOEXCEPT
{ return { attr }; }

} // namespace iostreams

} // namespace trance

#endif // IG_TRANCE_IOSTREAMS_ESCAPE_SEQUENCE_HPP_ONCE_

<|endoftext|>


<commit_before>#include <ROOT/RField.hxx>

#include "gtest/gtest.h"

#include "CustomStruct.hxx"

using RFieldBase = ROOT::Experimental::Detail::RFieldBase;

TEST(RNTuple, TypeName)
{
   EXPECT_STREQ("float", ROOT::Experimental::RField<float>::TypeName().c_str());
   EXPECT_STREQ("std::vector<std::string>", ROOT::Experimental::RField<std::vector<std::string>>::TypeName().c_str());
   EXPECT_STREQ("CustomStruct", ROOT::Experimental::RField<CustomStruct>::TypeName().c_str());
}

TEST(RNTuple, CreateField)
{
   auto field = RFieldBase::Create("test", "vector<unsigned int>");
   EXPECT_STREQ("std::vector<std::uint32_t>", field->GetType().c_str());
}
<commit_msg>[ntuple] minor unit test improvement<commit_after>#include <ROOT/RField.hxx>
#include <ROOT/RFieldValue.hxx>

#include "gtest/gtest.h"

#include <memory>

#include "CustomStruct.hxx"

using RFieldBase = ROOT::Experimental::Detail::RFieldBase;
using RFieldValue = ROOT::Experimental::Detail::RFieldValue;

TEST(RNTuple, TypeName)
{
   EXPECT_STREQ("float", ROOT::Experimental::RField<float>::TypeName().c_str());
   EXPECT_STREQ("std::vector<std::string>", ROOT::Experimental::RField<std::vector<std::string>>::TypeName().c_str());
   EXPECT_STREQ("CustomStruct", ROOT::Experimental::RField<CustomStruct>::TypeName().c_str());
}

TEST(RNTuple, CreateField)
{
   auto field = std::unique_ptr<RFieldBase>(RFieldBase::Create("test", "vector<unsigned int>"));
   EXPECT_STREQ("std::vector<std::uint32_t>", field->GetType().c_str());
   auto value = field->GenerateValue();
   field->DestroyValue(value);
}
<|endoftext|>


<commit_before>
// Code partially copyright Edd Dawson 2007
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include "libmesh_config.h"
#include "print_trace.h"

#if defined(HAVE_GCC_ABI_DEMANGLE) && defined(HAVE_GLIBC_BACKTRACE)

#include <iostream>
#include <string>
#include <execinfo.h>
#include <cxxabi.h>

std::string abi_demangle(const char *name)
{
  int status = 0;
  char *d = 0;
  std::string fullname = name;
  size_t namestart = fullname.find('(');
  if (namestart == std::string::npos)
    return fullname;
  else
    namestart++;
  size_t nameend = fullname.find('+');
  if (nameend == std::string::npos ||
      nameend <= namestart)
    return fullname;
  std::string funcname = fullname.substr(namestart, nameend - namestart);
  std::string goodname = funcname;
  try { if ( (d = abi::__cxa_demangle(funcname.c_str(), 0, 0, &status)) ) goodname = d; }
  catch(...) {  }
  std::free(d);
/*
  std::string ret = fullname.substr(0, namestart);
  ret.append(goodname);
  ret.append(fullname.substr(nameend, fullname.length() - nameend));
  return ret;
*/
  return goodname;
}

void print_trace(std::ostream &out)
{
  void *addresses[10];
  char **strings;

  int size = backtrace(addresses, 10);
  strings = backtrace_symbols(addresses, size);
  out << "Stack frames: " << size << std::endl;
  for(int i = 0; i < size; i++)
    {
//      out << i << ": " << (int)addresses[i] << std::endl;
//      out << abi_demangle(strings[i]) << std::endl;
      out << i << ": " << abi_demangle(strings[i]) << std::endl;
    }
  free(strings);
}

#else

void print_trace(void) {}

#endif

#if 0 // MAC OS X code??

#include <dlfcn.h>
#include <cxxabi.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>

std::string abi_demangle(const char *name)
{
    int status = 0;
    char *d = 0;
    std::string ret = name;
    try { if ( (d = abi::__cxa_demangle(name, 0, 0, &status)) ) ret = d; }
    catch(...) {  }
    std::free(d);
    return ret;
}

void print_trace(void)
{
std::cerr << "Trying print_trace()" << std::endl;
    Dl_info info;
    void **frame = static_cast<void **>(__builtin_frame_address(0));
    void **bp = static_cast<void **>(*frame);
    void *ip = frame[1];

    while(bp && ip && dladdr(ip, &info))
    {
        std::cout << ip << ": " << abi_demangle(info.dli_sname) << " in " <<
info.dli_fname << '\n';

        if(info.dli_sname && !strcmp(info.dli_sname, "main")) break;

        ip = bp[1];
        bp = static_cast<void**>(bp[0]);
    }
    char *dlerr = dlerror();
    if (dlerr)
      std::cout << "dlerror() = " << dlerr << std::endl;
}

#endif
<commit_msg>Fix --disable-tracefiles<commit_after>
// Code partially copyright Edd Dawson 2007
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include "libmesh_config.h"
#include "print_trace.h"

#if defined(HAVE_GCC_ABI_DEMANGLE) && defined(HAVE_GLIBC_BACKTRACE)

#include <iostream>
#include <string>
#include <execinfo.h>
#include <cxxabi.h>

std::string abi_demangle(const char *name)
{
  int status = 0;
  char *d = 0;
  std::string fullname = name;
  size_t namestart = fullname.find('(');
  if (namestart == std::string::npos)
    return fullname;
  else
    namestart++;
  size_t nameend = fullname.find('+');
  if (nameend == std::string::npos ||
      nameend <= namestart)
    return fullname;
  std::string funcname = fullname.substr(namestart, nameend - namestart);
  std::string goodname = funcname;
  try { if ( (d = abi::__cxa_demangle(funcname.c_str(), 0, 0, &status)) ) goodname = d; }
  catch(...) {  }
  std::free(d);
/*
  std::string ret = fullname.substr(0, namestart);
  ret.append(goodname);
  ret.append(fullname.substr(nameend, fullname.length() - nameend));
  return ret;
*/
  return goodname;
}

void print_trace(std::ostream &out)
{
  void *addresses[10];
  char **strings;

  int size = backtrace(addresses, 10);
  strings = backtrace_symbols(addresses, size);
  out << "Stack frames: " << size << std::endl;
  for(int i = 0; i < size; i++)
    {
//      out << i << ": " << (int)addresses[i] << std::endl;
//      out << abi_demangle(strings[i]) << std::endl;
      out << i << ": " << abi_demangle(strings[i]) << std::endl;
    }
  free(strings);
}

#else

void print_trace(std::ostream &) {}

#endif

#if 0 // MAC OS X code??

#include <dlfcn.h>
#include <cxxabi.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>

std::string abi_demangle(const char *name)
{
    int status = 0;
    char *d = 0;
    std::string ret = name;
    try { if ( (d = abi::__cxa_demangle(name, 0, 0, &status)) ) ret = d; }
    catch(...) {  }
    std::free(d);
    return ret;
}

void print_trace(void)
{
std::cerr << "Trying print_trace()" << std::endl;
    Dl_info info;
    void **frame = static_cast<void **>(__builtin_frame_address(0));
    void **bp = static_cast<void **>(*frame);
    void *ip = frame[1];

    while(bp && ip && dladdr(ip, &info))
    {
        std::cout << ip << ": " << abi_demangle(info.dli_sname) << " in " <<
info.dli_fname << '\n';

        if(info.dli_sname && !strcmp(info.dli_sname, "main")) break;

        ip = bp[1];
        bp = static_cast<void**>(bp[0]);
    }
    char *dlerr = dlerror();
    if (dlerr)
      std::cout << "dlerror() = " << dlerr << std::endl;
}

#endif
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SRS_CORE_PROTOCOL_HPP
#define SRS_CORE_PROTOCOL_HPP

/*
#include <srs_core_protocol.hpp>
*/

#include <srs_core.hpp>

#include <st.h>

class SrsMessage;

/**
* the protocol provides the rtmp-message-protocol services,
* to recv RTMP message from RTMP chunk stream,
* and to send out RTMP message over RTMP chunk stream.
*/
class SrsProtocol
{
private:
	st_netfd_t stfd;
public:
	SrsProtocol(st_netfd_t client_stfd);
	virtual ~SrsProtocol();
public:
	virtual int recv_message(SrsMessage** pmsg);
};

class SrsMessage
{
public:
	SrsMessage();
	virtual ~SrsMessage();
public:
};

#endif<commit_msg>add rtmp specification<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SRS_CORE_PROTOCOL_HPP
#define SRS_CORE_PROTOCOL_HPP

/*
#include <srs_core_protocol.hpp>
*/

#include <srs_core.hpp>

#include <st.h>

class SrsMessage;

/**
* the protocol provides the rtmp-message-protocol services,
* to recv RTMP message from RTMP chunk stream,
* and to send out RTMP message over RTMP chunk stream.
*/
class SrsProtocol
{
private:
	st_netfd_t stfd;
public:
	SrsProtocol(st_netfd_t client_stfd);
	virtual ~SrsProtocol();
public:
	virtual int recv_message(SrsMessage** pmsg);
};

class SrsMessage
{
public:
	int8_t message_type;
	int24_t payload_length;
public:
	SrsMessage();
	virtual ~SrsMessage();
public:
};

#endif<|endoftext|>


<commit_before>//===- llvm/unittest/ADT/DeltaAlgorithmTest.cpp ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/DeltaAlgorithm.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;

std::ostream &operator<<(std::ostream &OS,
                         const std::set<unsigned> &S) {
  OS << "{";
  for (std::set<unsigned>::const_iterator it = S.begin(),
         ie = S.end(); it != ie; ++it) {
    if (it != S.begin())
      OS << ",";
    OS << *it;
  }
  OS << "}";
  return OS;
}

namespace {

class FixedDeltaAlgorithm : public DeltaAlgorithm {
  changeset_ty FailingSet;
  unsigned NumTests;

protected:
  virtual bool ExecuteOneTest(const changeset_ty &Changes) {
    ++NumTests;
    return std::includes(Changes.begin(), Changes.end(),
                         FailingSet.begin(), FailingSet.end());
  }

public:
  FixedDeltaAlgorithm(const changeset_ty &_FailingSet)
    : FailingSet(_FailingSet),
      NumTests(0) {}

  unsigned getNumTests() const { return NumTests; }
};

std::set<unsigned> fixed_set(unsigned N, ...) {
  std::set<unsigned> S;
  va_list ap;
  va_start(ap, N);
  for (unsigned i = 0; i != N; ++i)
    S.insert(va_arg(ap, unsigned));
  va_end(ap);
  return S;
}

std::set<unsigned> range(unsigned Start, unsigned End) {
  std::set<unsigned> S;
  while (Start != End)
    S.insert(Start++);
  return S;
}

std::set<unsigned> range(unsigned N) {
  return range(0, N);
}

TEST(DeltaAlgorithmTest, Basic) {
  // P = {3,5,7} \in S
  //   [0, 20) should minimize to {3,5,7} in a reasonable number of tests.
  std::set<unsigned> Fails = fixed_set(3, 3, 5, 7);
  FixedDeltaAlgorithm FDA(Fails);
  EXPECT_EQ(fixed_set(3, 3, 5, 7), FDA.Run(range(20)));
  EXPECT_GE(33U, FDA.getNumTests());

  // P = {3,5,7} \in S
  //   [10, 20) should minimize to [10,20)
  EXPECT_EQ(range(10,20), FDA.Run(range(10,20)));

  // P = [0,4) \in S
  //   [0, 4) should minimize to [0,4) in 11 tests.
  //
  // 11 = |{ {},
  //         {0}, {1}, {2}, {3},
  //         {1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2},
  //         {0, 1}, {2, 3} }|
  FDA = FixedDeltaAlgorithm(range(10));
  EXPECT_EQ(range(4), FDA.Run(range(4)));
  EXPECT_EQ(11U, FDA.getNumTests());
}

}

<commit_msg>Define the new operator<< for sets into namespace std, so that argument-dependent lookup can find it. This is another case where an LLVM bug (not making operator<< visible) was masked by a GCC bug (looking in the global namespace when it shouldn't).<commit_after>//===- llvm/unittest/ADT/DeltaAlgorithmTest.cpp ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/DeltaAlgorithm.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;

namespace std {

std::ostream &operator<<(std::ostream &OS,
                         const std::set<unsigned> &S) {
  OS << "{";
  for (std::set<unsigned>::const_iterator it = S.begin(),
         ie = S.end(); it != ie; ++it) {
    if (it != S.begin())
      OS << ",";
    OS << *it;
  }
  OS << "}";
  return OS;
}

}

namespace {

class FixedDeltaAlgorithm : public DeltaAlgorithm {
  changeset_ty FailingSet;
  unsigned NumTests;

protected:
  virtual bool ExecuteOneTest(const changeset_ty &Changes) {
    ++NumTests;
    return std::includes(Changes.begin(), Changes.end(),
                         FailingSet.begin(), FailingSet.end());
  }

public:
  FixedDeltaAlgorithm(const changeset_ty &_FailingSet)
    : FailingSet(_FailingSet),
      NumTests(0) {}

  unsigned getNumTests() const { return NumTests; }
};

std::set<unsigned> fixed_set(unsigned N, ...) {
  std::set<unsigned> S;
  va_list ap;
  va_start(ap, N);
  for (unsigned i = 0; i != N; ++i)
    S.insert(va_arg(ap, unsigned));
  va_end(ap);
  return S;
}

std::set<unsigned> range(unsigned Start, unsigned End) {
  std::set<unsigned> S;
  while (Start != End)
    S.insert(Start++);
  return S;
}

std::set<unsigned> range(unsigned N) {
  return range(0, N);
}

TEST(DeltaAlgorithmTest, Basic) {
  // P = {3,5,7} \in S
  //   [0, 20) should minimize to {3,5,7} in a reasonable number of tests.
  std::set<unsigned> Fails = fixed_set(3, 3, 5, 7);
  FixedDeltaAlgorithm FDA(Fails);
  EXPECT_EQ(fixed_set(3, 3, 5, 7), FDA.Run(range(20)));
  EXPECT_GE(33U, FDA.getNumTests());

  // P = {3,5,7} \in S
  //   [10, 20) should minimize to [10,20)
  EXPECT_EQ(range(10,20), FDA.Run(range(10,20)));

  // P = [0,4) \in S
  //   [0, 4) should minimize to [0,4) in 11 tests.
  //
  // 11 = |{ {},
  //         {0}, {1}, {2}, {3},
  //         {1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2},
  //         {0, 1}, {2, 3} }|
  FDA = FixedDeltaAlgorithm(range(10));
  EXPECT_EQ(range(4), FDA.Run(range(4)));
  EXPECT_EQ(11U, FDA.getNumTests());
}

}

<|endoftext|>


<commit_before>//===- unittest/Support/YAMLParserTest ------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
#include "gtest/gtest.h"

namespace llvm {

// Checks that the given input gives a parse error. Makes sure that an error
// text is available and the parse fails.
static void ExpectParseError(StringRef Message, StringRef Input) {
  SourceMgr SM;
  yaml::Stream Stream(Input, SM);
  EXPECT_FALSE(Stream.validate()) << Message << ": " << Input;
  EXPECT_TRUE(Stream.failed()) << Message << ": " << Input;
}

// Checks that the given input can be parsed without error.
static void ExpectParseSuccess(StringRef Message, StringRef Input) {
  SourceMgr SM;
  yaml::Stream Stream(Input, SM);
  EXPECT_TRUE(Stream.validate()) << Message << ": " << Input;
}

TEST(YAMLParser, ParsesEmptyArray) {
  ExpectParseSuccess("Empty array", "[]");
}

TEST(YAMLParser, FailsIfNotClosingArray) {
  ExpectParseError("Not closing array", "[");
  ExpectParseError("Not closing array", "  [  ");
  ExpectParseError("Not closing array", "  [x");
}

TEST(YAMLParser, ParsesEmptyArrayWithWhitespace) {
  ExpectParseSuccess("Array with spaces", "  [  ]  ");
  ExpectParseSuccess("All whitespaces", "\t\r\n[\t\n \t\r ]\t\r \n\n");
}

TEST(YAMLParser, ParsesEmptyObject) {
  ExpectParseSuccess("Empty object", "[{}]");
}

TEST(YAMLParser, ParsesObject) {
  ExpectParseSuccess("Object with an entry", "[{\"a\":\"/b\"}]");
}

TEST(YAMLParser, ParsesMultipleKeyValuePairsInObject) {
  ExpectParseSuccess("Multiple key, value pairs",
                     "[{\"a\":\"/b\",\"c\":\"d\",\"e\":\"f\"}]");
}

TEST(YAMLParser, FailsIfNotClosingObject) {
  ExpectParseError("Missing close on empty", "[{]");
  ExpectParseError("Missing close after pair", "[{\"a\":\"b\"]");
}

TEST(YAMLParser, FailsIfMissingColon) {
  ExpectParseError("Missing colon between key and value", "[{\"a\"\"/b\"}]");
  ExpectParseError("Missing colon between key and value", "[{\"a\" \"b\"}]");
}

TEST(YAMLParser, FailsOnMissingQuote) {
  ExpectParseError("Missing open quote", "[{a\":\"b\"}]");
  ExpectParseError("Missing closing quote", "[{\"a\":\"b}]");
}

TEST(YAMLParser, ParsesEscapedQuotes) {
  ExpectParseSuccess("Parses escaped string in key and value",
                     "[{\"a\":\"\\\"b\\\"  \\\" \\\"\"}]");
}

TEST(YAMLParser, ParsesEmptyString) {
  ExpectParseSuccess("Parses empty string in value", "[{\"a\":\"\"}]");
}

TEST(YAMLParser, ParsesMultipleObjects) {
  ExpectParseSuccess(
      "Multiple objects in array",
      "["
      " { \"a\" : \"b\" },"
      " { \"a\" : \"b\" },"
      " { \"a\" : \"b\" }"
      "]");
}

TEST(YAMLParser, FailsOnMissingComma) {
  ExpectParseError(
      "Missing comma",
      "["
      " { \"a\" : \"b\" }"
      " { \"a\" : \"b\" }"
      "]");
}

TEST(YAMLParser, ParsesSpacesInBetweenTokens) {
  ExpectParseSuccess(
      "Various whitespace between tokens",
      " \t \n\n \r [ \t \n\n \r"
      " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
      " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r,\t \n\n \r"
      " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
      " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r]\t \n\n \r");
}

TEST(YAMLParser, ParsesArrayOfArrays) {
  ExpectParseSuccess("Array of arrays", "[[]]");
}

TEST(YAMLParser, HandlesEndOfFileGracefully) {
  ExpectParseError("In string starting with EOF", "[\"");
  ExpectParseError("In string hitting EOF", "[\"   ");
  ExpectParseError("In string escaping EOF", "[\"  \\");
  ExpectParseError("In array starting with EOF", "[");
  ExpectParseError("In array element starting with EOF", "[[], ");
  ExpectParseError("In array hitting EOF", "[[] ");
  ExpectParseError("In array hitting EOF", "[[]");
  ExpectParseError("In object hitting EOF", "{\"\"");
}

// Checks that the given string can be parsed into an identical string inside
// of an array.
static void ExpectCanParseString(StringRef String) {
  std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
  SourceMgr SM;
  yaml::Stream Stream(StringInArray, SM);
  yaml::SequenceNode *ParsedSequence
    = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot());
  StringRef ParsedString
    = dyn_cast<yaml::ScalarNode>(
      static_cast<yaml::Node*>(ParsedSequence->begin()))->getRawValue();
  ParsedString = ParsedString.substr(1, ParsedString.size() - 2);
  EXPECT_EQ(String, ParsedString.str());
}

// Checks that parsing the given string inside an array fails.
static void ExpectCannotParseString(StringRef String) {
  std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
  ExpectParseError((Twine("When parsing string \"") + String + "\"").str(),
                   StringInArray);
}

TEST(YAMLParser, ParsesStrings) {
  ExpectCanParseString("");
  ExpectCannotParseString("\\");
  ExpectCannotParseString("\"");
  ExpectCanParseString(" ");
  ExpectCanParseString("\\ ");
  ExpectCanParseString("\\\"");
  ExpectCannotParseString("\"\\");
  ExpectCannotParseString(" \\");
  ExpectCanParseString("\\\\");
  ExpectCannotParseString("\\\\\\");
  ExpectCanParseString("\\\\\\\\");
  ExpectCanParseString("\\\" ");
  ExpectCannotParseString("\\\\\" ");
  ExpectCanParseString("\\\\\\\" ");
  ExpectCanParseString("    \\\\  \\\"  \\\\\\\"   ");
}

TEST(YAMLParser, WorksWithIteratorAlgorithms) {
  SourceMgr SM;
  yaml::Stream Stream("[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]", SM);
  yaml::SequenceNode *Array
    = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot());
  EXPECT_EQ(6, std::distance(Array->begin(), Array->end()));
}

} // end namespace llvm
<commit_msg>Suppress stderr noise when test case runs.<commit_after>//===- unittest/Support/YAMLParserTest ------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
#include "gtest/gtest.h"

namespace llvm {

static void SuppressDiagnosticsOutput(const SMDiagnostic &, void *) {
  // Prevent SourceMgr from writing errors to stderr
  // to reduce noise in unit test runs.
}

// Checks that the given input gives a parse error. Makes sure that an error
// text is available and the parse fails.
static void ExpectParseError(StringRef Message, StringRef Input) {
  SourceMgr SM;
  yaml::Stream Stream(Input, SM);
  SM.setDiagHandler(SuppressDiagnosticsOutput);
  EXPECT_FALSE(Stream.validate()) << Message << ": " << Input;
  EXPECT_TRUE(Stream.failed()) << Message << ": " << Input;
}

// Checks that the given input can be parsed without error.
static void ExpectParseSuccess(StringRef Message, StringRef Input) {
  SourceMgr SM;
  yaml::Stream Stream(Input, SM);
  EXPECT_TRUE(Stream.validate()) << Message << ": " << Input;
}

TEST(YAMLParser, ParsesEmptyArray) {
  ExpectParseSuccess("Empty array", "[]");
}

TEST(YAMLParser, FailsIfNotClosingArray) {
  ExpectParseError("Not closing array", "[");
  ExpectParseError("Not closing array", "  [  ");
  ExpectParseError("Not closing array", "  [x");
}

TEST(YAMLParser, ParsesEmptyArrayWithWhitespace) {
  ExpectParseSuccess("Array with spaces", "  [  ]  ");
  ExpectParseSuccess("All whitespaces", "\t\r\n[\t\n \t\r ]\t\r \n\n");
}

TEST(YAMLParser, ParsesEmptyObject) {
  ExpectParseSuccess("Empty object", "[{}]");
}

TEST(YAMLParser, ParsesObject) {
  ExpectParseSuccess("Object with an entry", "[{\"a\":\"/b\"}]");
}

TEST(YAMLParser, ParsesMultipleKeyValuePairsInObject) {
  ExpectParseSuccess("Multiple key, value pairs",
                     "[{\"a\":\"/b\",\"c\":\"d\",\"e\":\"f\"}]");
}

TEST(YAMLParser, FailsIfNotClosingObject) {
  ExpectParseError("Missing close on empty", "[{]");
  ExpectParseError("Missing close after pair", "[{\"a\":\"b\"]");
}

TEST(YAMLParser, FailsIfMissingColon) {
  ExpectParseError("Missing colon between key and value", "[{\"a\"\"/b\"}]");
  ExpectParseError("Missing colon between key and value", "[{\"a\" \"b\"}]");
}

TEST(YAMLParser, FailsOnMissingQuote) {
  ExpectParseError("Missing open quote", "[{a\":\"b\"}]");
  ExpectParseError("Missing closing quote", "[{\"a\":\"b}]");
}

TEST(YAMLParser, ParsesEscapedQuotes) {
  ExpectParseSuccess("Parses escaped string in key and value",
                     "[{\"a\":\"\\\"b\\\"  \\\" \\\"\"}]");
}

TEST(YAMLParser, ParsesEmptyString) {
  ExpectParseSuccess("Parses empty string in value", "[{\"a\":\"\"}]");
}

TEST(YAMLParser, ParsesMultipleObjects) {
  ExpectParseSuccess(
      "Multiple objects in array",
      "["
      " { \"a\" : \"b\" },"
      " { \"a\" : \"b\" },"
      " { \"a\" : \"b\" }"
      "]");
}

TEST(YAMLParser, FailsOnMissingComma) {
  ExpectParseError(
      "Missing comma",
      "["
      " { \"a\" : \"b\" }"
      " { \"a\" : \"b\" }"
      "]");
}

TEST(YAMLParser, ParsesSpacesInBetweenTokens) {
  ExpectParseSuccess(
      "Various whitespace between tokens",
      " \t \n\n \r [ \t \n\n \r"
      " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
      " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r,\t \n\n \r"
      " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
      " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r]\t \n\n \r");
}

TEST(YAMLParser, ParsesArrayOfArrays) {
  ExpectParseSuccess("Array of arrays", "[[]]");
}

TEST(YAMLParser, HandlesEndOfFileGracefully) {
  ExpectParseError("In string starting with EOF", "[\"");
  ExpectParseError("In string hitting EOF", "[\"   ");
  ExpectParseError("In string escaping EOF", "[\"  \\");
  ExpectParseError("In array starting with EOF", "[");
  ExpectParseError("In array element starting with EOF", "[[], ");
  ExpectParseError("In array hitting EOF", "[[] ");
  ExpectParseError("In array hitting EOF", "[[]");
  ExpectParseError("In object hitting EOF", "{\"\"");
}

// Checks that the given string can be parsed into an identical string inside
// of an array.
static void ExpectCanParseString(StringRef String) {
  std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
  SourceMgr SM;
  yaml::Stream Stream(StringInArray, SM);
  yaml::SequenceNode *ParsedSequence
    = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot());
  StringRef ParsedString
    = dyn_cast<yaml::ScalarNode>(
      static_cast<yaml::Node*>(ParsedSequence->begin()))->getRawValue();
  ParsedString = ParsedString.substr(1, ParsedString.size() - 2);
  EXPECT_EQ(String, ParsedString.str());
}

// Checks that parsing the given string inside an array fails.
static void ExpectCannotParseString(StringRef String) {
  std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
  ExpectParseError((Twine("When parsing string \"") + String + "\"").str(),
                   StringInArray);
}

TEST(YAMLParser, ParsesStrings) {
  ExpectCanParseString("");
  ExpectCannotParseString("\\");
  ExpectCannotParseString("\"");
  ExpectCanParseString(" ");
  ExpectCanParseString("\\ ");
  ExpectCanParseString("\\\"");
  ExpectCannotParseString("\"\\");
  ExpectCannotParseString(" \\");
  ExpectCanParseString("\\\\");
  ExpectCannotParseString("\\\\\\");
  ExpectCanParseString("\\\\\\\\");
  ExpectCanParseString("\\\" ");
  ExpectCannotParseString("\\\\\" ");
  ExpectCanParseString("\\\\\\\" ");
  ExpectCanParseString("    \\\\  \\\"  \\\\\\\"   ");
}

TEST(YAMLParser, WorksWithIteratorAlgorithms) {
  SourceMgr SM;
  yaml::Stream Stream("[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]", SM);
  yaml::SequenceNode *Array
    = dyn_cast<yaml::SequenceNode>(Stream.begin()->getRoot());
  EXPECT_EQ(6, std::distance(Array->begin(), Array->end()));
}

} // end namespace llvm
<|endoftext|>


<commit_before>
#include <benchmark/benchmark.h>

#include <glkernel/Kernel.h>
#include <glkernel/sample.h>

static void BM_possion_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::poisson_square(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_jittered_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::multi_jittered(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_rooks_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::n_rooks(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_stratified_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::stratified(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_hammersley_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::hammersley(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_hammersley_sphere_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::hammersley_sphere(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_halton_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::halton(dkernel, 2, 3);

    state.SetComplexityN(state.range(0));
}

static void BM_halton_sphere_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::halton_sphere(dkernel, 2, 3);

    state.SetComplexityN(state.range(0));
}

static void BM_best_candidate_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::best_candidate(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_golden_point_set_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::golden_point_set(dkernel);

    state.SetComplexityN(state.range(0));
}

BENCHMARK(BM_poisson_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_jittered_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_rooks_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_stratified_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_hammersley_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_hammersley_sphere_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_halton_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_halton_sphere_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_best_candidate_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_golden_point_set_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
<commit_msg>fixing benchmark names<commit_after>
#include <benchmark/benchmark.h>

#include <glkernel/Kernel.h>
#include <glkernel/sample.h>

static void BM_poisson_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::poisson_square(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_jittered_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::multi_jittered(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_rooks_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::n_rooks(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_stratified_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::stratified(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_hammersley_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::hammersley(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_hammersley_sphere_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::hammersley_sphere(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_halton_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::halton(dkernel, 2, 3);

    state.SetComplexityN(state.range(0));
}

static void BM_halton_sphere_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::halton_sphere(dkernel, 2, 3);

    state.SetComplexityN(state.range(0));
}

static void BM_best_candidate_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel3{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::best_candidate(dkernel);

    state.SetComplexityN(state.range(0));
}

static void BM_golden_point_set_quad(benchmark::State& state) {
    auto dkernel = glkernel::dkernel2{state.range(0), state.range(0)};

    for (auto _ : state)
        glkernel::sample::golden_point_set(dkernel);

    state.SetComplexityN(state.range(0));
}

BENCHMARK(BM_poisson_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_jittered_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_rooks_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_stratified_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_hammersley_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_hammersley_sphere_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_halton_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_halton_sphere_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_best_candidate_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
BENCHMARK(BM_golden_point_set_quad)->RangeMultiplier(2)->Range(2, 64)->Complexity();
<|endoftext|>


<commit_before>#include "ncv.h"
#include "core/clamp.h"
#include "core/timer.h"
#include "core/logger.h"
#include "model/conv_network.h"
#include <boost/program_options.hpp>

int main(int argc, char *argv[])
{
        ncv::init();

        using namespace ncv;

        // parse the command line
        boost::program_options::options_description po_desc("", 160);
        po_desc.add_options()("help,h", "help message");
        po_desc.add_options()("inputs,i",
                boost::program_options::value<string_t>()->default_value("rgba"),
                "number of inputs [luma, rgba]");
        po_desc.add_options()("rows,ir",
                boost::program_options::value<size_t>()->default_value(32),
                "number of input rows [16, 64]");
        po_desc.add_options()("cols,ic",
                boost::program_options::value<size_t>()->default_value(32),
                "number of input columns [16, 64]");
        po_desc.add_options()("outputs,o",
                boost::program_options::value<size_t>()->default_value(10),
                "number of input rows [1, 100]");
        po_desc.add_options()("network,n",
                boost::program_options::value<string_t>(),
                "convolution network parameters");
        po_desc.add_options()("samples,s",
                boost::program_options::value<size_t>()->default_value(10000),
                "number of random samples [1K, 1M]");

        boost::program_options::variables_map po_vm;
        boost::program_options::store(
                boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
                po_vm);
        boost::program_options::notify(po_vm);

        // check arguments and options
        if (	po_vm.empty() ||
                !po_vm.count("network") ||
                po_vm.count("help"))
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        const color_mode cmd_color = text::from_string<color_mode>(po_vm["inputs"].as<string_t>());
        const size_t cmd_rows = math::clamp(po_vm["rows"].as<size_t>(), 16, 64);
        const size_t cmd_cols = math::clamp(po_vm["cols"].as<size_t>(), 16, 64);
        const size_t cmd_outputs = math::clamp(po_vm["outputs"].as<size_t>(), 1, 100);
        const string_t cmd_network = po_vm["network"].as<string_t>();
        const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 1000 * 1000);

        // create convolution network
        ncv::conv_network_t network(cmd_network);
        network.resize(cmd_rows, cmd_cols, cmd_outputs, cmd_color);

        // create random samples
        tensor3ds_t samples(cmd_samples, tensor3d_t(cmd_color == color_mode::luma ? 1 : 3, cmd_rows, cmd_cols));
        for (tensor3d_t& sample : samples)
        {
                sample.random(-1.0, +1.0);
        }

        // process the samples
        ncv::timer_t timer;

        size_t count = 0;
        for (tensor3d_t& sample : samples)
        {
                const vector_t output = network.value(sample);
                count += output.size();
        }

        log_info() << "<<< processed [" << (count / cmd_outputs) << "] samples in " << timer.elapsed() << ".";

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<commit_msg>fix command line tags<commit_after>#include "ncv.h"
#include "core/clamp.h"
#include "core/timer.h"
#include "core/logger.h"
#include "model/conv_network.h"
#include <boost/program_options.hpp>

int main(int argc, char *argv[])
{
        ncv::init();

        using namespace ncv;

        // parse the command line
        boost::program_options::options_description po_desc("", 160);
        po_desc.add_options()("help,h", "help message");
        po_desc.add_options()("inputs,i",
                boost::program_options::value<string_t>()->default_value("rgba"),
                "number of inputs [luma, rgba]");
        po_desc.add_options()("rows,r",
                boost::program_options::value<size_t>()->default_value(32),
                "number of input rows [16, 64]");
        po_desc.add_options()("cols,c",
                boost::program_options::value<size_t>()->default_value(32),
                "number of input columns [16, 64]");
        po_desc.add_options()("outputs,o",
                boost::program_options::value<size_t>()->default_value(10),
                "number of input rows [1, 100]");
        po_desc.add_options()("network,n",
                boost::program_options::value<string_t>(),
                "convolution network parameters");
        po_desc.add_options()("samples,s",
                boost::program_options::value<size_t>()->default_value(10000),
                "number of random samples [1K, 1M]");

        boost::program_options::variables_map po_vm;
        boost::program_options::store(
                boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
                po_vm);
        boost::program_options::notify(po_vm);

        // check arguments and options
        if (	po_vm.empty() ||
                !po_vm.count("network") ||
                po_vm.count("help"))
        {
                std::cout << po_desc;
                return EXIT_FAILURE;
        }

        const color_mode cmd_color = text::from_string<color_mode>(po_vm["inputs"].as<string_t>());
        const size_t cmd_rows = math::clamp(po_vm["rows"].as<size_t>(), 16, 64);
        const size_t cmd_cols = math::clamp(po_vm["cols"].as<size_t>(), 16, 64);
        const size_t cmd_outputs = math::clamp(po_vm["outputs"].as<size_t>(), 1, 100);
        const string_t cmd_network = po_vm["network"].as<string_t>();
        const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 1000 * 1000);

        // create convolution network
        ncv::conv_network_t network(cmd_network);
        network.resize(cmd_rows, cmd_cols, cmd_outputs, cmd_color);

        // create random samples
        tensor3ds_t samples(cmd_samples, tensor3d_t(cmd_color == color_mode::luma ? 1 : 3, cmd_rows, cmd_cols));
        for (tensor3d_t& sample : samples)
        {
                sample.random(-1.0, +1.0);
        }

        // process the samples
        ncv::timer_t timer;

        size_t count = 0;
        for (tensor3d_t& sample : samples)
        {
                const vector_t output = network.value(sample);
                count += output.size();
        }

        log_info() << "<<< processed [" << (count / cmd_outputs) << "] samples in " << timer.elapsed() << ".";

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<|endoftext|>