text:
#include "waymo_open_dataset/metrics/breakdown_generator.h"

#include <math.h>

#include <cmath>
#include <string>

#include <glog/logging.h>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "waymo_open_dataset/dataset.pb.h"
#include "waymo_open_dataset/label.pb.h"
#include "waymo_open_dataset/protos/breakdown.pb.h"
#include "waymo_open_dataset/protos/metrics.pb.h"

namespace waymo {
namespace open_dataset {
namespace {
double Hypot3(double a, double b, double c) {
  return std::sqrt(a * a + b * b + c * c);
}

// Number of cameras in BreakdownGeneratorCamera.
constexpr int kNumCameras = 5;
}  // namespace

// This breakdown generator considers everything as one shard.
class BreakdownGeneratorOneShard : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorOneShard() override {}

  int Shard(const Object& object) const override { return 0; }

  Breakdown::GeneratorId Id() const override { return Breakdown::ONE_SHARD; }

  int NumShards() const override { return 1; }

  std::string ShardName(int shard) const override { return "ONE_SHARD"; }
};

// This breakdown generator considers everything as one shard.
class BreakdownGeneratorAllButSign : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorAllButSign() override {}

  int Shard(const Object& object) const override {
    if (object.object().type() != Label::TYPE_SIGN) {
      return 0;
    }
    return 1;
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::ALL_BUT_SIGN; }

  int NumShards() const override { return 2; }

  std::string ShardName(int shard) const override {
    switch (shard) {
      case 0:
        return "ALL_BUT_SIGN";
      case 1:
        return "SIGN";
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }
};

// This breakdown generator breaks down the objects based on its object type.
class BreakdownGeneratorObjectType : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorObjectType() override {}

  int Shard(const Object& object) const override {
    // This returns -1 for TYPE_UNKNOWN. -1 indicates that TYPE_UNKNOWN is not
    // in any shard.
    return static_cast<int>(object.object().type() - 1);
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::OBJECT_TYPE; }

  int NumShards() const override { return static_cast<int>(Label::Type_MAX); }

  std::string ShardName(int shard) const override {
    return absl::StrCat(Breakdown::GeneratorId_Name(Id()), "_",
                        Label::Type_Name(static_cast<Label::Type>(shard + 1)));
  }
};

// This breakdown generator breaks down the objects based on their center
// distance (w.r.t. SDC if the box is in vehicle frame).
class BreakdownGeneratorRange : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorRange() override {}

  int Shard(const Object& object) const override {
    double range = Hypot3(object.object().box().center_x(),
                          object.object().box().center_y(),
                          object.object().box().center_z());
    constexpr float kNearRange = 30.0;
    constexpr float kMidRange = 50.0;
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return -1;
    }
    const int shard_offset = 3 * (object.object().type() - 1);
    if (shard_offset < 0) {
      return -1;
    }
    if (range < kNearRange) {
      return 0 + shard_offset;
    } else if (range < kMidRange) {
      return 1 + shard_offset;
    } else {
      return 2 + shard_offset;
    }
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::RANGE; }

  int NumShards() const override {
    return 3 * static_cast<int>(Label::Type_MAX);
  }

  std::string ShardName(int shard) const override {
    const Label::Type object_type = static_cast<Label::Type>(shard / 3 + 1);
    CHECK_LE(object_type, Label::Type_MAX) << shard;
    CHECK_GE(object_type, 1) << shard;

    const std::string prefix = absl::StrCat(Breakdown::GeneratorId_Name(Id()),
                                            "_", Label::Type_Name(object_type));
    const int range_shard = shard % 3;
    switch (range_shard) {
      case 0:
        return absl::StrCat(prefix, "_", "[0, 30)");
      case 1:
        return absl::StrCat(prefix, "_", "[30, 50)");
      case 2:
        return absl::StrCat(prefix, "_", "[50, +inf)");
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }
};

// This breakdown generator breaks down the objects based on their center
// distance (w.r.t. SDC if the box is in vehicle frame).
class BreakdownGeneratorSize : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorSize() override {}

  int Shard(const Object& object) const override {
    double size = std::max(
        std::max(object.object().box().length(), object.object().box().width()),
        object.object().box().height());
    constexpr float kLarge = 7.0;
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return -1;
    }
    const int shard_offset = 2 * (object.object().type() - 1);
    if (shard_offset < 0) {
      return -1;
    }
    if (size < kLarge) {
      return 0 + shard_offset;
    } else {
      return 1 + shard_offset;
    }
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::SIZE; }

  int NumShards() const override {
    return 2 * static_cast<int>(Label::Type_MAX);
  }

  std::string ShardName(int shard) const override {
    const Label::Type object_type = static_cast<Label::Type>(shard / 2 + 1);
    CHECK_LE(object_type, Label::Type_MAX) << shard;
    CHECK_GE(object_type, 1) << shard;

    const std::string prefix = absl::StrCat(Breakdown::GeneratorId_Name(Id()),
                                            "_", Label::Type_Name(object_type));
    const int range_shard = shard % 2;
    switch (range_shard) {
      case 0:
        return absl::StrCat(prefix, "_", "small");
      case 1:
        return absl::StrCat(prefix, "_", "large");
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }
};

// This generator breaks down the results based on the magnitude of
// the velocity vector.
class BreakdownGeneratorVelocity : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorVelocity() override {}

  int Shard(const Object& object) const override {
    double v_x, v_y;
    if (object.object().metadata().has_speed_x() &&
        object.object().metadata().has_speed_y()) {
      v_x = object.object().metadata().speed_x();
      v_y = object.object().metadata().speed_y();
    } else {
      LOG(WARNING) << "Object does not have speed: " << object.DebugString();
      v_x = 0;
      v_y = 0;
    }
    // In meters per second in world coordinates.
    const double v_mag = sqrt(v_x * v_x + v_y * v_y);

    constexpr float kStationary = 0.2;
    constexpr float kSlow = 1.;
    constexpr float kMedium = 3.;
    constexpr float kFast = 10.;
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return -1;
    }
    const int shard_offset = 5 * (object.object().type() - 1);

    if (v_mag < kStationary) {
      return 0 + shard_offset;  // Stationary
    } else if (v_mag < kSlow) {
      return 1 + shard_offset;  // Slow
    } else if (v_mag < kMedium) {
      return 2 + shard_offset;  // Medium
    } else if (v_mag < kFast) {
      return 3 + shard_offset;  // Fast
    } else {
      return 4 + shard_offset;  // Very fast
    }
  }

  std::vector<int> ShardsForMatching(const Object& object) const override {
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return std::vector<int>();
    }
    std::vector<int> shards(5);
    for (int i = 0; i < 5; ++i) {
      shards[i] = 5 * (object.object().type() - 1) + i;
    }
    return shards;
  }

  int NumShards() const override {
    return 5 * static_cast<int>(Label::Type_MAX);
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::VELOCITY; }

  std::string ShardName(int shard) const override {
    const Label::Type object_type = static_cast<Label::Type>(shard / 5 + 1);
    CHECK_LE(object_type, Label::Type_MAX) << shard;
    CHECK_GE(object_type, 1) << shard;

    const std::string prefix = absl::StrCat(Breakdown::GeneratorId_Name(Id()),
                                            "_", Label::Type_Name(object_type));
    const int velocity_shard = shard % 5;
    switch (velocity_shard) {
      case 0:
        return absl::StrCat(prefix, "_", "STATIONARY");
      case 1:
        return absl::StrCat(prefix, "_", "SLOW");
      case 2:
        return absl::StrCat(prefix, "_", "MEDIUM");
      case 3:
        return absl::StrCat(prefix, "_", "FAST");
      case 4:
        return absl::StrCat(prefix, "_", "VERY_FAST");
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }

  bool IsGroundTruthOnlyBreakdown() const { return true; }
};

// This generator breaks down the results based on the different camera of
// the detection or ground truth.
class BreakdownGeneratorCamera : public BreakdownGenerator {
 public:
  ~BreakdownGeneratorCamera() override {}

  int Shard(const Object& object) const override {
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return -1;
    }
    const int shard_offset = kNumCameras * (object.object().type() - 1);
    CameraName::Name camera_name;
    if (Is2DCamera(object)) {
      camera_name = object.camera_name();
    } else {  // 3D detection.
      if (object.object().has_most_visible_camera_name()) {
        const std::string& camera_name_str =
            object.object().most_visible_camera_name();
        if (!CameraName::Name_Parse(camera_name_str, &camera_name)) {
          LOG(WARNING)
              << "Object does not have valid most visible camera name: "
              << object.DebugString();
          return -1;
        }
      } else {
        // If the mostly visible camera is not pre-computed, we estimate the
        // corresponding camera by FOV.
        auto camera_names = EstimateCameraNamesByFov(object);
        if (!camera_names.empty())
          camera_name = camera_names[0];
        else
          return -1;
      }
    }
    const int camera_shard_offset = GetShardOffsetByCameraName(camera_name);
    if (camera_shard_offset < 0) {
      LOG(WARNING) << "Object does not have valid camera: "
                   << object.DebugString();
      return -1;
    }
    return shard_offset + camera_shard_offset;
  }

  std::vector<int> ShardsForMatching(const Object& object) const override {
    if (object.object().type() == Label::TYPE_UNKNOWN) {
      return std::vector<int>();
    }
    if (Is2DCamera(object)) {
      return std::vector<int>({Shard(object)});
    }
    // For 3D detections, we estimate the camera breakdowns by FOV.
    const int shard_offset = kNumCameras * (object.object().type() - 1);
    auto camera_names = EstimateCameraNamesByFov(object);
    std::vector<int> shards(camera_names.size());
    for (int i = 0; i < camera_names.size(); ++i) {
      shards[i] = shard_offset + GetShardOffsetByCameraName(camera_names[i]);
    }
    return shards;
  }

  int NumShards() const override {
    return kNumCameras * static_cast<int>(Label::Type_MAX);
  }

  Breakdown::GeneratorId Id() const override { return Breakdown::CAMERA; }

  std::string ShardName(int shard) const override {
    const Label::Type object_type =
        static_cast<Label::Type>(shard / kNumCameras + 1);
    CHECK_LE(object_type, Label::Type_MAX) << shard;
    CHECK_GE(object_type, 1) << shard;

    const std::string prefix = absl::StrCat(Breakdown::GeneratorId_Name(Id()),
                                            "_", Label::Type_Name(object_type));
    const int camera_shard = shard % kNumCameras;
    switch (camera_shard) {
      case 0:
        return absl::StrCat(prefix, "_", "FRONT");
      case 1:
        return absl::StrCat(prefix, "_", "FRONT-LEFT");
      case 2:
        return absl::StrCat(prefix, "_", "FRONT-RIGHT");
      case 3:
        return absl::StrCat(prefix, "_", "SIDE-LEFT");
      case 4:
        return absl::StrCat(prefix, "_", "SIDE-RIGHT");
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }

  bool IsGroundTruthOnlyBreakdown() const { return true; }

 private:
  bool Is2DCamera(const Object& object) const {
    return object.has_camera_name();
  }

  int GetShardOffsetByCameraName(CameraName::Name camera_name) const {
    switch (camera_name) {
      case CameraName::FRONT:
        return 0;
      case CameraName::FRONT_LEFT:
        return 1;
      case CameraName::FRONT_RIGHT:
        return 2;
      case CameraName::SIDE_LEFT:
        return 3;
      case CameraName::SIDE_RIGHT:
        return 4;
      default:
        LOG(FATAL) << "Code should not reach here.";
    }
  }

  std::vector<CameraName::Name> EstimateCameraNamesByFov(
      const Object& object) const {
    std::vector<CameraName::Name> camera_names;
    constexpr double kRadToDegree = 180.0 / M_PI;
    // The field-of-view of the camera images is approximately +-25.2 degrees.
    constexpr double kHalfFovDeg = 25.2;
    // Considering the vehicle coordinate system, where the x-axis represents
    // the front direction, the y-axis represents the left direction, we
    // estimate the angle of an object to the x-axis by calculating arctan(y/x).
    // Objects on the left side yield a positive angle, and objects on the right
    // side yield a negative angle.
    constexpr double kFrontCameraDeg = 0.0;
    constexpr double kFrontLeftCameraDeg = 45.0;
    constexpr double kFrontRightCameraDeg = -45.0;
    constexpr double kSideLeftCameraDeg = 90.0;
    constexpr double kSideRightCameraDeg = -90.0;

    const double c_x = object.object().box().center_x();
    const double c_y = object.object().box().center_y();
    const double c_deg = std::atan2(c_y, c_x) * kRadToDegree;
    if (c_deg > (kFrontCameraDeg - kHalfFovDeg) &&
        c_deg < (kFrontCameraDeg + kHalfFovDeg))
      camera_names.push_back(CameraName::FRONT);
    if (c_deg > (kFrontLeftCameraDeg - kHalfFovDeg) &&
        c_deg < (kFrontLeftCameraDeg + kHalfFovDeg))
      camera_names.push_back(CameraName::FRONT_LEFT);
    if (c_deg > (kFrontRightCameraDeg - kHalfFovDeg) &&
        c_deg < (kFrontRightCameraDeg + kHalfFovDeg))
      camera_names.push_back(CameraName::FRONT_RIGHT);
    if (c_deg > (kSideLeftCameraDeg - kHalfFovDeg) &&
        c_deg < (kSideLeftCameraDeg + kHalfFovDeg))
      camera_names.push_back(CameraName::SIDE_LEFT);
    if (c_deg > (kSideRightCameraDeg - kHalfFovDeg) &&
        c_deg < (kSideRightCameraDeg + kHalfFovDeg))
      camera_names.push_back(CameraName::SIDE_RIGHT);
    return camera_names;
  }
};

std::unique_ptr<BreakdownGenerator> BreakdownGenerator::Create(
    Breakdown::GeneratorId id) {
  switch (id) {
    case Breakdown::OBJECT_TYPE:
      return absl::make_unique<BreakdownGeneratorObjectType>();
    case Breakdown::ONE_SHARD:
      return absl::make_unique<BreakdownGeneratorOneShard>();
    case Breakdown::RANGE:
      return absl::make_unique<BreakdownGeneratorRange>();
    case Breakdown::VELOCITY:
      return absl::make_unique<BreakdownGeneratorVelocity>();
    case Breakdown::ALL_BUT_SIGN:
      return absl::make_unique<BreakdownGeneratorAllButSign>();
    case Breakdown::SIZE:
      return absl::make_unique<BreakdownGeneratorSize>();
    case Breakdown::CAMERA:
      return absl::make_unique<BreakdownGeneratorCamera>();
    default:
      LOG(FATAL) << "Unimplemented breakdown generator "
                 << Breakdown::GeneratorId_Name(id);
  }
}

}  // namespace open_dataset
}  // namespace waymo


text:
<action>
    <field name="view_cls">chart_view</field>
    <field name="model">report.sale</field>
    <field name="method">expected_revenue</field>
    <field name="chart_type">bar</field>
</action>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Bootstrap.NET.Helpers
{
    internal static class Extensions
    {
        public static bool HasKey(this StateBag bag, string key)
        {
            foreach (string bagKey in bag.Keys)
            {
                if (bagKey == key)
                    return true;
            }
            return false;
        }

        public static T GetValue<T>(this StateBag bag, string key, T defaultValue) where T : class
        {
            if (!bag.HasKey(key))
                return defaultValue;

            return bag[key] as T;
        }

        public static void AddRange(this ControlCollection thisCollection, ControlCollection collection)
        {
            foreach (Control control in collection)
            {
                thisCollection.Add(control);
            }
        }

        public static string ToRender(this Enum enumerator)
        {
            Type type = enumerator.GetType();
            System.Reflection.FieldInfo fieldInfo = type.GetField(enumerator.ToString());
            RenderAttribute attribute = fieldInfo.GetCustomAttributes(typeof(RenderAttribute), false).FirstOrDefault() as RenderAttribute;
            if (attribute == null)
                return enumerator.ToString();

            return attribute.ToString();
        }

        public static bool HasAttribute(Type what, Type which)
        {
            return !(Attribute.GetCustomAttribute(what, which) == null);
        }

        public static bool IsEmpty(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        public static bool IsSet(this string str)
        {
            return !str.IsEmpty();
        }

        public static void AddClass(this WebControl control, string cssClass) {
            if (string.IsNullOrWhiteSpace(control.CssClass)) {
                control.CssClass = cssClass;
            } else {
                control.CssClass = string.Format("{0} {1}", cssClass, control.CssClass);
            }
        }

        public static void EnsureClass(this WebControl control, string cssClass) {
            if (!control.CssClass.Contains(cssClass)) {
                control.AddClass(cssClass);
            }
        }
    }
}


text:
/**
 distortion_plate.cpp
 Purpose: This files contains the body for the functions defined in distortion_plate.h

 @author Ignasi Pérez-Ràfols
 @version 1.0 04/04/2016
 */

#include "distortion_plate.h"

DistortionPlate::DistortionPlate(int bad_data){
    /**
     EXPLANATION:
     Constructs a DistortionPlate instance and initializes all its variables

     INPUTS:
     bad_data - a double valued _BAD_DATA_INT_

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     ToStr
     */
    if (bad_data != _BAD_DATA_INT_){
        std::cout << "Error while initializing a DistortionPlate 'bad data' instance" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    plate_number_ = _BAD_DATA_INT_;

}

DistortionPlate::DistortionPlate(const Input& input, const int plate_number, const std::vector<int>& plate_neighbours){
    /**
     EXPLANATION:
     Cosntructs a DistortionPlate instance and initializes all its variables

     INPUTS:
     input - a Input instance
     plate_number - an integer with the plate number
     plate_neighbours - a vector containing the plate numbers of the neighbouring plates

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     ToStr
     */

    // set flags from input
    flag_verbose_distortion_plate_ = input.flag_verbose_distortion_plate();

    plate_number_ = plate_number;
    plate_neighbours_ = plate_neighbours;
    num_bins_ = input.num_bins();
    pairs_file_name_ = ToStr(plate_number_);

    // initialize distortion matrix computation
    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = 0; j < num_bins_; j++){
            dist_mat_[std::pair<size_t,size_t>(i,j)] = 0.0;
        }
    }
    weight_.resize(num_bins_,0.0);

}

DistortionPlate::DistortionPlate(const int plate_number, const int num_bins, const std::vector<int>& plate_neighbours, size_t flag_verbose_distortion_plate){
    /**
     EXPLANATION:
     Cosntructs a DistortionPlate instance and initializes all its variables

     INPUTS:
     input - a Input instance
     plate_number - an integer with the plate number
     plate_neighbours - a vector containing the plate numbers of the neighbouring plates
     flag_verbose_distortion_plate - correlation_plate verbose flag

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     ToStr
     */

    flag_verbose_distortion_plate_ = flag_verbose_distortion_plate;

    plate_number_ = plate_number;
    plate_neighbours_ = plate_neighbours;
    num_bins_ = num_bins;

    // initialize distortion matrix computation
    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = 0; j < num_bins_; j++){
            dist_mat_[std::pair<size_t,size_t>(i,j)] = 0.0;
        }
    }
    weight_.resize(num_bins_,0.0);
}

double DistortionPlate::weight(size_t index) const {
    /**
     EXPLANATION:
     Access function for weight_

     INPUTS:
     index - index of the selected weight_ element

     OUTPUTS:
     NONE

     CLASSES USED:
     CorrelationPlate

     FUNCITONS USED:
     NONE
     */

    if (index < weight_.size()){
        return weight_[index];
    }
    else{
        return _BAD_DATA_;
    }
}

void DistortionPlate::set_dist_mat(size_t i, size_t j, double value){
    /**
     EXPLANATION:
     Set function for dist_mat_

     INPUTS:
     i,j - indexs of the selected dist_mat_ element
     value - element's new value

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     NONE
     */

    DistMat::iterator it = dist_mat_.find(std::pair<size_t, size_t>(i,j));
    if (it != dist_mat_.end()){
        (*it).second = value;
    }
    else{
        std::cout << "Warining: in DistortionPlate::set_dist_mat(i, j, value): The given index is out of bouds, ignoring..." << std::endl;
    }
}

void DistortionPlate::set_weight(size_t index, double value){
    /**
     EXPLANATION:
     Set function for weight_

     INPUTS:
     index - index of the selected weight_ element
     value - element's new value

     OUTPUTS:
     NONE

     CLASSES USED:
     CorrelationPlate

     FUNCITONS USED:
     NONE
     */

    if (index < weight_.size()){
        weight_[index] = value;
    }
    else{
        std::cout << "Warining: in CorrelationPlate::set_weight(index, value): The given index is out of bouds, ignoring..." << std::endl;
    }
}

void DistortionPlate::AddPair(const LyaPixel& pixel, const LyaPixel& pixel2, const size_t& i, const size_t& j, const double& forest_total_weight, const double& forest_mean_loglam, const double& forest_aux){
    /**
     EXPLANATION:
     Adds pair contribution to the distortion matrix in the specified bin

     INPUTS:
     pixel,pixel2 - LyaPixel instances to add the contribution from
     i,j - distortion matrix element to add the contributions to
     forest_total_weight - sum of the weights of all the pixels in the forest
     forest_mean_loglam - mean logarithm of wavelength of the forest
     forest_aux - sum of (loglam-forest_mean_loglam)*weigth of all the pixels in the forest

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate
     LyaAutoInterpolationMap
     LyaPixel

     FUNCITONS USED:
     NONE
     */

    DistMat::iterator it;
    it = dist_mat_.find(std::pair<int, int>(i, j));

    if (it == dist_mat_.end()){
        std::cout << "Warning : In CovarianceMatrix::ComputeDistMat : Element " << i << ", " << j << " of the distortion matrix not found. Ignoring..."  << std::endl;
        return;
    }

    if (forest_total_weight == 0.0 or forest_aux == 0.0){
        std::cout << "Warning : In CovarianceMatrix::ComputeDistMat : Zero division error encounterd. Ignoring..."  << std::endl;
        return;
    }

    // add to distortion matrix
    double weight = pixel.weight();
    double add;
    if (i == j){
        add = 1.0-pixel2.weight()/forest_total_weight-(pixel2.loglam()-forest_mean_loglam)*(pixel.loglam()-forest_mean_loglam)*pixel2.weight()/forest_aux;
    }
    else{
        add = -pixel2.weight()/forest_total_weight-(pixel2.loglam()-forest_mean_loglam)*(pixel.loglam()-forest_mean_loglam)*pixel2.weight()/forest_aux;
    }

    (*it).second += add*weight;

}

void DistortionPlate::ComputeDistMat(const AstroObjectDataset& object_list, const SpectraDataset& spectra_list, const Input& input){
    /**
     EXPLANATION:
     Computes the distortion matrix

     INPUTS:
     object_list - an AstroObjectDataset instance
     spectra_list - a SpectraDataset instance
     input - a Input instance to load bin settings

     OUTPUTS:
     NONE

     CLASSES USED:
     AstroObjectDataset
     DistortionPlate
     Input
     LyaPixel
     LyaSpectrum
     SpectraDataset

     FUNCITONS USED:
     NONE
     */
    if (plate_number_ == _NORM_){
        #pragma omp critical (cout)
        {
            std::cout << "Warning : In DistortionPlate::ComputeDistMatrix : Plate number is set to _NORM_. The distortion should not be computed in this DistortionPlate instance. Ignoring..." << std::endl;
        }
        return;
    }

    // load bin settings
    double max_pi = input.max_pi();
    double max_sigma = input.max_sigma();
    double step_pi = input.step_pi();
    double step_sigma = input.step_sigma();
    double num_pi_bins = input.num_pi_bins();
    double num_sigma_bins = input.num_sigma_bins();
    size_t pixels_separation = input.pixels_separation();

    size_t number_of_spectra = spectra_list.num_objects_in_plate(plate_number_);

    if (flag_verbose_distortion_plate_ >= 1){
        #pragma omp critical (cout)
        {
            std::cout << "Computing distortion_matrix in plate " << plate_number_ << ". In this plate there are " << number_of_spectra << " LyaSpectra" << std::endl;
        }
    }
    if (number_of_spectra == 0){
        return;
    }

    // loop over LyaSpectra
    for (size_t lya_spectrum_num = 0; lya_spectrum_num < number_of_spectra; lya_spectrum_num ++){

        LyaSpectrum lya_spectrum = spectra_list.list(plate_number_, lya_spectrum_num);
        // checking that the object was loaded successfully
        if (lya_spectrum.dist() == _BAD_DATA_){
            if (flag_verbose_distortion_plate_ >= 2){
                #pragma omp critical (cout)
                {
                    std::cout << "_BAD_DATA_ LyaSpectrum found. Ignoring..." << std::endl;
                }
            }
            continue;
        }
        std::vector<LyaPixel> spectrum = lya_spectrum.spectrum();

        // compute forest variables (loop over forest pixels, twice)
        double forest_aux = 0.0; //forest_aux: sum of (loglam-forest_mean_loglam)**2*weigth of all the pixels in the forest
        double forest_total_weight = 0.0;
        double forest_mean_loglam = 0.0;

        for (int pixel = 0; pixel < spectrum.size(); pixel ++){
            forest_total_weight += spectrum[pixel].weight();
            forest_mean_loglam += spectrum[pixel].loglam()*spectrum[pixel].weight();
        }
        forest_mean_loglam /= forest_total_weight;

        for (int pixel = 0; pixel < spectrum.size(); pixel ++){
            forest_aux += (spectrum[pixel].loglam()-forest_mean_loglam)*(spectrum[pixel].loglam()-forest_mean_loglam)*spectrum[pixel].weight();
        }

        // loop over neighbouring plates
        for (size_t plate_neighbours_num = 0; plate_neighbours_num < plate_neighbours_.size(); plate_neighbours_num ++){

            size_t number_of_objects = object_list.num_objects_in_plate(plate_neighbours_[plate_neighbours_num]);
            if (number_of_objects == 0){
                continue;
            }

            // loop over AstroObjects
            for (size_t object_num = 0; object_num < number_of_objects; object_num ++){

                AstroObject object = object_list.list(plate_neighbours_[plate_neighbours_num], object_num);

                // checking that the object was loaded successfully
                if (object.dist() == _BAD_DATA_){
                    if (flag_verbose_distortion_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "_BAD_DATA_ AstroObject found. Ignoring..." << std::endl;
                        }
                    }
                    continue;
                }

                double sigma_aux_o = 2.0*object.dist(); // auxiliar variable to compute sigma values

                // compute angular separation
                double cos_theta = object.angle().CosAngularDistance(lya_spectrum.angle());

                double sigma_aux;
                if (cos_theta == 1.0){
                    sigma_aux = 0.0;
                }
                else{
                    sigma_aux = sigma_aux_o*(1.0-cos_theta); // auxiliar variable to compute sigma values
                }

                // check if all pixels in the spectrum are too far apart
                double pair_min_sigma = sqrt(sigma_aux*spectrum[0].dist()); // minimum distance obtained for lowest redshift pixel
                if (pair_min_sigma > max_sigma){ // if the minimum value for sigma (r_perp) is too large, the whole spectra is discarded
                    if (flag_verbose_distortion_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: min_sigma is too large" << std::endl;
                        }
                        if (flag_verbose_distortion_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "min_sigma = " << pair_min_sigma << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object.angle() << " " << lya_spectrum.angle() << " " << cos_theta << " " << acos(cos_theta) << " " << pair_min_sigma << std::endl;
                            }
                        }
                    }
                    continue;
                }
                // if the spectrum is being paired with its quasar, the whole spectra is discarded
                if (pair_min_sigma <= 0.1){
                    if (flag_verbose_distortion_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: It is being paired with its origin quasar" << std::endl;
                        }
                    }
                    continue;
                }

                double pair_max_pi = spectrum.back().dist() - object.dist(); // minimum distance obtained for lowest redshift pixel
                if (pair_max_pi < -max_pi) { // if maximum value for pi (r_par) is too small, the whole spectra is discarded
                    if (flag_verbose_distortion_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: max_pi is too small" << std::endl;
                        }
                        if (flag_verbose_distortion_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "max_pi = " << pair_max_pi << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object.angle() << " " << lya_spectrum.angle() << " " << cos_theta << " " << acos(cos_theta) << " " << pair_max_pi << std::endl;
                            }
                        }
                    }
                    continue;
                }

                double pair_min_pi = spectrum[0].dist() - object.dist(); // maximum distance obtained for highest redshift pixel
                if (pair_min_pi > max_pi){ // if minimum value for pi (r_par) is too high, the whole spectrum is discarded
                    if (flag_verbose_distortion_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: min_pi is too large" << std::endl;
                        }
                        if (flag_verbose_distortion_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "min_pi = " << pair_min_pi << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object.angle() << " " << lya_spectrum.angle() << " " << cos_theta << " " << acos(cos_theta) << " " << pair_min_pi << std::endl;
                            }
                        }
                    }
                    continue;
                }

                // loop over LyaPixels 1
                for (int pixel1 = 0; pixel1 < spectrum.size(); pixel1 ++){

                    // cehck that the weight is not zero
                    if (spectrum[pixel1].weight() == 0.0){
                        continue;
                    }

                    // compute pi and sigma
                    double sigma1 = sqrt(sigma_aux*spectrum[pixel1].dist());
                    if (sigma1 > max_sigma){ // if sigma (r_perp) is too large, discard pixel
                        if (flag_verbose_distortion_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: sigma is too large" << std::endl;
                                std::cout << "sigma = " << sigma1 << std::endl;
                            }
                        }
                        continue;
                    }

                    double pi1 = spectrum[pixel1].dist()-object.dist();
                    if ((pi1 > max_pi) or (pi1 <- max_pi)){ // if pi (r_par) is too large or too small, discard pixel
                        if (flag_verbose_distortion_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: abs(pi) is too large" << std::endl;
                                std::cout << "pi = " << pi1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate pi pixel (i_index)
                    int i_index1 = int(pi1/step_pi)+num_pi_bins/2;
                    if (pi1<0.0){
                        i_index1 -= 1;
                    }
                    if (i_index1 < 0){
                        if (flag_verbose_distortion_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: i_index = " << i_index1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate sigma pixel (j_index)
                    int j_index1 = int(sigma1/step_sigma);
                    if (j_index1 < 0){
                        if (flag_verbose_distortion_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: j_index = " << j_index1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate xi pixel1 (k)
                    int k_index1 = i_index1*num_sigma_bins+j_index1;
                    if (k_index1 < 0){
                        if (flag_verbose_distortion_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: k_index = " << k_index1 << std::endl;
                            }
                        }
                        continue;

                    }

                    // add pixel's weight to the total weight of the bin
                    weight_[k_index1] += spectrum[pixel1].weight();

                    // loop over LyaPixels 2
                    for (int pixel2 = pixel1; pixel2 < spectrum.size(); pixel2 ++){

                        // compute pi and sigma
                        double sigma2 = sqrt(sigma_aux*spectrum[pixel2].dist());
                        if (sigma2 > max_sigma){ // if sigma (r_perp) is too large, discard pixel
                            if (flag_verbose_distortion_plate_ >= 3){
                                #pragma omp critical (cout)
                                {
                                    std::cout << "Pixel rejected: sigma is too large" << std::endl;
                                    std::cout << "sigma = " << sigma2 << std::endl;
                                }
                            }
                            continue;
                        }

                        double pi2 = spectrum[pixel2].dist()-object.dist();
                        if ((pi2 > max_pi) or (pi2 <- max_pi)){ // if pi (r_par) is too large or too small, discard pixel
                            if (flag_verbose_distortion_plate_ >= 3){
                                #pragma omp critical (cout)
                                {
                                    std::cout << "Pixel rejected: abs(pi) is too large" << std::endl;
                                    std::cout << "pi = " << pi2 << std::endl;
                                }
                            }
                            continue;
                        }

                        // locate pi pixel (i_index)
                        int i_index2 = int(pi2/step_pi)+num_pi_bins/2;
                        if (pi2<0.0){
                            i_index2 -= 1;
                        }
                        if (i_index2 < 0){
                            if (flag_verbose_distortion_plate_ >= 2){
                                #pragma omp critical (cout)
                                {
                                    std::cout << "Pixel rejected: Bad indexing: i_index = " << i_index2 << std::endl;
                                }
                            }
                            continue;
                        }

                        // locate sigma pixel (j_index)
                        int j_index2 = int(sigma2/step_sigma);
                        if (j_index2 < 0){
                            if (flag_verbose_distortion_plate_ >= 2){
                                #pragma omp critical (cout)
                                {
                                    std::cout << "Pixel rejected: Bad indexing: j_index = " << j_index2 << std::endl;
                                }
                            }
                            continue;
                        }

                        // locate xi pixel2 (k)
                        int k_index2 = i_index2*num_sigma_bins+j_index2;
                        if (k_index2 < 0){
                            if (flag_verbose_distortion_plate_ >= 2){
                                #pragma omp critical (cout)
                                {
                                    std::cout << "Pixel rejected: Bad indexing: k_index = " << k_index2 << std::endl;
                                }
                            }
                            continue;

                        }

                        AddPair(spectrum[pixel1], spectrum[pixel2], k_index1, k_index2, forest_total_weight, forest_mean_loglam, forest_aux);

                        if (k_index1 != k_index2){
                            AddPair(spectrum[pixel2], spectrum[pixel1], k_index2, k_index1, forest_total_weight, forest_mean_loglam, forest_aux);
                        }

                    }

                }
            }
        }
    }

}

void DistortionPlate::Normalize(){
    /**
     EXPLANATION:
     Normalizes the distortion matrix

     INPUTS:
     NONE

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     NONE
     */

    if (plate_number_ == _NORM_){

        DistMat::iterator it;
        for (size_t i = 0; i < num_bins_; i ++){
            for (size_t j = 0; j < num_bins_; j ++){
                it = dist_mat_.find(std::pair<size_t,size_t>(i,j));
                if (it != dist_mat_.end() and weight_[i] != 0.0 and (*it).second != 0.0){
                    (*it).second /= weight_[i];
                }
            }
        }

    }
    else{
        // if plate number is not _NORM_, the instance is not supposed to normalize
        std::cout << "Warning : In DistortionPlate::Normalize : Plate number is not set to _NORM_. This DistortionPlate instance should not be normalized. Ignoring..." << std::endl;
    }

}

void DistortionPlate::SaveDistMat(const Input& input){
    /**
     EXPLANATION:
     Saves the distortion matrix measured in a specific plate

     INPUTS:
     input - a Input instance

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */
    if (plate_number_ == _NORM_){
        // if plate number is _NORM_, the instance is not supposed to be saved using this function
        std::cout << "Warning : In DistortionPlate::SaveDistMat : Plate number is not set to _NORM_. This DistortionPlate instance should not be saved using this function. Ignoring..." << std::endl;
    }
    else{
        std::string filename;
        DistMat::iterator it, it_weight;

        if (flag_verbose_distortion_plate_ >= 1){
            std::cout << "Saving distortion matrix contribution from plate " << pairs_file_name_ << std::endl;
        }

        filename = input.results() + "plate_" + pairs_file_name_ + ".dmat";
        {
            std::ofstream file(filename.c_str(),std::ofstream::trunc);
            if (file.is_open()){
                if (flag_verbose_distortion_plate_ >= 2){
                    std::cout << "Saving distortion matrix contribution" << std::endl;
                }
                file << "# i j dmat" << std::endl;
                for (size_t i = 0; i < num_bins_; i ++){
                    for (size_t j = 0; j < num_bins_; j ++){
                        it = dist_mat_.find(std::pair<size_t,size_t>(i,j));
                        if (it != dist_mat_.end()){
                            file << i << " " << j << " " << (*it).second << std::endl;
                        }
                    }
                }
                file << "# i weight" << std::endl;
                for (size_t i = 0; i < num_bins_; i ++){
                    file << i << weight_[i] << std::endl;
                }
                file.close();
            }
            else{
                std::cout << "Error : In DistortionPlate::SaveDistMat : Unable to open file:" << std::endl << filename << std::endl;
            }
        }

    }

}

void DistortionPlate::operator+= (const DistortionPlate& other){
    /**
     EXPLANATION:
     Overloads the += operator. Updates the dist_mat_ values by adding those in other.

     INPUTS:
     other - a DistortionPlate instance to be added

     OUTPUTS:
     NONE

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     NONE
     */

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In DistortionPlate::operator+= : Trying to add DistortionPlates with different number of bins. Ignoring..." << std::endl;
        return;
    }

    DistMat::iterator it;
    DistMat::const_iterator other_it;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = 0; j < num_bins_; j++){
            it = dist_mat_.find(std::pair<size_t,size_t>(i,j));
            other_it = other.dist_mat_.find(std::pair<size_t,size_t>(i,j));
            if (it != dist_mat_.end() and other_it != other.dist_mat_.end()){
                (*it).second += (*other_it).second;
            }
        }
        weight_[i] += other.weight(i);
    }

}

DistortionPlate DistortionPlate::operator- (const DistortionPlate& other){
    /**
     EXPLANATION:
     Overloads the - operator. Returns a new instance with the dist_mat subtracted by those in other.

     INPUTS:
     other - a DistortionPlate instance to be subtracted

     OUTPUTS:
     temp - a DistortionPlate instance

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     NONE
     */

    DistortionPlate temp;
    temp = DistortionPlate(plate_number_, num_bins_, plate_neighbours_, flag_verbose_distortion_plate_);

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In DistortionPlate::operator+= : Trying to add DistortionPlates with different number of bins. Returning zero filled DistortionPlates..." << std::endl;
        return temp;
    }

    DistMat::iterator it;
    DistMat::const_iterator other_it;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = 0; j < num_bins_; j++){
            it = dist_mat_.find(std::pair<size_t,size_t>(i,j));
            other_it = other.dist_mat_.find(std::pair<size_t,size_t>(i,j));
            if (it != dist_mat_.end() and other_it != other.dist_mat_.end()){
                temp.set_dist_mat(i, j, (*it).second - (*other_it).second);
            }
        }
        temp.set_weight(i, weight_[i] - other.weight(i));
    }

    return temp;

}

DistortionPlate DistortionPlate::operator* (const DistortionPlate& other){
    /**
     EXPLANATION:
     Overloads the * operator. Returns a new instance with the xi_, mean_sigma, mean_pi and weight_ values multiplied by those in other.

     INPUTS:
     other - a DistortionPlate instance to be subtracted

     OUTPUTS:
     temp - a DistortionPlate instance

     CLASSES USED:
     DistortionPlate

     FUNCITONS USED:
     NONE
     */
    DistortionPlate temp;
    temp = DistortionPlate(plate_number_, num_bins_, plate_neighbours_, flag_verbose_distortion_plate_);

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In DistortionPlate::operator+= : Trying to add DistortionPlates with different number of bins. Returning zero filled DistortionPlates..." << std::endl;
        return temp;
    }

    DistMat::iterator it;
    DistMat::const_iterator other_it;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = 0; j < num_bins_; j++){
            it = dist_mat_.find(std::pair<size_t,size_t>(i,j));
            other_it = other.dist_mat_.find(std::pair<size_t,size_t>(i,j));
            if (it != dist_mat_.end() and other_it != other.dist_mat_.end()){
                temp.set_dist_mat(i, j, (*it).second*(*other_it).second);
            }
        }
        temp.set_weight(i, weight_[i]*other.weight(i));
    }

    return temp;

}


text:
/**
 * Created by barakedry on 6/19/15.
 */
'use strict';

let Utils = {
    isValid: function (val) {
        // val === val for cases val is NaN value
        return val === val;
    },
    concatPath: function (path, suffix) {
        if (path && suffix) {
            return [path, suffix].join('.');
        }

        return path || suffix;
    },
    wrapByPath: function wrapByPath(value, path) {

        let levels,
            wrapper,
            curr,
            i,
            len;

        if (!path) {
            return value;
        }

        levels = path.split('.');
        len = levels.length;
        i = 0;
        wrapper = {};
        curr = wrapper;

        while (i < (len - 1)) {
            curr[levels[i]] = {};
            curr = curr[levels[i]];
            i++;
        }

        curr[levels[i]] = value;

        return wrapper;
    },

    hasSamePrototype: function (obj1, obj2) {
        return typeof obj1 === 'object' && Object.getPrototypeOf(obj1) === Object.getPrototypeOf(obj2);
    },

    SERIALIZABLE_FUNCTION: {
        toJSON: function () {
            return 'function()';
        }
    }
};

module.exports = Utils;


text:
#include <utils/String16.h>
#include <utils/String8.h>

#include <gtest/gtest.h>

namespace android {

::testing::AssertionResult Char16_tStringEquals(const char16_t* a, const char16_t* b) {
    if (strcmp16(a, b) != 0) {
        return ::testing::AssertionFailure()
               << "\"" << String8(a).c_str() << "\" not equal to \"" << String8(b).c_str() << "\"";
    }
    return ::testing::AssertionSuccess();
}

#define EXPECT_STR16EQ(a, b) EXPECT_TRUE(Char16_tStringEquals(a, b))

TEST(String16Test, FromChar16_t) {
    String16 tmp(u"Verify me");
    EXPECT_STR16EQ(u"Verify me", tmp);
}

TEST(String16Test, FromChar16_tSized) {
    String16 tmp(u"Verify me", 7);
    EXPECT_STR16EQ(u"Verify ", tmp);
}

TEST(String16Test, FromChar) {
    String16 tmp("Verify me");
    EXPECT_STR16EQ(u"Verify me", tmp);
}

TEST(String16Test, FromCharSized) {
    String16 tmp("Verify me", 7);
    EXPECT_STR16EQ(u"Verify ", tmp);
}

TEST(String16Test, Copy) {
    String16 tmp("Verify me");
    String16 another = tmp;
    EXPECT_STR16EQ(u"Verify me", tmp);
    EXPECT_STR16EQ(u"Verify me", another);
}

TEST(String16Test, CopyAssign) {
    String16 tmp("Verify me");
    String16 another;
    another = tmp;
    EXPECT_STR16EQ(u"Verify me", tmp);
    EXPECT_STR16EQ(u"Verify me", another);
}

TEST(String16Test, Move) {
    String16 tmp("Verify me");
    String16 another(std::move(tmp));
    EXPECT_STR16EQ(u"Verify me", another);
}

TEST(String16Test, MoveAssign) {
    String16 tmp("Verify me");
    String16 another;
    another = std::move(tmp);
    EXPECT_STR16EQ(u"Verify me", another);
}

TEST(String16Test, Size) {
    String16 tmp("Verify me");
    EXPECT_EQ(9U, tmp.size());
}

TEST(String16Test, setTo) {
    String16 tmp("Verify me");
    tmp.setTo(u"New content");
    EXPECT_EQ(11U, tmp.size());
    EXPECT_STR16EQ(u"New content", tmp);
}

TEST(String16Test, Append) {
    String16 tmp("Verify me");
    tmp.append(String16("Hello"));
    EXPECT_EQ(14U, tmp.size());
    EXPECT_STR16EQ(u"Verify meHello", tmp);
}

TEST(String16Test, Insert) {
    String16 tmp("Verify me");
    tmp.insert(6, u"Insert");
    EXPECT_EQ(15U, tmp.size());
    EXPECT_STR16EQ(u"VerifyInsert me", tmp);
}

TEST(String16Test, ReplaceAll) {
    String16 tmp("Verify verify Verify");
    tmp.replaceAll(u'r', u'!');
    EXPECT_STR16EQ(u"Ve!ify ve!ify Ve!ify", tmp);
}

TEST(String16Test, Compare) {
    String16 tmp("Verify me");
    EXPECT_EQ(String16(u"Verify me"), tmp);
}

TEST(String16Test, StaticString) {
    String16 nonStaticString("NonStatic");
    StaticString16 staticString(u"Static");

    EXPECT_TRUE(staticString.isStaticString());
    EXPECT_FALSE(nonStaticString.isStaticString());
}

TEST(String16Test, StaticStringCopy) {
    StaticString16 tmp(u"Verify me");
    String16 another = tmp;
    EXPECT_STR16EQ(u"Verify me", tmp);
    EXPECT_STR16EQ(u"Verify me", another);
    EXPECT_TRUE(tmp.isStaticString());
    EXPECT_TRUE(another.isStaticString());
}

TEST(String16Test, StaticStringMove) {
    StaticString16 tmp(u"Verify me");
    String16 another(std::move(tmp));
    EXPECT_STR16EQ(u"Verify me", another);
    EXPECT_TRUE(another.isStaticString());
}

TEST(String16Test, StaticStringSize) {
    StaticString16 tmp(u"Verify me");
    EXPECT_EQ(9U, tmp.size());
}

TEST(String16Test, StaticStringSetTo) {
    StaticString16 tmp(u"Verify me");
    tmp.setTo(u"New content");
    EXPECT_EQ(11U, tmp.size());
    EXPECT_STR16EQ(u"New content", tmp);
    EXPECT_FALSE(tmp.isStaticString());
}

TEST(String16Test, StaticStringAppend) {
    StaticString16 tmp(u"Verify me");
    tmp.append(String16("Hello"));
    EXPECT_EQ(14U, tmp.size());
    EXPECT_STR16EQ(u"Verify meHello", tmp);
    EXPECT_FALSE(tmp.isStaticString());
}

TEST(String16Test, StaticStringInsert) {
    StaticString16 tmp(u"Verify me");
    tmp.insert(6, u"Insert");
    EXPECT_EQ(15U, tmp.size());
    EXPECT_STR16EQ(u"VerifyInsert me", tmp);
    EXPECT_FALSE(tmp.isStaticString());
}

TEST(String16Test, StaticStringReplaceAll) {
    StaticString16 tmp(u"Verify verify Verify");
    tmp.replaceAll(u'r', u'!');
    EXPECT_STR16EQ(u"Ve!ify ve!ify Ve!ify", tmp);
    EXPECT_FALSE(tmp.isStaticString());
}

TEST(String16Test, StaticStringCompare) {
    StaticString16 tmp(u"Verify me");
    EXPECT_EQ(String16(u"Verify me"), tmp);
}

TEST(String16Test, StringSetToStaticString) {
    StaticString16 tmp(u"Verify me");
    String16 another(u"nonstatic");
    another = tmp;
    EXPECT_STR16EQ(u"Verify me", tmp);
    EXPECT_STR16EQ(u"Verify me", another);
}

TEST(String16Test, StringCopyAssignFromStaticString) {
    StaticString16 tmp(u"Verify me");
    String16 another(u"nonstatic");
    another = tmp;
    EXPECT_STR16EQ(u"Verify me", another);
    EXPECT_TRUE(another.isStaticString());
    EXPECT_STR16EQ(u"Verify me", tmp);
    EXPECT_TRUE(tmp.isStaticString());
}

TEST(String16Test, StringMoveAssignFromStaticString) {
    StaticString16 tmp(u"Verify me");
    String16 another(u"nonstatic");
    another = std::move(tmp);
    EXPECT_STR16EQ(u"Verify me", another);
    EXPECT_TRUE(another.isStaticString());
}

TEST(String16Test, EmptyStringIsStatic) {
    String16 tmp("");
    EXPECT_TRUE(tmp.isStaticString());
}

TEST(String16Test, OverreadUtf8Conversion) {
    char tmp[] = {'a', static_cast<char>(0xe0), '\0'};
    String16 another(tmp);
    EXPECT_TRUE(another.size() == 0);
}

TEST(String16Test, ValidUtf8Conversion) {
    String16 another("abcdef");
    EXPECT_EQ(6U, another.size());
    EXPECT_STR16EQ(another, u"abcdef");
}

}  // namespace android


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object4170816371.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings
struct  AdvancedSettings_t3928785196  : public Il2CppObject
{
public:
	// System.Single UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings::groundCheckDistance
	float ___groundCheckDistance_0;
	// System.Single UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings::stickToGroundHelperDistance
	float ___stickToGroundHelperDistance_1;
	// System.Single UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings::slowDownRate
	float ___slowDownRate_2;
	// System.Boolean UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings::airControl
	bool ___airControl_3;
	// System.Single UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController/AdvancedSettings::shellOffset
	float ___shellOffset_4;

public:
	inline static int32_t get_offset_of_groundCheckDistance_0() { return static_cast<int32_t>(offsetof(AdvancedSettings_t3928785196, ___groundCheckDistance_0)); }
	inline float get_groundCheckDistance_0() const { return ___groundCheckDistance_0; }
	inline float* get_address_of_groundCheckDistance_0() { return &___groundCheckDistance_0; }
	inline void set_groundCheckDistance_0(float value)
	{
		___groundCheckDistance_0 = value;
	}

	inline static int32_t get_offset_of_stickToGroundHelperDistance_1() { return static_cast<int32_t>(offsetof(AdvancedSettings_t3928785196, ___stickToGroundHelperDistance_1)); }
	inline float get_stickToGroundHelperDistance_1() const { return ___stickToGroundHelperDistance_1; }
	inline float* get_address_of_stickToGroundHelperDistance_1() { return &___stickToGroundHelperDistance_1; }
	inline void set_stickToGroundHelperDistance_1(float value)
	{
		___stickToGroundHelperDistance_1 = value;
	}

	inline static int32_t get_offset_of_slowDownRate_2() { return static_cast<int32_t>(offsetof(AdvancedSettings_t3928785196, ___slowDownRate_2)); }
	inline float get_slowDownRate_2() const { return ___slowDownRate_2; }
	inline float* get_address_of_slowDownRate_2() { return &___slowDownRate_2; }
	inline void set_slowDownRate_2(float value)
	{
		___slowDownRate_2 = value;
	}

	inline static int32_t get_offset_of_airControl_3() { return static_cast<int32_t>(offsetof(AdvancedSettings_t3928785196, ___airControl_3)); }
	inline bool get_airControl_3() const { return ___airControl_3; }
	inline bool* get_address_of_airControl_3() { return &___airControl_3; }
	inline void set_airControl_3(bool value)
	{
		___airControl_3 = value;
	}

	inline static int32_t get_offset_of_shellOffset_4() { return static_cast<int32_t>(offsetof(AdvancedSettings_t3928785196, ___shellOffset_4)); }
	inline float get_shellOffset_4() const { return ___shellOffset_4; }
	inline float* get_address_of_shellOffset_4() { return &___shellOffset_4; }
	inline void set_shellOffset_4(float value)
	{
		___shellOffset_4 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
import SocketServer, sys, argparse
from threading import Timer, Thread, Event
from time import strftime, localtime, sleep
from usi import *
from usiserver import *

def timeprint(string):
    print "[%s] %s" % (strftime("%Y-%m-%d %H:%M:%S", localtime()), string)

class TCPHandle(SocketServer.BaseRequestHandler):
    def do_error(self):
        self.request.send(error_msg(self.server.code))

    def handle(self):
        is_derived_close = False
        data = self.request.recv(PACK_HEAD_SIZE)
        pkg_keyword, pkg_size, pkg_type = unpack_head(data)
        user_host = self.client_address[0]
        timeprint("Request from %s with %s keyword, package size: %s" % (user_host, pkg_keyword, pkg_size))
        if pkg_type == PARAM_LIST:
            if pkg_size:
                data = self.request.recv(pkg_size)
                timeprint("Subscribe request")
                new_params = params_from_ask(data, self.server.usi_data.params)
                self.server.user_data[user_host] = { 'params' : set(new_params), 'code' : self.server.code, 'iter_index' : 0 }
                self.request.send(param_list_responce(self.server.code, new_params))
        elif pkg_type == PARAM_VALUES:
            if user_host not in self.server.user_data:
                timeprint('Attempt to get values from unsubscribed host %s' % user_host)
                self.do_error()
            else:
                timeprint('Request for values from %s' % user_host)
                timer_delay = self.server.delay / 1000
                self.server.user_data[user_host]['request'] = self.request
                self.server.user_data[user_host]['iter_index']  = 0
                telemetries_len = len(self.server.usi_data.telemetries)
                while self.server.user_data[user_host]['iter_index'] < telemetries_len:
                    try:
                        timeprint('Sending telemetry #%03d to %s' % (self.server.user_data[user_host]['iter_index'], user_host))
                        self.request.send(param_values_responce(self.server.code, self.server.usi_data.telemetries[self.server.user_data[user_host]['iter_index']], self.server.is_inner_time))
                        sleep(timer_delay)
                    except Exception as ex:
                        timeprint('Communication breakdown with %s' % user_host)
                        return
                    self.server.user_data[user_host]['iter_index'] += 1
                    if self.server.user_data[user_host]['iter_index']  >= telemetries_len: #and do_repeat:
                        self.server.user_data[user_host]['iter_index'] = 0
                is_derived_close = True
        elif pkg_type == PARAM_INFO:
            #not implemented. accessible only in db.
            pass
        elif pkg_type == PARAM_CHECKCONNECT:
            timeprint("Connection check request")
            self.request.send('connected')
        elif pkg_type == PARAM_ADD:
            timeprint("Request for adding subscriptions")
            if pkg_size:
                data = self.request.recv(pkg_size)
                new_params = params_from_ask(data, self.server.usi_data.params)
                if user_host in self.server.user_data:
                    map(lambda p : self.server.user_data[user_host]['params'].add(p), new_params)
                else:
                    self.server.user_data[user_host] = { params : set(new_params), iter_index : 0, request : None }
        elif pkg_type == PARAM_DEL:
            timeprint("Request for deleting subscriptions")
            if pkg_size and user_host in self.server.user_data:
                data = self.request.recv(pkg_size)
                del_params = params_from_ask_index(data, self.server.usi_data.params)
                params_container = self.server.user_data[user_host]['params']
                for del_param in del_params:
                    if del_param in params_container:
                        params_container.remove(del_param)
        elif pkg_type == PARAM_ERROR:
            timeprint('An error occured in client app at host %s' % user_host)
            self.server.cancel_user_host(user_host)
            self.server.del_user_host(user_host)
            is_derived_close = True
        elif pkg_type == PARAM_DISCONNECT:
            timeprint('Host %s has been disconnected' % user_host)
            self.server.cancel_user_host(user_host)
            self.server.del_user_host(user_host)
            is_derived_close = True
        if not is_derived_close:
            timeprint("Responce closed")
            self.request.close()

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def cancel_user_host(self, user_host):
        if user_host not in self.user_data: return
        if 'request' in self.user_data[user_host] and self.user_data[user_host]['request'] is not None:
            try:
                self.user_data[user_host]['request'].send(disconnect_msg(self.user_data[user_host]['code']))
                self.user_data[user_host]['request'].close()
            except Exception:
                print "User %s is left. The disconnect message wasn't sent." % user_host
            self.user_data[user_host]['request'] = None

    def del_user_host(self, user_host):
        del self.user_data[user_host]

    def clean_up(self):
        for user_host in self.user_data:
            self.cancel_user_host(user_host)

def callback_test_timer(string):
    print string

def is_output_only(args):
    return args.output_params or args.output

def load_arg_parser():
    parser = argparse.ArgumentParser(usage='%(prog)s [options]')
    parser.add_argument('-V', '--version', action='version', version='auriga %s' % VER)
    parser.add_argument('-o', '--output', action='store_true', default=False, help='just output usi file, without starting server')
    parser.add_argument('-u', '--output_params', action='store_true', default=False, help='just output params of loaded usi file, without starting server')
    parser.add_argument('-s', '--server', type=str, default="localhost", help='host to attach')
    parser.add_argument('-p', '--port', type=int, default=USI_PORT_DEFAULT, help='port to listen')
    parser.add_argument('-r', '--repeat', action='store_true', default=False, help='repeat USI')
    parser.add_argument('-t', '--time', action='store_true', default=False, help='add inner time')
    parser.add_argument('-d', '--delay', type=int, default=1000, help='delay of timer in msec')
    parser.add_argument('-c', '--code', type=str, default=CODE_GVM_DRAW, help='USI server code')
    parser.add_argument('usifile', nargs='?', type=argparse.FileType('rb'), default=sys.stdin, help='USI/USL file')

    return parser

def draw_logo(ARGS):
    print "*  *"
    print "    *  Auriga USI Server %s" % VER
    print "*      (c)Rikki Mongoose (http://github.com/rikkimongoose/auriga), 2015."
    print "    *  Auriga application started on %s:%s." % (ARGS.server, ARGS.port)
    print " *     Ctrl+C to shutdown server; call with --help for options."

def main():
    parser = load_arg_parser()

    try:
        ARGS = parser.parse_args()
    except Exception, e:
        sys.stderr.write("Unable to load file. Exception: %s" % e)
        exit(1)

    usi_loader = UsiDataLoader(ARGS.usifile)

    output_only_mode = is_output_only(ARGS)
    usi_loader.debug_output = ARGS.output
    usi_data = usi_loader.do_load()
    if output_only_mode:
        if ARGS.output_params:
            for param in usi_data.params: print ("%s %s\n" % (param.name, param.param_type))
            print ""
        return
    try:
        server = ThreadedTCPServer((ARGS.server, ARGS.port), TCPHandle)
    except Exception:
        sys.stderr.write('Socket %s:%s is already occupied. Unable to run Auriga server.\n' % (ARGS.server, ARGS.port))
        quit()
    server.usi_data = usi_data
    server.code = ARGS.code
    server.repeat = ARGS.repeat
    server.delay = ARGS.delay
    server.is_inner_time = ARGS.time
    server.user_data = {}

    draw_logo(ARGS)

    try:
       server.serve_forever()
    except KeyboardInterrupt:
        server.clean_up()

if __name__ == "__main__":
    main()


text:
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint
from keras import backend as K

# In[13]:

import pickle

pickle_file = '-data.pickle'

with open(pickle_file, 'rb') as f:
    save = pickle.load(f)
    typesList = save['typesList']
    del save

# In[14]:

import os
from scipy import misc

imageFolder = "-temp"

image_dim = 1 # black and white
image_size = 32

data = []

fileNames = os.listdir(imageFolder)

for fileName in fileNames:

    img = misc.imread("/".join([imageFolder, fileName]))

    if image_dim == 1 and len(img.shape) > 2:
        img = img[:,:,0] # convert to black and white

    if img.shape[0] != image_size or img.shape[1] != image_size:
        img = misc.imresize(img, (image_size, image_size), interp='nearest')

    img = (img - img.mean()) / img.std() / 4 + 0.5

    data.append([img])

# In[15]:

import numpy as np

X = np.ndarray((len(data), image_size, image_size), dtype=np.float32)

for i, d in enumerate(data):
    X[i] = d[0]

# In[16]:

# number of classes
num_classes = 3

# image dimensions
img_rows, img_cols = X.shape[1],  X.shape[2]

if K.image_dim_ordering() == 'th':
    X = X.reshape(X.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    X = X.reshape(X.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

# In[17]:

# model hyperparameters
# batch_size = 32
# nb_epoch = 30

# network architecture
patch_size_1 = 3
patch_size_2 = 3

depth_1 = 32
depth_2 = 32

pool_size = 2

num_hidden_1 = 64
num_hidden_2 = 64

# dropout = 0.5

# In[18]:

model = Sequential()

model.add(Convolution2D(depth_1, patch_size_1, patch_size_1,
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))

model.add(Convolution2D(depth_2, patch_size_2, patch_size_2, border_mode='valid'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))

model.add(Flatten())

model.add(Dense(num_hidden_1))
model.add(Activation('relu'))
# model.add(Dropout(dropout))

model.add(Dense(num_hidden_2))
model.add(Activation('relu'))
# model.add(Dropout(dropout))

model.add(Dense(num_classes))

model.add(Activation('softmax'))

# In[19]:

model.load_weights("-model.hdf5")

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])

# In[20]:

y = model.predict(X)
predictions = np.argmax(y,1)

predNames = [typesList[x] for x in predictions]

pred = max(set(predNames), key=predNames.count)
conf = '{:.2%}'.format(float(predNames.count(pred)) / len(predNames))

print "python: ", pred
print "python: ", conf


text:
/* jshint asi:true */

'use strict'

var test = require('assertit')
var hasBomString = require('./index')

test('should return true if a string has a bom', function (done) {
  test.strictEqual(hasBomString('\ufefffoo'), true)
  done()
})

test('should return false if not a string', function (done) {
  test.strictEqual(hasBomString(123), false)
  done()
})

test('should return false if a string does not have a bom', function (done) {
  test.strictEqual(hasBomString('foo'), false)
  done()
})

test('should return false if a buffer has a bom', function (done) {
  test.strictEqual(hasBomString(new Buffer('\ufefffoo')), false)
  done()
})

test('should return false if a buffer does not have a bom', function (done) {
  test.strictEqual(hasBomString(new Buffer('foo')), false)
  done()
})


text:
	YouTube URL: <input id="url"></input>

	autoplay: <input id="autoplay" type="checkbox"></input>

	no controls: <input id="controls" type="checkbox"></input>

	<button onclick="playVideo()">play video</button>

	Video id:


text:
export const getMatrixDataTypeDocs = {
  name: 'getMatrixDataType',
  category: 'Matrix',
  syntax: [
    'getMatrixDataType(x)'
  ],
  description: 'Find the data type of all elements in a matrix or array, ' +
  'for example "number" if all items are a number ' +
  'and "Complex" if all values are complex numbers. ' +
  'If a matrix contains more than one data type, it will return "mixed".',
  examples: [
    'getMatrixDataType([1, 2, 3])',
    'getMatrixDataType([[5 cm], [2 inch]])',
    'getMatrixDataType([1, "text"])',
    'getMatrixDataType([1, bignumber(4)])'
  ],
  seealso: ['matrix', 'sparse', 'typeOf']
}


text:
package org.capcaval.c3.componentmanager.tools;

import java.lang.reflect.Field;

public class UsedServicesDescription {
	protected Field field;
	public Field getField() {
		return field;
	}

	public Class<?> getImplementationType() {
		return implementationType;
	}

	protected Class<?> implementationType;

	public UsedServicesDescription(Field field, Class<?> implementationType) {
		this.field = field;
		this.implementationType = implementationType;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>io.cloudslang</groupId>
        <artifactId>runtime-management</artifactId>
        <version>0.3.35-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>runtime-management-api</artifactId>
</project>


text:
package cn.aposoft.tutorial.http.loop;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author LiuJian
 * @date 2017年5月10日
 *
 */
public class GoServerLoop {

    /**
     *
     *
     * @param args
     */
    public static void main(String[] args) {

        try (CloseableHttpClient httpClient = HttpClients.custom().setMaxConnPerRoute(200).setMaxConnTotal(200).build()) {
            HttpGet httpGet = new HttpGet("http://127.0.0.1");
            long begin = System.currentTimeMillis();
            for (int i = 0; i < /* 1000 **/5; i++) {
                System.out.println("begin:" + System.currentTimeMillis());
                try (CloseableHttpResponse resp = httpClient.execute(httpGet)) {
                    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        System.out.println(resp.getFirstHeader("Connection"));
                        EntityUtils.consumeQuietly(resp.getEntity());
                    }
                    System.out.println("complete:" + System.currentTimeMillis());
                    try {
                        TimeUnit.MILLISECONDS.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("awake:" + System.currentTimeMillis());
                }

            }
            long end = System.currentTimeMillis();

            System.out.println("Duration:" + (end - begin));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}


text:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> // for mkdir
#include <inttypes.h>
#include <stdint.h>
#include <algorithm> // for max/min
#include <vector> // for sorting_kmers
#include <sys/time.h>
#ifndef OSX
#include <sys/sysinfo.h> // to determine system memory
#endif
#include <sys/statvfs.h> // to determine available disk space
#include <dirent.h> // to clear the temp directory
#include <libgen.h> // for basename()
#include <string>

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

int max_memory; // the most memory dsk should alloc at any time, in MB
int max_disk_space; // the most disk space dsk should use at any time, in MB
extern bool output_histo;
#include "minia/Bank.h"
#include "minia/Pool.h"
#include "minia/Bloom.h"
#include "minia/Utils.h"
#include "minia/SortingCount.h"
#include "minia/Kmer.h"
#include "minia/loadKmers.h" // Added by Raunaq

int main(int argc, char *argv[])
{
    if(argc <  3)
    {
        fprintf (stderr,"%s: [d]isk [s]treaming of [k]-mers (constant-memory k-mer counting)\n",argv[0]);
        fprintf (stderr,"usage:\n");
        fprintf (stderr," %s input_file kmer_size [-t min_abundance] [-m max_memory] [-d max_disk_space] [-o out_prefix] [-histo]\n",argv[0]);
        fprintf (stderr,"details:\n [-t min_abundance] filters out k-mers seen ( < min_abundance ) times, default: 1 (all kmers are returned)\n [-m max_memory] is in MB, default: min(total system memory / 2, 5 GB) \n [-d max_disk_space] is in MB, default: min(available disk space / 2, reads file size)\n [-o out_prefix] saves results in [out_prefix].solid_kmers. default out_prefix = basename(input_file)\n [-histo] outputs histogram of kmers abundance\n [-rev] outputs only one of forward or reverse complement k-mers\n Input file can be fasta, fastq, gzipped or not, or a file containing a list of file names.\n");
#ifdef SVN_REV
fprintf(stderr,"Running dsk version %s\n",STR(SVN_REV));
#endif
        return 0;
    }

    // reads file
    Bank *Reads = new Bank(argv[1]);

    if (argv[2][0] == '-')
    {
        printf("please specify a k value\n");
        exit(1);
    }
	/* Changes by Raunaq
	 * Code addition for taking in multiple values of k. The file containing should have values of k sorted in decreasing order
	 *
	*/
	int *Kmerlist =  loadKmers(argv[2]);

    // kmer size
	//fprintf(stderr,"Smallest kmer is %d \n",smallestKmer);
    sizeKmer = Kmerlist[0];
    if (sizeKmer>(int)(sizeof(kmer_type)*4))
    {
        printf("Max kmer size on this compiled version is %lu\n",sizeof(kmer_type)*4);
        exit(1);
    }
    kmerMask=(((kmer_type)1)<<(sizeKmer*2))-1;

    // default solidity
    nks = 1;

    // default max memory
    max_memory = 5*1024;
    #ifndef OSX
    struct sysinfo info;
    sysinfo(&info);
    int total_ram = (int)(((double)info.totalram*(double)info.mem_unit)/1024/1024);
    printf("Total RAM: %d MB\n",total_ram);
#else
    int total_ram = 128*1024;
#endif

    // default prefix is the reads file basename
    char *reads_path=strdup(argv[1]);
    string reads_name(basename(reads_path)); // posix basename() may alter reads_path
    free(reads_path);
    int lastindex = reads_name.find_last_of(".");
    strcpy(prefix,reads_name.substr(0, lastindex).c_str());

    for (int n_a = 3; n_a < argc ; n_a++)
    {
        if (strcmp(argv[n_a],"-t")==0)
            nks = atoi(argv[n_a+1]);

        if (strcmp(argv[n_a],"-o")==0)
            strcpy(prefix,argv[n_a+1]);
    }

    int verbose = 0;
    bool reverse = false;
    max_disk_space = 0;

    output_histo =false;
    // parse the remaining arguments: these will override the default max memory / max disk
    for (int n_a = 3; n_a < argc ; n_a++)
    {
        if (strcmp(argv[n_a],"-m")==0)
            max_memory = atoi(argv[n_a+1]);

        if (strcmp(argv[n_a],"-d")==0)
            max_disk_space = atoi(argv[n_a+1]);

        if (strcmp(argv[n_a],"-v")==0)
            verbose = 1;

        if (strcmp(argv[n_a],"-vv")==0)
            verbose = 2;

        if (strcmp(argv[n_a],"-histo")==0)
            output_histo =true;

	if (strcmp(argv[n_a],"-rev")==0)
	    reverse = true;
    }

    if (max_memory > total_ram)
    {
        printf("Maximum memory (%d MB), exceeds total RAM (%d MB). Setting maximum memory to %d MB.\n",max_memory,total_ram,total_ram/2);
        max_memory = total_ram/2;
    }

    STARTWALL(0);

    sorting_count(Reads,prefix,max_memory,max_disk_space,true,verbose,reverse);

    STOPWALL(0,"Total");

    delete Reads;

    return 0;
}


text:
void ofApp::setup(){

	finder.setup("haarcascade_frontalface_default.xml");
    webcam.initGrabber( 1280 , 800 ) ;
    scaledSize = ofRectangle( 0 , 0 , webcam.getWidth() / 4 , webcam.getHeight() / 4 ) ;

    faceImage.loadImage( "face.png" ) ;
}

//--------------------------------------------------------------
void ofApp::update(){
    webcam.update() ;

    if ( webcam.isFrameNew() )
    {
        //comment out the above and use the following instead
        //We make a copy of the pixels from the webcam
        ofPixels pix ;
        pix.setFromPixels( webcam.getPixels() , webcam.getWidth() , webcam.getHeight() , 3 ) ;

        //resizing the pixels to a smaller array will improve performance
        pix.resize( scaledSize.getWidth() , scaledSize.getHeight() ) ;
        finder.findHaarObjects( pix ) ;

    }

}

//--------------------------------------------------------------
void ofApp::draw(){

    //Setting the color to white set images to draw at full color
    ofSetColor( ofColor::white ) ;
    webcam.draw( 0, 0 ) ;

    ofNoFill();

	for(unsigned int i = 0; i < finder.blobs.size(); i++)
    {
        //Use a stringstream object to generate a label
        stringstream label ;
        label << "face #" << i ;

        //Get the rectangle from the haarFinder
		ofRectangle cur = finder.blobs[i].boundingRect;

        //because we have a scaled image, we need to adjust the coordinate space of the haar finder rectangle
        float scaleToWebcam = webcam.getWidth() / scaledSize.getWidth() ;
        cur.scale( scaleToWebcam ) ;
        cur.x *= scaleToWebcam ;
        cur.y *= scaleToWebcam ;

        //Draw a face starting in the top left
        ofSetColor( ofColor::white ) ;
        faceImage.draw( cur.x , cur.y , cur.getWidth() , cur.getHeight() ) ;

    }

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


text:
package com.ehret.mixit.domain;

/**
 * Différents type de fichier pouvant être affichés à l'utilsiateur
 */
public enum TypeFile {
    speaker,
    staff,
    talks,
    test,
    workshops,
    members,
    lightningtalks,
    sponsor,
    favorites,
    interests;

    public static TypeFile getTypeFile(String value) {
        for (TypeFile typeFile : values()) {
            if (typeFile.name().equals(value)) {
                return typeFile;
            }
        }
        return null;
    }
}


text:
using System;
using Cassandra.Serialization;

namespace Cassandra
{
    public class DynamicCompositeTypeAdapter : ITypeAdapter
    {
        public Type GetDataType()
        {
            return typeof (byte[]);
        }

        public object ConvertFrom(byte[] decimalBuf)
        {
            return decimalBuf;
        }

        public byte[] ConvertTo(object value)
        {
            TypeSerializer.CheckArgument<byte[]>(value);
            return (byte[]) value;
        }
    }
}


text:
import React from 'react';
import { connect } from 'react-redux';
import callDirections from 'ringcentral-integration/enums/callDirections';
import RecentActivityPanel from '../../components/RecentActivityPanel';
import dynamicsFont from '../../assets/DynamicsFont/DynamicsFont.scss';
import RecentActivityMessages from '../../components/RecentActivityMessages';
import RecentActivityCalls from '../../components/RecentActivityCalls';
import VoicemailIcon from '../../assets/images/VoicemailIcon.svg';
import FaxIcon from '../../assets/images/Fax.svg';
import { withPhone } from '../../lib/phoneContext';
import i18n from './i18n';

function getTabs({
  ready,
  currentLocale,
  dateTimeFormatter,
  navigateTo,
  recentMessages,
  recentCalls,
  currentContact,
  sessionId,
  showRecentCalls,
  showRecentMessage,
  showFax,
  showVoiceMails,
}) {
  if (!ready) return [];
  let messages = [];
  let calls = [];
  if (currentContact && currentContact.id) {
    const contactId = currentContact.id;
    const activityCardId = sessionId ? `${contactId}-${sessionId}` : contactId;
    if (recentMessages.messages[activityCardId]) {
      messages = recentMessages.messages[activityCardId];
    }
    if (recentCalls.calls[activityCardId]) {
      calls = recentCalls.calls[activityCardId];
    }
  }

  return [
    showVoiceMails
      ? {
          icon: <VoicemailIcon width={21} height={21} />,
          label: i18n.getString('voicemail', currentLocale),
          path: 'voicemails',
          isActive: (path) => path === 'voicemails',
          view: null,
          getData() {},
          cleanUp() {},
        }
      : null,
    showRecentMessage
      ? {
          icon: ,
          label: i18n.getString('text', currentLocale),
          path: 'recentMessages',
          isActive: (path) => path === 'recentMessages',
          view: (
            <RecentActivityMessages
              messages={messages}
              navigateTo={navigateTo}
              dateTimeFormatter={dateTimeFormatter}
              currentLocale={currentLocale}
              isMessagesLoaded={recentMessages.isMessagesLoaded}
            />
          ),
          getData() {
            recentMessages.getMessages({ currentContact, sessionId });
          },
          cleanUp: () =>
            recentMessages.cleanUpMessages({
              contact: currentContact,
              sessionId,
            }),
        }
      : null,
    showFax
      ? {
          icon: <FaxIcon width={21} height={21} />,
          label: i18n.getString('fax', currentLocale),
          path: 'faxes',
          isActive: (path) => path === 'faxes',
          view: null,
          getData() {},
          cleanUp() {},
        }
      : null,
    showRecentCalls
      ? {
          icon: ,
          label: i18n.getString('call', currentLocale),
          path: 'recentCalls',
          isActive: (path) => path === 'recentCalls',
          view: (
            <RecentActivityCalls
              calls={calls}
              dateTimeFormatter={dateTimeFormatter}
              currentLocale={currentLocale}
              isCallsLoaded={recentCalls.isCallsLoaded}
            />
          ),
          getData() {
            recentCalls.getCalls({ currentContact, sessionId });
          },
          cleanUp: () =>
            recentCalls.cleanUpCalls({ contact: currentContact, sessionId }),
        }
      : null,
  ].filter((x) => x !== null);
}

function mapToProps(
  _,
  {
    phone: {
      locale,
      dateTimeFormat,
      recentMessages,
      recentCalls,
      contactMatcher,
    },
    currentLocale = locale.currentLocale,
    navigateTo,
    dateTimeFormatter = (...args) => dateTimeFormat.formatDateTime(...args),
    getSession,
    useContact,
    contact,
    showRecentCalls = true,
    showRecentMessage = true,
    showFax = true,
    showVoiceMails = true,
  },
) {
  let sessionId = null;
  let currentContact = contact;
  let ready =
    dateTimeFormat.ready &&
    locale.ready &&
    recentMessages.ready &&
    recentCalls.ready;
  if (!useContact) {
    const session = getSession();
    sessionId = session.id;
    currentContact = session.contactMatch;
    const contactMapping = contactMatcher && contactMatcher.dataMapping;
    const phoneNumber =
      session.direction === callDirections.outbound ? session.to : session.from;
    if (!currentContact) {
      currentContact = contactMapping && contactMapping[phoneNumber];
      if (currentContact && currentContact.length >= 1) {
        currentContact = currentContact[0];
      }
    }
    ready = ready && contactMatcher.ready;
  }
  return {
    currentLocale,
    title: i18n.getString('recentActivities', locale.currentLocale),
    showSpinner: !ready,
    currentContact,
    calls: recentCalls.calls || [],
    tabs: getTabs({
      ready,
      currentLocale,
      dateTimeFormatter,
      navigateTo,
      currentContact,
      recentMessages,
      recentCalls,
      sessionId,
      showFax,
      showRecentCalls,
      showVoiceMails,
      showRecentMessage,
    }),
    defaultTab: 'recentCalls',
  };
}

const RecentActivityContainer = withPhone(
  connect(mapToProps)(RecentActivityPanel),
);

export { getTabs, mapToProps, RecentActivityContainer as default };


text:
Employees

                First name
                Last name
                Email
                Account enabled

                {{employee.firstName}}
                {{employee.lastName}}
                {{employee.email}}
                {{employee.enabled}}

              <button type="submit" class="btn btn-success btn-lg" ng-click="vmAdmin.addEmployee()"
                      ng-disabled="vmAdmin.selectedEmployee && !vmAdmin.selectedEmployee.id">

              </button>
              <button class="btn btn-danger btn-lg" ng-click="vmAdmin.deleteEmployee(vmAdmin.selectedEmployee)">

              </button>

            <form id="houses-properties" name="vmAdmin.propertiesForm">

                 First name:
                <input type="text" class="form-control" placeholder="..." ng-model="vmAdmin.copiedSelectedEmployee.firstName"
                       required>

                 Last name:
                <input type="text" class="form-control" placeholder="..." ng-model="vmAdmin.copiedSelectedEmployee.lastName"
                       required>

                 Email:
                <input type="email" class="form-control" placeholder="..." ng-model="vmAdmin.copiedSelectedEmployee.email"
                       required>

                 Acc. enabled:
                <input type="checkbox" id="form-control-checkbox" class="form-control"  ng-model="vmAdmin.copiedSelectedEmployee.enabled"/>

                 Roles:
                <select multiple class="form-control" name="rolesMultiSelect"

                        ng-model="vmAdmin.copiedSelectedEmployee.roles">

                  <option ng-repeat="role in vmAdmin.roles" value="{{role.type | lowercase}}">{{role.type}}</option>
                </select>

                <button ng-show="vmAdmin.selectedEmployee.id" class="btn btn-default form-control"
                        ng-click="vmAdmin.updateEmployee(vmAdmin.copiedSelectedEmployee)"
                        ng-disabled="!vmAdmin.propertiesForm.$valid || !vmAdmin.propertiesForm.$dirty">Update
                </button>
                <button ng-show="!vmAdmin.selectedEmployee.id" class="btn btn-default form-control"
                        ng-click="vmAdmin.createEmployee(vmAdmin.copiedSelectedEmployee)"
                        ng-disabled="!vmAdmin.propertiesForm.$valid">Create
                </button>

            </form>


text:
package org.sf.cafebabe.theme;

import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;

/**
 * This class describes a theme using "khaki" colors.
 *
 * @version 1.4 04/23/99
 * @author Steve Wilson
 */
public class KhakiMetalTheme extends DefaultMetalTheme {

    public String getName() { return "Sandstone"; }

    private final ColorUIResource primary1 = new ColorUIResource( 87,  87,  47);
    private final ColorUIResource primary2 = new ColorUIResource(159, 151, 111);
    private final ColorUIResource primary3 = new ColorUIResource(199, 183, 143);

    private final ColorUIResource secondary1 = new ColorUIResource( 111,  111,  111);
    private final ColorUIResource secondary2 = new ColorUIResource(159, 159, 159);
    private final ColorUIResource secondary3 = new ColorUIResource(231, 215, 183);

    protected ColorUIResource getPrimary1() { return primary1; }
    protected ColorUIResource getPrimary2() { return primary2; }
    protected ColorUIResource getPrimary3() { return primary3; }

    protected ColorUIResource getSecondary1() { return secondary1; }
    protected ColorUIResource getSecondary2() { return secondary2; }
    protected ColorUIResource getSecondary3() { return secondary3; }

}


text:
package com.sksamuel.scrimage.nio

import java.io.{File, ByteArrayOutputStream}
import java.nio.file.{Paths, Files, Path}
import javax.imageio.metadata.IIOMetadataNode
import javax.imageio.stream.MemoryCacheImageOutputStream
import javax.imageio.{IIOImage, ImageIO, ImageTypeSpecifier}

import com.sksamuel.scrimage.Image

import scala.concurrent.duration._

/**
 * Baseed on work by Elliot Kroo on 2009-04-25 and adapted into Scala and rewritten.
 *
 * This work is licensed under the Creative Commons Attribution 3.0 Unported
 * License. To view a copy of this license, visit
 * http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
 Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
 */
case class GifSequenceWriter(frameDelay: Duration = 1.second, infiniteLoop: Boolean = true) {

  def withFrameDelay(delay: Duration): GifSequenceWriter = copy(frameDelay = delay)
  def withInfiniteLoop(infiniteLoop: Boolean): GifSequenceWriter = copy(infiniteLoop = infiniteLoop)

  /**
   * Returns an existing child node, or creates and returns a new child node (if
   * the requested node does not exist).
   *
   * @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
   * @param nodeName the name of the child node.
   *
   * @return the child node, if found or a new node created with the given name.
   */
  private def getNode(rootNode: IIOMetadataNode, nodeName: String): IIOMetadataNode = {
    val nodes = for ( i <- 0 until rootNode.getLength ) yield rootNode.item(i).asInstanceOf[IIOMetadataNode]
    nodes.find(_.getNodeName.equalsIgnoreCase(nodeName)).getOrElse {
      val node = new IIOMetadataNode(nodeName)
      rootNode.appendChild(node)
      node
    }
  }

  def output(images: Seq[Image], path: Path): Path = Files.write(path, bytes(images))
  def output(images: Seq[Image], file: File): Path = Files.write(file.toPath, bytes(images))
  def output(images: Seq[Image], path: String): Path = Files.write(Paths.get(path), bytes(images))

  def bytes(images: Seq[Image]): Array[Byte] = {

    import scala.collection.JavaConverters._

    val baos = new ByteArrayOutputStream()
    val output = new MemoryCacheImageOutputStream(baos)

    val writer = ImageIO.getImageWritersBySuffix("gif").asScala.next
    val imageWriteParam = writer.getDefaultWriteParam()

    val imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(images.head.awt.getType)
    val imageMetaData = writer.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam)

    val metaFormatName = imageMetaData.getNativeMetadataFormatName()

    val root = imageMetaData.getAsTree(metaFormatName).asInstanceOf[IIOMetadataNode]

    val graphicsControlExtensionNode = getNode(root, "GraphicControlExtension")

    graphicsControlExtensionNode.setAttribute("disposalMethod", "none")
    graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE")
    graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE")
    graphicsControlExtensionNode.setAttribute("delayTime", (frameDelay.toMillis / 10).toString)
    graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0")

    val commentsNode = getNode(root, "CommentExtensions")
    commentsNode.setAttribute("CommentExtension", "Created by Scrimage")

    val appEntensionsNode = getNode(root, "ApplicationExtensions")
    val child = new IIOMetadataNode("ApplicationExtension")

    child.setAttribute("applicationID", "NETSCAPE")
    child.setAttribute("authenticationCode", "2.0")

    val loop = if (infiniteLoop) 0 else 1
    child.setUserObject(Array[Byte](0x1, (loop & 0xFF).toByte, ((loop >> 8) & 0xFF).toByte))
    appEntensionsNode.appendChild(child)

    imageMetaData.setFromTree(metaFormatName, root)
    writer.setOutput(output)
    writer.prepareWriteSequence(null)

    for ( image <- images ) writer.writeToSequence(new IIOImage(image.awt, null, imageMetaData), imageWriteParam)
    writer.endWriteSequence()
    output.close()

    baos.toByteArray
  }
}


text:
package generator

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"

	"goa.design/goa/v3/codegen"
	"goa.design/goa/v3/eval"
	"golang.org/x/tools/go/packages"
)

// Generate runs the code generation algorithms.
func Generate(dir, cmd string) (outputs []string, err1 error) {
	// 1. Compute design roots.
	var roots []eval.Root
	{
		rs, err := eval.Context.Roots()
		if err != nil {
			return nil, err
		}
		roots = rs
	}

	// 2. Compute "gen" package import path.
	var genpkg string
	{
		base, err := filepath.Abs(dir)
		if err != nil {
			return nil, err
		}
		path := filepath.Join(base, codegen.Gendir)
		if err := os.MkdirAll(path, 0777); err != nil {
			return nil, err
		}

		// We create a temporary Go file to make sure the directory is a valid Go package
		dummy, err := ioutil.TempFile(path, "temp.*.go")
		if err != nil {
			return nil, err
		}
		defer func() {
			if err := os.Remove(dummy.Name()); err != nil {
				outputs = nil
				err1 = err
			}
		}()
		if _, err = dummy.Write([]byte("package gen")); err != nil {
			return nil, err
		}
		if err = dummy.Close(); err != nil {
			return nil, err
		}

		pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName}, path)
		if err != nil {
			return nil, err
		}
		genpkg = pkgs[0].PkgPath
	}

	// 3. Retrieve goa generators for given command.
	var genfuncs []Genfunc
	{
		gs, err := Generators(cmd)
		if err != nil {
			return nil, err
		}
		genfuncs = gs
	}

	// 4. Run the code pre generation plugins.
	err := codegen.RunPluginsPrepare(cmd, genpkg, roots)
	if err != nil {
		return nil, err
	}

	// 5. Generate initial set of files produced by goa code generators.
	var genfiles []*codegen.File
	for _, gen := range genfuncs {
		fs, err := gen(genpkg, roots)
		if err != nil {
			return nil, err
		}
		genfiles = append(genfiles, fs...)
	}

	// 6. Run the code generation plugins.
	genfiles, err = codegen.RunPlugins(cmd, genpkg, roots, genfiles)
	if err != nil {
		return nil, err
	}

	// 7. Write the files.
	written := make(map[string]struct{})
	for _, f := range genfiles {
		filename, err := f.Render(dir)
		if err != nil {
			return nil, err
		}
		if filename != "" {
			written[filename] = struct{}{}
		}
	}

	// 8. Compute all output filenames.
	{
		outputs = make([]string, len(written))
		cwd, err := os.Getwd()
		if err != nil {
			cwd = "."
		}
		i := 0
		for o := range written {
			rel, err := filepath.Rel(cwd, o)
			if err != nil {
				rel = o
			}
			outputs[i] = rel
			i++
		}
	}
	sort.Strings(outputs)

	return outputs, nil
}


text:
import * as React from 'react';
import { Responsive } from './utils';

interface AutocompleteData {
  [key: string]: string | null;
}

export interface AutocompleteOptions {
  data: AutocompleteData;
  limit?: number;
  onAutocomplete?: (value: string) => void;
  minLength?: number;
  sortFunction?: <T>(a: T, b: T, inputString: string) => number;
}

export interface AutocompleteProps extends Responsive {
  id?: string;
  className?: string;
  title?: string;
  icon?: React.ReactNode;
  placeholder?: string;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  value?: string;
  options: AutocompleteOptions;
}

/**
 * React Materialize: Autocomplete
 */
declare const Autocomplete: React.FC<AutocompleteProps>

export default Autocomplete;