text:
#include "tensorflow/core/framework/tensor_shape.h"

#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {
class TensorShapeTestHelper {
 public:
  static void set_data_type(TensorShape* s, DataType t) { s->set_data_type(t); }
  static uint8 data_type(const TensorShape* s) { return s->data_type(); }
};

namespace {

TEST(TensorShapeTest, Default) {
  // The default TensorShape constructor constructs a shape of 0-dim
  // and 1-element.
  TensorShape s;
  EXPECT_EQ(s.dims(), 0);
  EXPECT_EQ(s.num_elements(), 1);
}

TEST(TensorShapeTest, set_dim) {
  TensorShape s({10, 5});

  s.set_dim(0, 20);
  ASSERT_EQ(2, s.dims());
  EXPECT_EQ(20, s.dim_size(0));
  EXPECT_EQ(100, s.num_elements());

  s.set_dim(1, 2);
  ASSERT_EQ(2, s.dims());
  EXPECT_EQ(2, s.dim_size(1));
  EXPECT_EQ(40, s.num_elements());
}

TEST(TensorShapeTest, RemoveDim) {
  TensorShape s({10, 5});
  s.RemoveDim(0);
  EXPECT_EQ(5, s.num_elements());
  ASSERT_EQ(1, s.dims());
}

TEST(TensorShapeTest, RemoveAndAddDim) {
  TensorShape s({10, 5, 20});
  s.RemoveDim(1);
  s.AddDim(100);

  EXPECT_EQ(20000, s.num_elements());
  ASSERT_EQ(3, s.dims());
}

TEST(TensorShapeTest, RemoveLastDims) {
  TensorShape s({2, 3, 5, 7});
  s.RemoveLastDims(1);

  ASSERT_EQ(3, s.dims());
  EXPECT_EQ(30, s.num_elements());

  s.RemoveLastDims(2);
  ASSERT_EQ(1, s.dims());
  EXPECT_EQ(2, s.dim_size(0));
}

TEST(TensorShapeTest, RemoveDimRange) {
  TensorShape s0({2, 3, 5, 7});
  // Empty interval => noop.
  for (int i = -4; i <= 4; ++i) {
    s0.RemoveDimRange(i, i);
    ASSERT_EQ(4, s0.dims());
    ASSERT_EQ(210, s0.num_elements());
  }

  // Positive begin and end.
  s0.RemoveDimRange(3, 1);  // Empty interval.
  ASSERT_EQ(4, s0.dims());
  ASSERT_EQ(210, s0.num_elements());
  s0.RemoveDimRange(0, 3);
  ASSERT_EQ(1, s0.dims());
  EXPECT_EQ(7, s0.dim_size(0));
  TensorShape s1({2, 3, 5, 7});
  s1.RemoveDimRange(2, 3);
  ASSERT_EQ(3, s1.dims());
  ASSERT_EQ(42, s1.num_elements());

  // Negative begin or end.
  TensorShape s2({2, 3, 5, 7});
  s2.RemoveDimRange(-2, -3);  // Empty interval.
  ASSERT_EQ(4, s2.dims());
  ASSERT_EQ(210, s2.num_elements());
  s2.RemoveDimRange(0, -2);
  ASSERT_EQ(1, s2.dims());
  ASSERT_EQ(7, s2.dim_size(0));
  TensorShape s3({2, 3, 5, 7});
  s3.RemoveDimRange(-3, -2);
  ASSERT_EQ(3, s3.dims());
  ASSERT_EQ(42, s3.num_elements());
}

TEST(TensorShapeTest, InvalidShapeProto) {
  TensorShapeProto proto;
  EXPECT_TRUE(TensorShape::IsValid(proto));

  proto.add_dim()->set_size(357);
  proto.add_dim()->set_size(982);
  EXPECT_TRUE(TensorShape::IsValid(proto));

  proto.Clear();
  proto.add_dim()->set_size(-357);
  proto.add_dim()->set_size(-982);
  EXPECT_FALSE(TensorShape::IsValid(proto));

  proto.Clear();
  proto.add_dim()->set_size(1LL << 35);
  proto.add_dim()->set_size((1LL << 35) + 1);
  EXPECT_FALSE(TensorShape::IsValid(proto));
}

TEST(TensorShapeTest, TooManyDimsProto) {
  TensorShapeProto proto;
  // Deliberate redundancy to ensure that both paths work.
  EXPECT_TRUE(TensorShape::IsValid(proto));
  TF_EXPECT_OK(TensorShape::IsValidShape(proto));
  for (int i = 0; i < TensorShape::MaxDimensions(); i++) {
    proto.add_dim()->set_size(1);
  }
  EXPECT_TRUE(TensorShape::IsValid(proto));
  TF_EXPECT_OK(TensorShape::IsValidShape(proto));
  proto.add_dim()->set_size(1);
  EXPECT_FALSE(TensorShape::IsValid(proto));
  EXPECT_FALSE(TensorShape::IsValidShape(proto).ok());
}

TEST(TensorShapeTest, SetDimForEmptyTensor) {
  TensorShape s({10, 5, 20});
  EXPECT_EQ(1000, s.num_elements());
  s.set_dim(1, 0);
  EXPECT_EQ(0, s.num_elements());
  s.set_dim(1, 7);
  EXPECT_EQ(1400, s.num_elements());
}

TEST(TensorShapeTest, AppendShape64BitIndices) {
  TensorShape s({10, 2147483648});

  EXPECT_EQ(10, s.dim_size(0));
  EXPECT_EQ(2147483648, s.dim_size(1));

  TensorShape s2;
  s2.AppendShape(s);
  EXPECT_EQ(10, s2.dim_size(0));
  EXPECT_EQ(2147483648, s2.dim_size(1));
}

TEST(TensorShapeTest, DataType) {
  TensorShape s({});
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_INVALID);
  TensorShapeTestHelper::set_data_type(&s, DT_INT32);
  s.AddDim(1);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_INT32);
  s.AddDim(100000);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_INT32);
  TensorShapeTestHelper::set_data_type(&s, DT_UINT16_REF);
  s.AddDim(2);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_UINT16_REF);
  s.AddDim(4);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_UINT16_REF);
  s.AddDim(3);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s), DT_UINT16_REF);

  TensorShape s2 = s;
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s2), DT_UINT16_REF);
  s2.RemoveDim(2);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s2), DT_UINT16_REF);
  TensorShapeTestHelper::set_data_type(&s2, DT_FLOAT);
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s2), DT_FLOAT);
  s2.Clear();
  EXPECT_EQ(TensorShapeTestHelper::data_type(&s2), DT_INVALID);
}

// -----------------------------------------------------------------------
// An old implementation of TensorShape using a different representation,
// preserved here in the unittest to allow us to have a randomized unittest
// that makes sure the behavior of TensorShape and TensorShapeOld are
// the same.
class TensorShapeIterOld;  // Declared below

/// Manages the dimensions of a Tensor and their sizes.
class TensorShapeOld {
 public:
  /// \brief Construct a `TensorShape` from the provided sizes.
  /// REQUIRES: `dim_sizes[i] >= 0`
  explicit TensorShapeOld(gtl::ArraySlice<int64> dim_sizes);
  TensorShapeOld(std::initializer_list<int64> dim_sizes)
      : TensorShapeOld(gtl::ArraySlice<int64>(dim_sizes)) {}

  /// REQUIRES: `IsValid(proto)`
  explicit TensorShapeOld(const TensorShapeProto& proto);

  /// Create a tensor shape with no dimensions and one element, which you can
  /// then call `AddDim()` on.
  TensorShapeOld();

  /// Returns `true` iff `proto` is a valid tensor shape.
  static bool IsValid(const TensorShapeProto& proto);

  /// Returns `OK` iff `proto` is a valid tensor shape, and a descriptive error
  /// status otherwise.
  static Status IsValidShape(const TensorShapeProto& proto);

  /// Clear a tensor shape
  void Clear();

  /// \brief Add a dimension to the end ("inner-most").
  /// REQUIRES: `size >= 0`
  void AddDim(int64 size);

  /// Appends all the dimensions from `shape`.
  void AppendShape(const TensorShapeOld& shape);

  /// \brief Insert a dimension somewhere in the `TensorShape`.
  /// REQUIRES: `0 <= d <= dims()`
  /// REQUIRES: `size >= 0`
  void InsertDim(int d, int64 size);

  /// \brief Modifies the size of the dimension `d` to be `size`
  /// REQUIRES: `0 <= d < dims()`
  /// REQUIRES: `size >= 0`
  void set_dim(int d, int64 size);

  /// \brief Removes dimension `d` from the `TensorShape`.
  /// REQUIRES: `0 <= d < dims()`
  void RemoveDim(int d);

  /// Return the number of dimensions in the tensor.
  int dims() const { return dim_sizes_.size(); }

  /// \brief Returns the number of elements in dimension `d`.
  /// REQUIRES: `0 <= d < dims()`
  // TODO(touts): Rename to `dimension()` to match
  // `Eigen::Tensor::dimension()`?
  int64 dim_size(int d) const {
    DCHECK_GE(d, 0);
    DCHECK_LT(d, dims());
    return dim_sizes_[d];
  }

  /// Returns sizes of all dimensions.
  gtl::ArraySlice<int64> dim_sizes() const { return dim_sizes_; }

  /// \brief Returns the number of elements in the tensor.
  ///
  /// We use `int64` and not `size_t` to be compatible with `Eigen::Tensor`
  /// which uses `ptrdiff_t`.
  int64 num_elements() const { return num_elements_; }

  /// Returns true if `*this` and `b` have the same sizes. Ignores
  /// dimension names.
  bool IsSameSize(const TensorShapeOld& b) const;
  bool operator==(const TensorShapeOld& b) const { return IsSameSize(b); }

  /// Fill `*proto` from `*this`.
  void AsProto(TensorShapeProto* proto) const;

  /// Fill `*dsizes` from `*this`.
  template <int NDIMS>
  Eigen::DSizes<Eigen::DenseIndex, NDIMS> AsEigenDSizes() const;

  /// Same as `AsEigenDSizes()` but allows for `NDIMS > dims()` -- in
  /// which case we pad the rest of the sizes with 1.
  template <int NDIMS>
  Eigen::DSizes<Eigen::DenseIndex, NDIMS> AsEigenDSizesWithPadding() const;

  /// For iterating through the dimensions.
  TensorShapeIterOld begin() const;
  TensorShapeIterOld end() const;

  /// For error messages.
  string DebugString() const;

  /// Same as `TensorShape(proto).DebugString()` but doesn't crash for
  /// invalid protos.
  static string DebugString(const TensorShapeProto& proto);

 private:
  // Recalculates the dimensions of this tensor after they are modified.
  void recompute_dims();

  // TODO(josh11b): Maybe use something from the Eigen Tensor library
  // for the sizes.
  gtl::InlinedVector<int64, 4> dim_sizes_;

  // total number of elements (avoids recomputing it each time).
  int64 num_elements_;
};

struct TensorShapeDimOld {
  explicit TensorShapeDimOld(int64 s) : size(s) {}
  int64 size;
};

class TensorShapeIterOld {
 public:
  TensorShapeIterOld(const TensorShapeOld* shape, int d)
      : shape_(shape), d_(d) {}
  bool operator==(const TensorShapeIterOld& rhs) {
    DCHECK(shape_ == rhs.shape_);
    return d_ == rhs.d_;
  }
  bool operator!=(const TensorShapeIterOld& rhs) {
    DCHECK(shape_ == rhs.shape_);
    return d_ != rhs.d_;
  }
  void operator++() { ++d_; }
  TensorShapeDimOld operator*() {
    return TensorShapeDimOld(shape_->dim_size(d_));
  }

 private:
  const TensorShapeOld* shape_;
  int d_;
};

// An upper limit of the total number of elements in a tensor.
static const int64 kMaxElements = (1LL << 40);

bool TensorShapeOld::IsValid(const TensorShapeProto& proto) {
  int64 num_elements = 1;
  for (const auto& d : proto.dim()) {
    if (d.size() < 0) return false;
    num_elements *= d.size();
    if (num_elements > kMaxElements) return false;
  }
  return true;
}

Status TensorShapeOld::IsValidShape(const TensorShapeProto& proto) {
  int64 num_elements = 1;
  for (const auto& d : proto.dim()) {
    if (d.size() < 0) {
      return errors::InvalidArgument("Shape ", DebugString(proto),
                                     " has negative dimensions; ",
                                     "perhaps an un-fed placeholder?");
    }
    num_elements *= d.size();
    if (num_elements > kMaxElements) {
      return errors::InvalidArgument("Shape ", DebugString(proto),
                                     " is too large (more than ", kMaxElements,
                                     " entries)");
    }
  }
  return Status::OK();
}

TensorShapeOld::TensorShapeOld(const TensorShapeProto& proto) {
  dim_sizes_.reserve(proto.dim_size());
  num_elements_ = 1;
  for (const auto& d : proto.dim()) {
    AddDim(d.size());
  }
}

TensorShapeOld::TensorShapeOld(gtl::ArraySlice<int64> dim_sizes) {
  dim_sizes_.reserve(dim_sizes.size());
  num_elements_ = 1;
  for (auto s : dim_sizes) {
    AddDim(s);
  }
}

TensorShapeOld::TensorShapeOld() : num_elements_(1) {}

void TensorShapeOld::Clear() {
  dim_sizes_.clear();
  num_elements_ = 1;
}

void TensorShapeOld::AddDim(int64 size) {
  CHECK_GE(size, 0);
  dim_sizes_.push_back(size);
  num_elements_ *= size;
  CHECK_LE(0, num_elements_);
  CHECK_LE(num_elements_, kMaxElements);
}

void TensorShapeOld::AppendShape(const TensorShapeOld& shape) {
  for (auto d : shape) AddDim(d.size);
}

void TensorShapeOld::InsertDim(int d, int64 size) {
  CHECK_GE(d, 0);
  CHECK_LE(d, dims());
  CHECK_GE(size, 0);
  dim_sizes_.insert(dim_sizes_.begin() + d, size);
  num_elements_ *= size;
  CHECK_LE(0, num_elements_);
  CHECK_LE(num_elements_, kMaxElements);
}

void TensorShapeOld::set_dim(int d, int64 size) {
  CHECK_GE(d, 0);
  CHECK_LT(d, dims());
  CHECK_GE(size, 0);

  // Update the number of elements. num_elements_ is int64.
  dim_sizes_[d] = size;
  recompute_dims();
}

void TensorShapeOld::RemoveDim(int d) {
  CHECK_GE(d, 0);
  CHECK_LT(d, dims());

  // Update the number of elements and remove the dimension from the
  // sizes.
  dim_sizes_.erase(dim_sizes_.begin() + d);
  recompute_dims();
}

void TensorShapeOld::recompute_dims() {
  num_elements_ = 1;
  for (auto s : dim_sizes_) {
    num_elements_ *= s;
    CHECK_LE(0, num_elements_);
    CHECK_LE(num_elements_, kMaxElements);
  }
}

bool TensorShapeOld::IsSameSize(const TensorShapeOld& b) const {
  if (b.dims() != dims()) return false;
  for (int d = 0; d < dims(); d++) {
    if (dim_size(d) != b.dim_size(d)) return false;
  }
  return true;
}

void TensorShapeOld::AsProto(TensorShapeProto* proto) const {
  proto->Clear();
  for (size_t d = 0; d < dim_sizes_.size(); ++d) {
    auto* dim = proto->add_dim();
    dim->set_size(dim_sizes_[d]);
  }
}

TensorShapeIterOld TensorShapeOld::begin() const {
  return TensorShapeIterOld(this, 0);
}

TensorShapeIterOld TensorShapeOld::end() const {
  return TensorShapeIterOld(this, dims());
}

string TensorShapeOld::DebugString() const {
  return strings::StrCat(
      "[", str_util::Join(gtl::ArraySlice<int64>(dim_sizes_), ","), "]");
}

string TensorShapeOld::DebugString(const TensorShapeProto& proto) {
  string s = "[";
  bool first = true;
  for (const auto& d : proto.dim()) {
    strings::StrAppend(&s, first ? "" : ",", d.size());
    first = false;
  }
  strings::StrAppend(&s, "]");
  return s;
}
// End of old implementation
// ------------------------------------------------------------------------

static int64 SkewedSize(random::SimplePhilox* gen, int64 current_elements) {
  int64 result = 0;
  do {
    if (current_elements < 100) {
      result = gen->Uniform(100000);
    } else {
      result = gen->Uniform(2);
    }
  } while ((result * current_elements >= 1LL << 34) ||
           (result * current_elements < 0));
  return result;
}

TEST(TensorShapeTest, Randomized) {
  // We do a randomized test to verify that the behavior of the
  // TensorShape implementation (which changes representations depending
  // on the values) is identical to our older, more straightforward (but
  // more memory hungry) implementation (TensorShapeOld).
  random::PhiloxRandom philox(7, 7);
  random::SimplePhilox gen(&philox);
  TensorShape s;
  TensorShapeOld sold;
  TensorShapeProto sp;
  TensorShapeProto spold;
  LOG(INFO) << "Sizes: " << sizeof(TensorShape) << " vs "
            << sizeof(TensorShapeOld);
  for (int i = 0; i < 100000; i++) {
    s.AsProto(&sp);
    sold.AsProto(&spold);
    EXPECT_EQ(sp.DebugString(), spold.DebugString());
    if ((i % 1000) == 0) {
      fprintf(stderr, "ITERATION %d: %s\n", i, sp.DebugString().c_str());
    }
    EXPECT_EQ(s.num_elements(), sold.num_elements());

    // Test moves.
    TensorShape copy = s;
    TensorShape moved(std::move(copy));
    EXPECT_EQ(s, moved);
    copy = s;
    moved = std::move(copy);
    EXPECT_EQ(s, moved);

    int64 ne = sold.num_elements();
    int r = gen.Uniform(100);
    if (r < 10) {
      int64 sz = SkewedSize(&gen, sold.num_elements());
      s.AddDim(sz);
      sold.AddDim(sz);
    } else if (r < 15) {
      s.Clear();
      sold.Clear();
    } else if (r < 35 && s.dims() > 0 && ne > 0 && ne < 100000000) {
      int dim = gen.Uniform(s.dims());
      s.RemoveDim(dim);
      sold.RemoveDim(dim);
    } else if (r < 50 && ne > 0 && ne < 100000000) {
      int dim = gen.Uniform(s.dims() + 1);
      int64 sz = SkewedSize(&gen, sold.num_elements());
      s.InsertDim(dim, sz);
      sold.InsertDim(dim, sz);
    } else {
      std::vector<int64> sizes;
      const int N = (gen.Uniform(4) == 0) ? gen.Uniform(10) : gen.Uniform(3);
      int64 num_elements = 1;
      for (int i = 0; i < N; i++) {
        int64 sz = SkewedSize(&gen, num_elements);
        sizes.push_back(sz);
        num_elements *= std::max<int64>(1, sz);
      }

      s = TensorShape(sizes);
      sold = TensorShapeOld(sizes);
    }
  }
}

TEST(TensorShapeTest, Large) {
  // We used to cap shapes at 2**40 elements.  Ensure the
  // bound is now higher.
  int64 one = 1;
  int64 max = std::numeric_limits<int64>::max();
  EXPECT_EQ(TensorShape({max}).num_elements(), max);
  EXPECT_EQ(TensorShape({1, max}).num_elements(), max);
  EXPECT_EQ(TensorShape({max, 1}).num_elements(), max);
  EXPECT_EQ(TensorShape({one << 62}).num_elements(), one << 62);
  EXPECT_EQ(TensorShape({one << 20, one << 41}).num_elements(), one << 61);
  EXPECT_EQ(TensorShape({1000, 1000, 1000, 1000, 1000, 1000}).num_elements(),
            1e18);
}

TEST(TensorShapeTest, Overflow) {
  int64 one = 1;
  std::vector<std::vector<int64>> overflows = {
      {1 << 30, 1 << 30, 1 << 30},
      {1 << 5, (one << 60) + 1},
  };
  for (const auto& overflow : overflows) {
    TensorShapeProto proto;
    for (auto dim : overflow) {
      proto.add_dim()->set_size(dim);
    }
    EXPECT_EQ(tensorflow::error::INVALID_ARGUMENT,
              TensorShape::IsValidShape(proto).code());
    TensorShape shape;
    EXPECT_EQ(tensorflow::error::INVALID_ARGUMENT,
              TensorShapeUtils::MakeShape(overflow, &shape).code());
  }
}

TEST(TensorShapeTest, UnknownRank) {
  // NOTE(irving): Unfortunately, for historical reasons we have to allow an
  // TensorShapeProto with unknown_rank() set to be parsed as a TensorShape.
  // Would be nice to tighten this, but it's tricky given backwards
  // compatibility requirements.
  TensorShapeProto proto;
  proto.set_unknown_rank(true);
  EXPECT_TRUE(TensorShape::IsValid(proto));
  TF_EXPECT_OK(TensorShape::IsValidShape(proto));
  EXPECT_EQ(TensorShape(), TensorShape(proto));

  proto.add_dim()->set_size(7);
  EXPECT_TRUE(TensorShape::IsValid(proto));
  TF_EXPECT_OK(TensorShape::IsValidShape(proto));
  EXPECT_EQ(TensorShape({7}), TensorShape(proto));
}

TEST(TensorShapeUtilsTest, StartsWith) {
  EXPECT_TRUE(TensorShapeUtils::StartsWith(TensorShape({}), TensorShape({})));
  EXPECT_TRUE(
      TensorShapeUtils::StartsWith(TensorShape({2, 3}), TensorShape({})));
  EXPECT_TRUE(
      TensorShapeUtils::StartsWith(TensorShape({2, 3}), TensorShape({2})));
  EXPECT_TRUE(
      TensorShapeUtils::StartsWith(TensorShape({2, 3}), TensorShape({2, 3})));
  EXPECT_TRUE(TensorShapeUtils::StartsWith(TensorShape({2, 3, 4}),
                                           TensorShape({2, 3})));
  EXPECT_FALSE(
      TensorShapeUtils::StartsWith(TensorShape({2, 3}), TensorShape({3})));
  EXPECT_FALSE(
      TensorShapeUtils::StartsWith(TensorShape({2, 3}), TensorShape({2, 4})));
  EXPECT_FALSE(TensorShapeUtils::StartsWith(TensorShape({2, 3}),
                                            TensorShape({2, 3, 4})));
  EXPECT_FALSE(TensorShapeUtils::StartsWith(TensorShape({2, 3, 4}),
                                            TensorShape({3, 4})));
}

TEST(TensorShapeUtilsTest, EndsWith) {
  EXPECT_TRUE(TensorShapeUtils::EndsWith(TensorShape({}), TensorShape({})));
  EXPECT_TRUE(TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({})));
  EXPECT_TRUE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({3})));
  EXPECT_TRUE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({2, 3})));
  EXPECT_TRUE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3, 4}), TensorShape({3, 4})));
  EXPECT_FALSE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({2})));
  EXPECT_FALSE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({2, 4})));
  EXPECT_FALSE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3}), TensorShape({2, 3, 4})));
  EXPECT_FALSE(
      TensorShapeUtils::EndsWith(TensorShape({2, 3, 4}), TensorShape({2, 3})));
}

// A few different test cases for tensor sizes for benchmarks
static std::vector<int64> MakeSizes(int arg) {
  std::vector<int64> sizes;
  switch (arg) {
    case 0:
      sizes = {100};
      break;
    case 1:
      sizes = {100, 1000};
      break;
    case 2:
      sizes = {100, 1000000};
      break;
    case 3:
      sizes = {100, 256, 192, 3};
      break;
    case 4:
      sizes = {1, 2, 1ll << 34, 1, 1, 1};
      break;
  }
  return sizes;
}

static void BM_TensorShape_Assign(int iters, int arg) {
  TensorShape s(MakeSizes(arg));
  while (--iters > 0) {
    TensorShape s2 = s;
  }
}
BENCHMARK(BM_TensorShape_Assign)->Arg(0)->Arg(1)->Arg(2)->Arg(3)->Arg(4);

}  // namespace
}  // namespace tensorflow


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. Bot. Fr. IV 15: 17 (1915)

#### Original name
Charcotia rufidula Hue

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package ldap

import (
	"fmt"

	"gopkg.in/asn1-ber.v1"
)

func init() {
	ControlTypeMap[ControlTypeContentSync] = "Content Sync"
}

func NewControlContentSync(mode uint64, reloadHint bool, cookie []byte) *ControlContentSync {
	return &ControlContentSync{
		Criticality: true,
		Mode:        mode,
		Cookie:      cookie,
		ReloadHint:  reloadHint,
	}
}

type ControlContentSync struct {
	Criticality bool
	Mode        uint64
	Cookie      []byte
	ReloadHint  bool
}

func (c *ControlContentSync) GetControlType() string {
	return ControlTypeContentSync
}

func (c *ControlContentSync) Encode() *ber.Packet {
	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeContentSync, "Control Type ("+ControlTypeMap[ControlTypeContentSync]+")"))

	p2 := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Control Value (Content Sync)")
	seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Content Sync Control Value")

	seq.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, uint64(c.Mode), "Mode"))

	cookie := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Cookie")
	cookie.Value = c.Cookie
	cookie.Data.Write(c.Cookie)
	seq.AppendChild(cookie)

	seq.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.ReloadHint, "ReloadHint"))

	p2.AppendChild(seq)

	if c.Criticality {
		packet.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.Criticality, "Criticality"))
	}
	packet.AppendChild(p2)
	return packet
}

func (c *ControlContentSync) String() string {
	return fmt.Sprintf(
		"Control Type: %s (%q) Criticality:%v Mode:%v ReloadHint:%v Cookie:%s",
		ControlTypeMap[ControlTypeContentSync],
		ControlTypeContentSync,
		c.Criticality,
		c.Mode,
		c.ReloadHint,
		c.Cookie)
}

func (c *ControlContentSync) SetCookie(cookie []byte) {
	c.Cookie = cookie
}


text:
package kit.scyla.canvas.touch;

import android.graphics.Point;
import android.os.Handler;

import java.util.ArrayList;
import java.util.Calendar;

import kit.scyla.core.shapes.Shape;

/**
 * Created with IntelliJ
 * Created by Nelaupe Lucas
 * Date 04/01/15
 */
@SuppressWarnings({"unused", "unchecked"})
public abstract class TouchGestureEvent implements IGestureEvent {

    private final Handler handler = new Handler();
    private final ArrayList<Shape> touchedShape;
    private Shape shapeMoving;
    private Point PointFinger;
    private final Runnable mLongPressed = new Runnable() {
        public void run() {
            if (shapeMoving != null) {
                onLongPressEvent(shapeMoving, PointFinger);
            }
        }
    };
    private long lastTap = Calendar.getInstance().getTimeInMillis();

    public TouchGestureEvent() {
        touchedShape = new ArrayList<>();
    }

    public void addElement(Shape shape) {
        touchedShape.add(shape);
    }

    public void removeElement(Shape shape) {
        touchedShape.remove(shape);
    }

    public void clear() {
        touchedShape.clear();
    }

    public void onTouchEvent(android.view.MotionEvent event) {
        PointFinger = new Point((int) event.getX(), (int) event.getY());

        switch (event.getAction()) {
            case android.view.MotionEvent.ACTION_DOWN:

                long now = Calendar.getInstance().getTimeInMillis();

                Shape currentShapeMoving = findClosestElement();

                int minDurationBetweenDoubleTap = 500;
                if (now - lastTap < minDurationBetweenDoubleTap && shapeMoving != null && currentShapeMoving != null && currentShapeMoving.equals(shapeMoving)) {
                    onDoubleTapEvent(shapeMoving, PointFinger);
                    break;
                } else {
                    shapeMoving = currentShapeMoving;
                    int minDurationLongPress = 200;
                    handler.postDelayed(mLongPressed, minDurationLongPress);
                    lastTap = Calendar.getInstance().getTimeInMillis();
                }
                break;
            case android.view.MotionEvent.ACTION_MOVE:
                handler.removeCallbacks(mLongPressed);
                if (shapeMoving != null) {
                    onMovingEvent(shapeMoving, PointFinger);
                }
                break;
            case android.view.MotionEvent.ACTION_UP:
                handler.removeCallbacks(mLongPressed);
                if (shapeMoving != null) {
                    onTouchEvent(shapeMoving, PointFinger);
                    onRaiseEvent(shapeMoving, PointFinger);
                }
                break;
        }

    }

    private Shape findClosestElement() {
        Shape res = null;

        for (Shape element : touchedShape) {
            if (element.collisionFacet() == null) {
                throw new IllegalStateException("A shape that can be touch cannot be a phantom element");
            } else {
                if (element.collisionFacet().fingerOn(PointFinger.x, PointFinger.y)) {
                    res = element;
                    break;

                }
            }
        }

        return res;
    }
}


text:
package at.ac.tuwien.infosys.aggr.elastic;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import at.ac.tuwien.infosys.aggr.node.AggregatorNode;
import at.ac.tuwien.infosys.aggr.node.Gateway;
import at.ac.tuwien.infosys.aggr.node.Registry;
import at.ac.tuwien.infosys.aggr.strategy.Topology;

public class ElasticityState {

	private int numNodes;
	private int numActiveNodes;

	public static ElasticityState getState() {
		ElasticityState state = new ElasticityState();
		try {
			Set<AggregatorNode> activeNodes = new HashSet<AggregatorNode>();
			List<AggregatorNode> nodes = Registry.getRegistryProxy().getAggregatorNodes();
			List<Topology> topos = Gateway.getGatewayProxy(
					Gateway.REGISTRY_FEATURE_GATEWAY).collectAllTopologies();
			for(AggregatorNode node : nodes) {
				for(Topology topo : topos) {
					if(topo.getAllAggregators().contains(node)) {
						activeNodes.add(node);
						break;
					}
				}
			}
			System.out.println("nodes: " + nodes);
			System.out.println("active: " + activeNodes);
			state.numNodes = nodes.size();
			state.numActiveNodes = activeNodes.size();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return state;
	}

	@Override
	public String toString() {
		return "[state nodes=" + numNodes + ",active=" + numActiveNodes + "]";
	}

	public int getNumNodes() {
		return numNodes;
	}
	public void setNumNodes(int numNodes) {
		this.numNodes = numNodes;
	}
	public int getNumActiveNodes() {
		return numActiveNodes;
	}
	public void setNumActiveNodes(int numActiveNodes) {
		this.numActiveNodes = numActiveNodes;
	}
}


text:
layout: post
published: true
title: "What happened to LEGO?"
permalink: /2013/02/09/what-happened-to-lego/
link: http://therealityprose.wordpress.com/2013/01/17/what_happened_with_lego/
---

So LEGO is expensive to adults because it was free when we were kids. Damn.


text:
import { getConfiguredCache } from 'money-clip'

const bundleCache = getConfiguredCache({
  name: 'bundle-cache',
  version: 1,
  maxAge: Infinity
})

export default bundleCache


text:
package com.ibm.wala.ssa;

import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;

/**
 * A store from a pointer.
 *
 * *p = v
 */
public class SSAStoreIndirectInstruction extends SSAInstruction {

  private final int addressVal;

  private final int rval;

  private final TypeReference pointeeType;

  /**
   * @param addressVal the value number holding the pointer p deferenced (*p)
   * @param rval the value number which is stored into the pointer location
   */
  public SSAStoreIndirectInstruction(int iindex, int addressVal, int rval, TypeReference pointeeType) {
    super(iindex);
    this.addressVal = addressVal;
    this.rval = rval;
    this.pointeeType = pointeeType;
  }

  public TypeReference getPointeeType() {
    return pointeeType;
  }

  @Override
  public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
    Assertions.UNREACHABLE("unimplemented");
    return null;
  }

  @Override
  public int hashCode() {
    return addressVal * 353456 * rval;
  }

  @Override
  public boolean isFallThrough() {
    return true;
  }

  @Override
  public String toString(SymbolTable symbolTable) {
    return "*" + getValueString(symbolTable, addressVal) + " = " + getValueString(symbolTable, rval);
  }

  @Override
  public void visit(IVisitor v) {
    ((IVisitorWithAddresses)v).visitStoreIndirect(this);
  }

}


text:
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.db import models

class PublishedPressReleaseManager(models.Manager):
    def get_queryset(self):
        return super(PublishedPressReleaseManager, self).get_queryset().filter(
            release_date__lt=timezone.now())

class PressRelease(models.Model):
    objects = models.Manager()
    published_objects = PublishedPressReleaseManager()

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    release_date = models.DateTimeField()

    def get_absolute_url(self):
        return reverse('press-release', kwargs={'slug': self.slug})

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('-release_date',)

class PublishedPressMentionMananger(models.Manager):
    def get_queryset(self):
        return super(PublishedPressMentionMananger, self).get_queryset(). \
            filter(published=True)

class PressMention(models.Model):
    objects = models.Manager()
    published_objects = PublishedPressMentionMananger()

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    publisher = models.CharField(max_length=60)
    publication_date = models.DateField()
    url = models.URLField()
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    author = models.CharField(max_length=100)
    notes = models.TextField()
    published = models.BooleanField()

    # TODO: add a projects FK.

    def get_absolute_url(self):
        return reverse('press-mention', kwargs={'slug': self.slug})

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('-publication_date',)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2012 FuseSource
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<features name="horo-features-1.0-SNAPSHOT">

    <feature name="horo-model" version="1.0-SNAPSHOT">
        <bundle>mvn:com.fusesource.examples/horo-model/1.0-SNAPSHOT</bundle>
        <bundle>mvn:joda-time/joda-time/${joda.time.version}</bundle>
        <bundle>mvn:commons-lang/commons-lang/${commons.lang.version}</bundle>
    </feature>

    <feature name="horo-db" version="1.0-SNAPSHOT">
        <feature version="1.0-SNAPSHOT">horo-model</feature>
        <feature version="${camel.version}">camel.mybatis</feature>
        <bundle>wrap:mvn:postgresql/postgresql/${postgresql.version}</bundle>
        <!--
        <bundle>wrap:mvn:commons-dbcp/commons-dbcp/${commons-dbcp-version}</bundle>
        -->
        <bundle>wrap:mvn:c3p0/c3p0/${c3p0.version}</bundle>
        <bundle>mvn:com.fusesource.examples/horo-db/1.0-SNAPSHOT</bundle>
        <bundle>mvn:org.mybatis/mybatis/${mybatis.version}</bundle>
        <bundle>mvn:org.mybatis/mybatis-spring/${mybatis.spring.version}</bundle>
        <bundle>mvn:org.springframework/org.springframework.jdbc/${spring.jdbc.version}</bundle>
        <!-- required by mybatis-spring -->
        <bundle>mvn:org.springframework.batch/spring-batch-infrastructure/${spring.batch.version}</bundle>
    </feature>

    <feature name="horo-rss-reader" version="1.0-SNAPSHOT">
        <feature version="${camel.version}">camel-tagsoup</feature>
        <feature version="${camel.version}">camel-jetty</feature>
        <feature version="${camel.version}">camel-xstream</feature>
        <feature version="${camel.version}">camel-rss</feature>
        <feature version="${camel.version}">camel-sql</feature>
        <feature version="1.0-SNAPSHOT">horo-model</feature>
        <bundle>mvn:org.springframework/org.springframework.jdbc/${spring.jdbc.version}</bundle>
        <bundle>mvn:com.fusesource.examples/horo-rss-reader/1.0-SNAPSHOT</bundle>
    </feature>

    <feature name="horo-web" version="1.0-SNAPSHOT">
        <feature version="${cxf.version}">cxf</feature>
        <feature version="1.0-SNAPSHOT">horo-model</feature>
        <bundle>mvn:com.fusesource.examples/horo-web/1.0-SNAPSHOT</bundle>
    </feature>

    <feature name="horo-all" version="1.0-SNAPSHOT">
        <feature version="1.0-SNAPSHOT">horo-model</feature>
        <feature version="1.0-SNAPSHOT">horo-db</feature>
        <feature version="1.0-SNAPSHOT">horo-web</feature>
        <feature version="1.0-SNAPSHOT">horo-rss-reader</feature>
    </feature>

</features>


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Bg Person Generator</title>
    <link rel="stylesheet" href="../css/bootstrap.min.css" />
    <link rel="stylesheet" href="../css/bootstrap-theme.min.css" />
    <link rel="stylesheet" href="../css/toastr.min.css" />
    <link rel="stylesheet" href="../css/app.css" />

                Bg Person Generator
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

                </button>

                        Create one

                        Generate many

                        Delete all

        Author: TsvetanKT


text:
@import "https://localhost/modify-this.css";
@import "https://localhost/modify-again.css";
.modify {
  my-url: url("https://localhost/a.png");
}
.modify {
  my-url: url("https://localhost/b.png");
}
@font-face {
  src: url("/fonts/garamond-pro.ttf");
  src: local(Futura-Medium), url(https://localhost/fonts.svg#MyGeometricModern) format("svg");
}
#shorthands {
  background: url("http://www.lesscss.org/spec.html") no-repeat 0 4px;
}
#misc {
  background-image: url(https://localhost/images/image.jpg);
}
#data-uri {
  background: url(data:image/png;charset=utf-8;base64,
    kiVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/
    k//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U
    kg9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC);
  background-image: url(data:image/x-png,f9difSSFIIGFIFJD1f982FSDKAA9==);
  background-image: url(http://fonts.googleapis.com/css?family=\"Rokkitt\":\(400\),700);
}
#svg-data-uri {
  background: transparent url('data:image/svg+xml, <svg version="1.1"><g></g></svg>');
}
.comma-delimited {
  background: url(https://localhost/bg.jpg) no-repeat, url(https://localhost/bg.png) repeat-x top left, url(https://localhost/bg);
}
.values {
  url: url('https://localhost/Trebuchet');
}


text:
<?php

namespace AppBundle\Handler;

use Redis;
use RedisArray;

class RedisSessionFactory
{
    protected $container;

    protected $redis;

    public function __construct($container)
    {
        $this->container = $container;
    }

    public function getRedis()
    {
        if (empty($this->redis)) {
            $this->redis = $this->createRedis();
        }

        return $this->redis;
    }

    public function createRedis()
    {
        if ($this->container->hasParameter('session_redis_host')) {
            $options = array(
                'host' => $this->container->getParameter('session_redis_host'),
                'timeout' => $this->container->getParameter('session_redis_timeout'),
                'reserved' => $this->container->getParameter('session_redis_reserved'),
                'retry_interval' => $this->container->getParameter('session_redis_retry_interval'),
            );
        } elseif ($this->container->hasParameter('redis_host')) {
            $options = array(
                'host' => $this->container->getParameter('redis_host'),
                'timeout' => $this->container->getParameter('redis_timeout'),
                'reserved' => $this->container->getParameter('redis_reserved'),
                'retry_interval' => $this->container->getParameter('redis_retry_interval'),
            );
        } else {
            throw new \RuntimeException('redis session parameters is not defined.');
        }

        if (!is_array($options['host'])) {
            $options['host'] = array((string) $options['host']);
        }

        if (empty($options['host'])) {
            throw new \RuntimeException('redis session host parameter is not defined.');
        }

        if (count($options['host']) == 1) {
            list($host, $port) = explode(':', current($options['host']));
            $redis = new Redis();
            $redis->pconnect($host, $port, $options['timeout'], $options['reserved'], $options['retry_interval']);
            $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
        } else {
            $redis = new RedisArray($options['host']);
            $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
        }

        return $redis;
    }
}


text:
package org.tinylog.core.backend;

import org.tinylog.core.Framework;

/**
 * Builder for creating an instance of a {@link LoggingBackend}.
 *
 *

 *     This interface must be implemented by all logging backends and provided as
 *     {@link java.util.ServiceLoader service} in {@code META-INF/services}.
 *

 */
public interface LoggingBackendBuilder {

	/**
	 * Gets the name of the logging backend, which can be used to address the logging backend in a configuration.
	 *
	 *

	 *     The name must start with a lower case ASCII letter [a-z] and end with a lower case ASCII letter [a-z] or
	 *     digit [0-9]. Within the name, lower case letters [a-z], numbers [0-9], spaces [ ], and hyphens [-] are
	 *     allowed.
	 *

	 *
	 * @return The name of the logging backend
	 */
	String getName();

	/**
	 * Creates a new instance of the logging backend.
	 *
	 * @param framework The actual logging framework instance
	 * @return New instance of the logging backend
	 */
	LoggingBackend create(Framework framework);

}


text:
package org.fcrepo.server.journal.readerwriter.singlefile;

import java.io.FileWriter;
import java.io.IOException;

import java.util.Map;

import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;

import javanet.staxutils.IndentingXMLEventWriter;

import org.fcrepo.server.journal.JournalException;
import org.fcrepo.server.journal.JournalWriter;
import org.fcrepo.server.journal.ServerInterface;
import org.fcrepo.server.journal.entry.CreatorJournalEntry;

/**
 * A rudimentary implementation of JournalWriter that just writes all entries to
 * a single Journal file. Useful only for System tests.
 *
 * @author Jim Blake
 */
public class SingleFileJournalWriter
        extends JournalWriter
        implements SingleFileJournalConstants {

    private final FileWriter out;

    private final XMLEventWriter writer;

    private boolean fileHasHeader = false;

    /**
     * Get the name of the journal file from the server parameters, create the
     * file, wrap it in an XMLEventWriter, and initialize it with a document
     * header.
     */
    public SingleFileJournalWriter(Map<String, String> parameters,
                                   String role,
                                   ServerInterface server)
            throws JournalException {
        super(parameters, role, server);

        if (!parameters.containsKey(PARAMETER_JOURNAL_FILENAME)) {
            throw new JournalException("Parameter '"
                    + PARAMETER_JOURNAL_FILENAME + "' not set.");
        }

        try {
            out = new FileWriter(parameters.get(PARAMETER_JOURNAL_FILENAME));

            XMLOutputFactory factory = XMLOutputFactory.newInstance();
            writer =
                    new IndentingXMLEventWriter(factory
                            .createXMLEventWriter(out));
        } catch (IOException e) {
            throw new JournalException(e);
        } catch (XMLStreamException e) {
            throw new JournalException(e);
        }
    }

    /**
     * Make sure that the file has been initialized before writing any journal
     * entries.
     */
    @Override
    public void prepareToWriteJournalEntry() throws JournalException {
        if (!fileHasHeader) {
            super.writeDocumentHeader(writer);
            fileHasHeader = true;
        }
    }

    /**
     * Every journal entry just gets added to the file.
     */
    @Override
    public void writeJournalEntry(CreatorJournalEntry journalEntry)
            throws JournalException {
        try {
            super.writeJournalEntry(journalEntry, writer);
            writer.flush();
        } catch (XMLStreamException e) {
            throw new JournalException(e);
        }
    }

    /**
     * Add the document trailer and close the journal file.
     */
    @Override
    public void shutdown() throws JournalException {
        try {
            if (fileHasHeader) {
                super.writeDocumentTrailer(writer);
            }
            writer.close();
            out.close();
        } catch (XMLStreamException e) {
            throw new JournalException(e);
        } catch (IOException e) {
            throw new JournalException(e);
        }
    }

}


text:
package com.livescribe.web.registration.response;

import java.util.ArrayList;
import java.util.List;

import com.livescribe.framework.orm.vectordb.Registration;
import com.livescribe.framework.web.response.ResponseCode;
import com.livescribe.framework.web.response.ServiceResponse;
import com.livescribe.web.registration.dto.RegistrationDTO;
import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("response")
public class RegistrationListResponse extends ServiceResponse {

	@XStreamAlias("registrations")
	private List<RegistrationDTO> registrations;

	/**
	 * Constructor
	 *
	 * @param responseCode
	 */
	public RegistrationListResponse() {
		super();
		registrations = new ArrayList<RegistrationDTO>();
	}

	/**
	 * Constructor
	 *
	 * @param responseCode
	 */
	public RegistrationListResponse(ResponseCode responseCode) {
		super(responseCode);
		registrations = new ArrayList<RegistrationDTO>();
	}

	/**
	 * Constructor
	 *
	 * @param responseCode
	 * @param regs
	 */
	public RegistrationListResponse(ResponseCode responseCode, List<Registration> regs) {
		super(responseCode);
		this.registrations = new ArrayList<RegistrationDTO>();

		if (regs != null) {
			for (Registration reg : regs) {
				RegistrationDTO regDTO = new RegistrationDTO(reg);
				this.registrations.add(regDTO);
			}
		}
	}

	public List<RegistrationDTO> getRegistrations() {
		return registrations;
	}

	public void setRegistrations(List<RegistrationDTO> registrations) {
		this.registrations = registrations;
	}

	/**
	 *

	 *
	 * @param regDTO
	 */
	public void addRegistrationDTO(RegistrationDTO regDTO) {
		if (registrations == null) {
			registrations = new ArrayList<RegistrationDTO>();
		}

		registrations.add(regDTO);
	}
}


text:
from os import path, chdir, getcwd

from cement.utils.misc import minimal_logger

from ..core import io, hooks, fileoperations
from ..core.abstractcontroller import AbstractBaseController
from ..lib import utils
from ..objects.exceptions import NoEnvironmentForBranchError, \
    InvalidOptionsError
from ..operations import commonops, deployops, composeops
from ..resources.strings import strings, flag_text

LOG = minimal_logger(__name__)

class DeployController(AbstractBaseController):
    class Meta(AbstractBaseController.Meta):
        label = 'deploy'
        description = strings['deploy.info']
        arguments = [
            (['environment_name'], dict(
                action='store', nargs='?', default=[],
                help=flag_text['deploy.env'])),
            (['--modules'], dict(help=flag_text['deploy.modules'], nargs='*')),
            (['-g', '--env-group-suffix'], dict(help=flag_text['deploy.group_suffix'])),
            (['--version'], dict(help=flag_text['deploy.version'])),
            (['-l', '--label'], dict(help=flag_text['deploy.label'])),
            (['-m', '--message'], dict(help=flag_text['deploy.message'])),
            (['-nh', '--nohang'], dict(
                action='store_true', help=flag_text['deploy.nohang'])),
            (['--staged'], dict(
                action='store_true', help=flag_text['deploy.staged'])),
            (['--timeout'], dict(type=int, help=flag_text['general.timeout'])),
            (['--source'], dict(type=utils.check_source, help=flag_text['deploy.source'])),
            (['-p', '--process'], dict(
                action='store_true', help=flag_text['deploy.process'])),
            ]
        usage = AbstractBaseController.Meta.usage.replace('{cmd}', label)

    def do_command(self):
        self.message = self.app.pargs.message
        self.staged = self.app.pargs.staged
        self.timeout = self.app.pargs.timeout
        self.nohang = self.app.pargs.nohang
        self.modules = self.app.pargs.modules
        self.source = self.app.pargs.source
        self.app_name = self.get_app_name()
        self.env_name = self.app.pargs.environment_name
        self.version = self.app.pargs.version
        self.label = self.app.pargs.label
        self.process = self.app.pargs.process
        group_name = self.app.pargs.env_group_suffix

        if self.modules and len(self.modules) > 0:
            self.multiple_app_deploy()
            return

        if self.nohang:
            self.timeout = 0

        if self.version and (self.message or self.label):
            raise InvalidOptionsError(strings['deploy.invalidoptions'])

        if not self.env_name:
            self.env_name = commonops.get_current_branch_environment()

        if not self.env_name:
            self.message = strings['branch.noenv'].replace('eb {cmd}',
                                                           self.Meta.label)
            io.log_error(self.message)
            raise NoEnvironmentForBranchError()

        # ToDo add support for deploying to multiples?
        # for arg in self.app.pargs.environment_name:
        #     # deploy to every environment listed
        #     ## Right now you can only list one

        process_app_versions = fileoperations.env_yaml_exists() or self.process

        deployops.deploy(self.app_name, self.env_name, self.version, self.label,
                         self.message, group_name=group_name, process_app_versions=process_app_versions,
                         staged=self.staged, timeout=self.timeout, source=self.source)

    def complete_command(self, commands):
        # TODO: edit this if we ever support multiple env deploys
        super(DeployController, self).complete_command(commands)

        ## versionlabels on --version
        cmd = commands[-1]
        if cmd in ['--version']:
            app_name = fileoperations.get_application_name()
            io.echo(*commonops.get_app_version_labels(app_name))

    def multiple_app_deploy(self):
        missing_env_yaml = []
        top_dir = getcwd()

        for module in self.modules:
            if not path.isdir(path.join(top_dir, module)):
                continue

            chdir(path.join(top_dir, module))

            if not fileoperations.env_yaml_exists():
                missing_env_yaml.append(module)

            chdir(top_dir)

        # We currently do not want to support multiple deploys when some of the
        # modules do not contain env.yaml files
        if len(missing_env_yaml) > 0:
            module_list = ''
            for module_name in missing_env_yaml:
                module_list = module_list + module_name + ', '
            io.echo(strings['deploy.modulemissingenvyaml'].replace('{modules}', module_list[:-2]))

            return

        self.compose_deploy()
        return

    def compose_deploy(self):
        app_name = None
        modules = self.app.pargs.modules
        group_name = self.app.pargs.env_group_suffix

        env_names = []
        stages_version_labels = {}
        stages_env_names = {}

        top_dir = getcwd()
        for module in modules:
            if not path.isdir(path.join(top_dir, module)):
                io.log_error(strings['deploy.notadirectory'].replace('{module}', module))
                continue

            chdir(path.join(top_dir, module))

            if not group_name:
                group_name = commonops.get_current_branch_group_suffix()
            if group_name not in stages_version_labels.keys():
                stages_version_labels[group_name] = []
                stages_env_names[group_name] = []

            if not app_name:
                app_name = self.get_app_name()

            io.echo('--- Creating application version for module: {0} ---'.format(module))

            # Re-run hooks to get values from .elasticbeanstalk folders of apps
            hooks.set_region(None)
            hooks.set_ssl(None)
            hooks.set_profile(None)

            if not app_name:
                app_name = self.get_app_name()

            process_app_version = fileoperations.env_yaml_exists()
            version_label = commonops.create_app_version(app_name, process=process_app_version)

            stages_version_labels[group_name].append(version_label)

            environment_name = fileoperations.get_env_name_from_env_yaml()

            if environment_name is not None:
                commonops.set_environment_for_current_branch(environment_name.
                                                             replace('+', '-{0}'.
                                                                     format(group_name)))

                env_name = commonops.get_current_branch_environment()
                stages_env_names[group_name].append(env_name)
                env_names.append(env_name)
            else:
                io.echo(strings['deploy.noenvname'].replace('{module}', module))
                stages_version_labels[group_name].pop(version_label)

            chdir(top_dir)

        if len(stages_version_labels) > 0:
            for stage in stages_version_labels.keys():
                request_id = composeops.compose_no_events(app_name, stages_version_labels[stage],
                                                          group_name=stage)
                if request_id is None:
                    io.error("Unable to compose modules.")
                    return

                commonops.wait_for_compose_events(request_id, app_name, env_names, self.timeout)
        else:
            io.log_warning(strings['compose.novalidmodules'])


text:
package org.apache.hyracks.storage.am.lsm.common.api;

import java.util.List;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.replication.IReplicationJob.ReplicationOperation;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.api.IIndexCursor;
import org.apache.hyracks.storage.am.common.api.IIndexOperationContext;
import org.apache.hyracks.storage.am.common.api.IModificationOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchPredicate;
import org.apache.hyracks.storage.am.common.api.IndexException;

public interface ILSMIndexInternal extends ILSMIndex {
    @Override
    public ILSMIndexAccessorInternal createAccessor(IModificationOperationCallback modificationCallback,
            ISearchOperationCallback searchCallback) throws HyracksDataException;

    public void modify(IIndexOperationContext ictx, ITupleReference tuple) throws HyracksDataException, IndexException;

    public void search(ILSMIndexOperationContext ictx, IIndexCursor cursor, ISearchPredicate pred)
            throws HyracksDataException, IndexException;

    public void scheduleFlush(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
            throws HyracksDataException;

    public ILSMComponent flush(ILSMIOOperation operation) throws HyracksDataException, IndexException;

    public void scheduleMerge(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
            throws HyracksDataException, IndexException;

    public ILSMComponent merge(ILSMIOOperation operation) throws HyracksDataException, IndexException;

    public void addComponent(ILSMComponent index) throws HyracksDataException;

    public void subsumeMergedComponents(ILSMComponent newComponent, List<ILSMComponent> mergedComponents)
            throws HyracksDataException;

    public void changeMutableComponent();

    public void changeFlushStatusForCurrentMutableCompoent(boolean needsFlush);

    public boolean hasFlushRequestForCurrentMutableComponent();

    /**
     * Populates the context's component holder with a snapshot of the components involved in the operation.
     *
     * @param ctx
     *            - the operation's context
     * @throws HyracksDataException
     */
    public void getOperationalComponents(ILSMIndexOperationContext ctx) throws HyracksDataException;

    public List<ILSMComponent> getInactiveDiskComponents();

    public void addInactiveDiskComponent(ILSMComponent diskComponent);

    /**
     * Persistent the LSM component
     *
     * @param lsmComponent
     *            , the component to be persistent
     * @throws HyracksDataException
     */
    public void markAsValid(ILSMComponent lsmComponent) throws HyracksDataException;

    public boolean isCurrentMutableComponentEmpty() throws HyracksDataException;

    public void scheduleReplication(ILSMIndexOperationContext ctx, List<ILSMComponent> lsmComponents, boolean bulkload,
            ReplicationOperation operation, LSMOperationType opType) throws HyracksDataException;

}


text:
package pt.up.fe.ssin.pexplorer.app;

import java.util.List;
import java.util.Locale;

import pt.up.fe.ssin.pexplorer.R;
import pt.up.fe.ssin.pexplorer.data.PermissionCatalog;
import pt.up.fe.ssin.pexplorer.utils.PermissionUtils;
import pt.up.fe.ssin.pexplorer.utils.ui.SimpleObjectAdapter;
import android.content.Context;
import android.content.pm.PermissionInfo;
import android.view.View;
import android.widget.TextView;

public class PermissionListAdapter extends SimpleObjectAdapter<PermissionInfo> {

    PermissionCatalog catalog;

    public PermissionListAdapter(Context context, List<PermissionInfo> objects) {
        super(context, R.layout.perm_row, objects);
        catalog = PermissionCatalog.getInstance(context);
    }

    @Override
    public View getView(View inflatedView, PermissionInfo perm) {
        String shortName = PermissionUtils.getShortName(perm);

        TextView tv = (TextView) inflatedView.findViewById(android.R.id.text1);
        tv.setText(shortName);

        tv = (TextView) inflatedView.findViewById(android.R.id.text2);
        tv.setText(perm.loadLabel(catalog.getPackageManager()));

        return inflatedView;
    }

    @Override
    public boolean isFilterMatch(CharSequence constraint, PermissionInfo perm) {
        String[] prefixes = constraint.toString()
                .toLowerCase(Locale.getDefault()).split(" ");
        String[] words = PermissionUtils.getShortName(perm).split("_");

        for (String prefix : prefixes) {
            boolean hasPrefix = false;
            for (String word : words)
                if (word.toLowerCase(Locale.getDefault()).startsWith(prefix)) {
                    hasPrefix = true;
                    break;
                }
            if (!hasPrefix)
                return false;
        }
        return true;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 34: 18 (1951)

#### Original name
Nodulisporium africanum G. Sm., 1951

### Remarks
null


text:
import { getModuleLoader } from 'emscripten-wasm-loader';
import { HunspellAsmModule } from './HunspellAsmModule';
import { HunspellFactory } from './HunspellFactory';
import { hunspellLoader } from './hunspellLoader';
import { log } from './util/logger';

//imports MODULARIZED emscripten preamble
import * as runtime from './lib/node/hunspell';

/**
 * Load, initialize wasm binary to use actual hunspell wasm instances.
 *
 * @param [InitOptions] Options to initialize hunspell wasm binary.
 * @param {number} [InitOptions.timeout] - timeout to wait wasm binary compilation & load.
 * @param {string | object} [InitOptions.locateBinary] - custom resolution logic for wasm binary. (not supported)
 * It could be either remote endpoint url, or loader-returned object for bundler. Check examples/browser_* for references.
 *
 * @returns {() => Promise<HunspellFactory>} Function to load module
 */
const loadModule = async (
  initOptions: Partial<{
    timeout: number;
  }> = {}
) => {
  const { timeout } = initOptions;
  log(`loadModule: loading hunspell wasm binary`, { initOptions });

  const moduleLoader = await getModuleLoader<HunspellFactory, HunspellAsmModule>(
    (runtime: HunspellAsmModule) => hunspellLoader(runtime),
    runtime,
    undefined,
    { timeout }
  );

  return moduleLoader();
};

export { loadModule };


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * apk 升级包
 * Class Upgrade
 * @package App\Models\Busi
 * @author xrs
 * @SWG\Model(id="Upgrade")
 * @SWG\Property(name="upgrade_date", type="string", description="更新日期")
 * @SWG\Property(name="content", type="string", description="更新内容")
 * @SWG\Property(name="created_at", type="string", description="created_at")
 * @SWG\Property(name="enforce", type="integer", description="是否强制(0-否,1-是)")
 * @SWG\Property(name="id", type="integer", description="id")
 * @SWG\Property(name="updated_at", type="string", description="updated_at")
 * @SWG\Property(name="url", type="string", description="下载地址")
 * @SWG\Property(name="version_code", type="string", description="version_code")
 * @SWG\Property(name="version_name", type="string", description="version_name")
 * @SWG\Property(name="type", type="string", description="类型(android, iphone)")
 */
class Upgrade extends Model
{
    //
    protected $table='sys_upgrades';
    protected $guarded = ['id'];
}


text:
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
 * @fileoveriew A leaf dispatcher that uses a single service object for
 * all suffixes
 */

/**
 * Returns a dispatcher function that will reuse the same service object
 * for all suffixes.
 * @private
 * @param {Service} service Service object.
 * @param {Authorizer} [authorizer] Optional authorizer to use.
 * @return {function} A dispatcher function that will reuse the same service
 * object.
 */
function createLeafDispatcher(service, authorizer) {
  var dispatcher = function() {
    return {
      service: service,
      authorizer: authorizer,
    };
  };
  dispatcher._isLeaf = true;
  return dispatcher;
}

/**
 * Export module
 */
module.exports = createLeafDispatcher;


text:
- do not use newer viewmodel version

## v0.7.0

- updated node-queue

## v0.6.1

- send commandRejected event with better reason

## v0.6.0 (BREAKING CHANGES!!!)

- updated eventdenormalier
- introduction of revisionGuard
- contextEventDenormalizer is now eventDenormalizer
- eventMissing notification (for atomic replay)
- eventDenormalizer.replay to replay (from scratch)
- eventDenormalizerBase is now viewBuilderBase
- viewBuilderBase new signature (see documentation or tests)

## v0.5.4

- buffer commands by aggregate id

## v0.5.3

- fix for async business rules

## v0.5.2

- fix commandDispatcher if no commandqueue is used

## v0.5.0

- a complete change of validation rules (see new [rule-validator](https://github.com/adrai/rule-validator))

## v0.4.3

- added disableQueuing flag

## v0.4.2

- strip .js file extensions to enable loading of .coffee scripts too

## v0.4.1

- added forcedQueuing flag

## v0.4.0

- asynchronous api for saga

## v0.3.7

- optimized performance a little

## v0.3.6

- fixed saga handler base


text:
/**
 * @author Pedro Sanders
 * @since v1
 */
const postal = require('postal')
const Registrar = require('@routr/registrar/registrar')
const RegistrarUtils = require('@routr/registrar/utils')
const {
  sendOk,
  sendUnauthorized,
  getExpires
} = require('@routr/core/processor/processor_utils')

const ToHeader = Java.type('javax.sip.header.ToHeader')
const ContactHeader = Java.type('javax.sip.header.ContactHeader')

class RegisterHandler {
  constructor () {
    this.registrar = new Registrar()
  }

  doProcess (transaction) {
    const request = transaction.getRequest()
    // See: Removing bindings -> https://tools.ietf.org/html/rfc3261#section-10.2.2
    if (getExpires(request) <= 0) {
      const contactHeader = request.getHeader(ContactHeader.NAME)
      const toHeader = request.getHeader(ToHeader.NAME)
      const addressOfRecord = toHeader.getAddress().getURI()

      postal.publish({
        channel: 'locator',
        topic: 'endpoint.remove',
        data: {
          addressOfRecord: addressOfRecord,
          contactURI: contactHeader
            .getAddress()
            .getURI()
            .toString(),
          isWildcard: contactHeader.getAddress().isWildcard()
        }
      })

      sendOk(transaction)
    } else {
      this.registrar.register(request)
        ? sendOk(transaction)
        : sendUnauthorized(transaction)
    }
  }
}

module.exports = RegisterHandler


text:
namespace Tiny3D {
namespace IO {

bool ModelXmlImporter::ImportMesh(Model* asset, const pugi::xml_node& node, std::shared_ptr<Material> material)
{
    const pugi::xml_attribute& meshtype_attr = node.attribute("type");
    const pugi::xml_attribute& meshsrc_attr = node.attribute("src");
    if (meshtype_attr && meshsrc_attr)
    {
        size_t first_mesh = asset->GetMeshCount();
        // Add the mesh(es) from the model/mesh file to the model.
        // Only whole Models are cached so we can not use GetAsset().
        bool result = Assets::Importers.Import<Model>(asset, meshtype_attr.value(), meshsrc_attr.value());

        if (result)
        {
            for (size_t i = first_mesh; i < asset->GetMeshCount(); i++)
            {
                // Apply material to new meshes
                shared_ptr<Mesh> mesh = asset->GetMesh(i);
                if (!mesh->material_)
                    mesh->material_ = material;
                else
                {
                    // If it has a material but no program, just assign the program
                    if (!mesh->material_->HasProgram())
                        mesh->material_->SetProgram(material->GetProgram());
                    if (material->wireFrame_)
                        mesh->material_->wireFrame_ = material->wireFrame_;
                }
            }
        }

        return result;
    }
    return false;
}

bool ModelXmlImporter::Import(Model* asset, FileTypes::filetype_t ft, const std::wstring& name)
{
    UNREFERENCED_PARAMETER(ft);

    pugi::xml_document doc;
    const pugi::xml_parse_result& result = doc.load_file(name.c_str());
    if (result.status != pugi::status_ok)
        return false;
    const pugi::xml_node& modelnode = doc.child("model");
    if (!modelnode)
        return false;

    return LoadFromNode(asset, modelnode);
}

bool ModelXmlImporter::LoadFromNode(Model* asset, const pugi::xml_node& node)
{

    const pugi::xml_attribute& name_attr = node.attribute("name");
    if (name_attr)
        asset->name_ = name_attr.value();

    const pugi::xml_attribute& attr = node.attribute("type");
    if (attr)
    {
        if (strcmp(attr.value(), "static") == 0)
            asset->type_ = Model::ModelType::Static;
        else if (strcmp(attr.value(), "animated") == 0)
            asset->type_ = Model::ModelType::Animated;
    }

    const pugi::xml_node& meshesnode = node.child("meshes");
    if (meshesnode)
    {
        // Add all meshes to the model
        for (pugi::xml_node_iterator it = meshesnode.begin(); it != meshesnode.end(); ++it)
        {
            std::shared_ptr<Material> material = nullptr;
            const pugi::xml_node& mat_node = (*it).child("material");
            if (mat_node)
            {
                const pugi::xml_attribute& type_attr = mat_node.attribute("type");
                const pugi::xml_attribute& src_attr = mat_node.attribute("src");
                if (type_attr && src_attr)
                    material = Assets::Importers.GetAsset<Material>(StringHashRt(type_attr.value()), src_attr.value());
                if (!material)
                {
                    // maybe inline
                    material = std::make_shared<Material>();
                    if (!MaterialXmlImporter::LoadFromNode(material.get(), mat_node))
                        material.reset();
                }
            }
            if (!ImportMesh(asset, (*it), material))
                return false;
        }
    }

    asset->MakeDirty();
    return true;
}

}
}


text:
A wysiwyg editor that mimics medium, build on top of https://github.com/facebook/draft-js and https://github.com/draft-js-plugins/draft-js-plugins. All the relevant behaviour comes from plugins, so this may serve as an example of using the plugin architecture and the different plugins. You can also install and use draft-wysiwyg right away.

## Demo
https://textio-editor.herokuapp.com/

## Features
- Copy-Paste Functionality
- Inline toolbar for text
- Block drag/drop
- Block toolbars
- Block keydown handling to remove blocks (backspace) or move cursor to next/previous block
- Bold, H1, H2, UL, LI
- Blocks copying of undesirable things like tables, images, etc

## Needs Work
- Allows multiple empty blocks
- It's hard to end a list in an intuitive way

## Installation
```
npm install draft-wysiwyg
```
or
```
sudo npm install draft-wysiwyg
```

## Usage
```
npm install
npm start
```

Then open [localhost:3030](http://localhost:3030)

## Contributing
Pull requests are very welcome, feel free to commit your ideas!


text:
namespace browser_sync {

// Maximum number of session we're going to display on the NTP
static const size_t kMaxSessionsToShow = 10;

// Invalid value, used to note that we don't have a tab or window number.
static const int kInvalidId = -1;

namespace {

// Comparator function for use with std::sort that will sort sessions by
// descending modified_time (i.e., most recent first).
bool SortSessionsByRecency(const SyncedSession* s1, const SyncedSession* s2) {
  return s1->modified_time > s2->modified_time;
}

}  // namepace

ForeignSessionHandler::ForeignSessionHandler() {
}

void ForeignSessionHandler::RegisterMessages() {
  Init();
  web_ui()->RegisterMessageCallback("getForeignSessions",
      base::Bind(&ForeignSessionHandler::HandleGetForeignSessions,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("openForeignSession",
      base::Bind(&ForeignSessionHandler::HandleOpenForeignSession,
                 base::Unretained(this)));
}

void ForeignSessionHandler::Init() {
  Profile* profile = Profile::FromWebUI(web_ui());
  registrar_.Add(this, chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
                 content::Source<Profile>(profile));
  registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED,
                 content::Source<Profile>(profile));
  registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED,
                 content::Source<Profile>(profile));
}

void ForeignSessionHandler::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  ListValue list_value;
  switch (type) {
    case chrome::NOTIFICATION_SYNC_CONFIGURE_DONE:
    case chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED:
    case chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED:
      HandleGetForeignSessions(&list_value);
      break;
    default:
      NOTREACHED();
  }
}

SessionModelAssociator* ForeignSessionHandler::GetModelAssociator() {
  Profile* profile = Profile::FromWebUI(web_ui());
  ProfileSyncService* service =
      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
  if (service == NULL)
    return NULL;

  // Only return the associator if it exists and it is done syncing sessions.
  SessionModelAssociator* model_associator =
      service->GetSessionModelAssociator();
  if (!service->ShouldPushChanges())
    return NULL;
  return model_associator;
}

bool ForeignSessionHandler::IsTabSyncEnabled() {
  Profile* profile = Profile::FromWebUI(web_ui());
  ProfileSyncService* service =
      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
  return service && service->GetSessionModelAssociator();
}

void ForeignSessionHandler::HandleGetForeignSessions(const ListValue* args) {
  SessionModelAssociator* associator = GetModelAssociator();
  std::vector<const SyncedSession*> sessions;

  ListValue session_list;
  if (associator && associator->GetAllForeignSessions(&sessions)) {
    // Sort sessions from most recent to least recent.
    std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);

    // Note: we don't own the SyncedSessions themselves.
    for (size_t i = 0; i < sessions.size() && i < kMaxSessionsToShow; ++i) {
      const SyncedSession* session = sessions[i];
      scoped_ptr<DictionaryValue> session_data(new DictionaryValue());
      session_data->SetString("tag", session->session_tag);
      session_data->SetString("name", session->session_name);
      scoped_ptr<ListValue> window_list(new ListValue());
      for (SyncedSession::SyncedWindowMap::const_iterator it =
           session->windows.begin(); it != session->windows.end(); ++it) {
        SessionWindow* window = it->second;
        scoped_ptr<DictionaryValue> window_data(new DictionaryValue());
        if (SessionWindowToValue(*window, window_data.get()))
          window_list->Append(window_data.release());
      }

      session_data->Set("windows", window_list.release());
      session_list.Append(session_data.release());
    }
  }
  base::FundamentalValue tab_sync_enabled(IsTabSyncEnabled());
  web_ui()->CallJavascriptFunction("ntp.setForeignSessions",
                                   session_list,
                                   tab_sync_enabled);
}

void ForeignSessionHandler::HandleOpenForeignSession(
    const ListValue* args) {
  size_t num_args = args->GetSize();
  // Expect either 2 or 8 args. For restoring an entire window, only
  // two arguments are required -- the session tag and the window id.
  // To restore a tab, the additional args required are the tab id,
  // and 4 properties of the event object (button, altKey, ctrlKey,
  // metaKey, shiftKey) for determining how to open the tab.
  if (num_args != 8U && num_args != 2U) {
    LOG(ERROR) << "openForeignSession called with " << args->GetSize()
               << " arguments.";
    return;
  }

  // Extract the machine tag (always provided).
  std::string session_string_value;
  if (!args->GetString(0, &session_string_value)) {
    LOG(ERROR) << "Failed to extract session tag.";
    return;
  }

  // Extract window number (always provided).
  std::string window_num_str;
  int window_num = kInvalidId;
  if (num_args >= 2 && (!args->GetString(1, &window_num_str) ||
      !base::StringToInt(window_num_str, &window_num))) {
    LOG(ERROR) << "Failed to extract window number.";
    return;
  }

  // Extract tab id.
  std::string tab_id_str;
  SessionID::id_type tab_id = kInvalidId;
  if (num_args >= 3 && (!args->GetString(2, &tab_id_str) ||
      !base::StringToInt(tab_id_str, &tab_id))) {
    LOG(ERROR) << "Failed to extract tab SessionID.";
    return;
  }

  SessionModelAssociator* associator = GetModelAssociator();

  Profile* profile = Profile::FromWebUI(web_ui());
  if (tab_id != kInvalidId) {
    // We don't actually care about |window_num|, this is just a sanity check.
    DCHECK_LT(kInvalidId, window_num);
    const SessionTab* tab;
    if (!associator->GetForeignTab(session_string_value, tab_id, &tab)) {
      LOG(ERROR) << "Failed to load foreign tab.";
      return;
    }
    WindowOpenDisposition disposition =
        web_ui_util::GetDispositionFromClick(args, 3);
    SessionRestore::RestoreForeignSessionTab(profile, *tab, disposition);
  } else {
    std::vector<const SessionWindow*> windows;
    // Note: we don't own the ForeignSessions themselves.
    if (!associator->GetForeignSession(session_string_value, &windows)) {
      LOG(ERROR) << "ForeignSessionHandler failed to get session data from"
          "SessionModelAssociator.";
      return;
    }
    std::vector<const SessionWindow*>::const_iterator iter_begin =
        windows.begin() + ((window_num == kInvalidId) ? 0 : window_num);
    std::vector<const SessionWindow*>::const_iterator iter_end =
        ((window_num == kInvalidId) ?
        std::vector<const SessionWindow*>::const_iterator(windows.end()) :
        iter_begin + 1);
    SessionRestore::RestoreForeignSessionWindows(profile, iter_begin, iter_end);
  }
}

bool ForeignSessionHandler::SessionTabToValue(
    const SessionTab& tab,
    DictionaryValue* dictionary) {
  if (tab.navigations.empty())
    return false;
  int selected_index = tab.current_navigation_index;
  selected_index = std::max(
      0,
      std::min(selected_index,
               static_cast<int>(tab.navigations.size() - 1)));
  const TabNavigation& current_navigation =
      tab.navigations.at(selected_index);
  if (current_navigation.virtual_url() == GURL(chrome::kChromeUINewTabURL))
    return false;
  NewTabUI::SetURLTitleAndDirection(dictionary, current_navigation.title(),
                                    current_navigation.virtual_url());
  dictionary->SetString("type", "tab");
  dictionary->SetDouble("timestamp",
                        static_cast<double>(tab.timestamp.ToInternalValue()));
  dictionary->SetInteger("sessionId", tab.tab_id.id());
  return true;
}

bool ForeignSessionHandler::SessionWindowToValue(
    const SessionWindow& window,
    DictionaryValue* dictionary) {
  if (window.tabs.empty()) {
    NOTREACHED();
    return false;
  }
  scoped_ptr<ListValue> tab_values(new ListValue());
  for (size_t i = 0; i < window.tabs.size(); ++i) {
    scoped_ptr<DictionaryValue> tab_value(new DictionaryValue());
    if (SessionTabToValue(*window.tabs[i], tab_value.get()))
      tab_values->Append(tab_value.release());
  }
  if (tab_values->GetSize() == 0)
    return false;
  dictionary->SetString("type", "window");
  dictionary->SetDouble("timestamp",
      static_cast<double>(window.timestamp.ToInternalValue()));
  dictionary->SetInteger("sessionId", window.window_id.id());
  dictionary->Set("tabs", tab_values.release());
  return true;
}

}  // namespace browser_sync


text:
{# These macros implement different DOM components of the opportunities page #}

{# listing : string, string, URL --> opportunity listing
 # given a name, description and link, this macro produces an offset description
 # of an opportunity in a certain category.
 #}
{% macro listing( name, description, link, linktext ) %}

{{ name }}

{{ description }}

          {% if link || linktext %}

            {% if link %} {% else %}
{% endif %}

              {% if linktext %}
                {{ linktext }}
              {% else %}
                Learn More
              {% endif %}

             {% if link %}{% else %}
{% endif %}

          {% endif %}

{% endmacro %}

{# header : string, string --> opportunity header
 # given a name, description and link, this macro produces an offset description
 # of an opportunity in a certain category.
 #}
{% macro header( section, description ) %}

            {{ section }}

              {{ description }}

{% endmacro %}

{# opportunities : string, string, [opportunity] --> opportunity listing
 # given a name, description, and an array of listings in the category, this
 # macro produces a
 #}
{% macro opportunities(name, description, no_opportunities, collection, classes) %}

	      {% if collection && collection.length > 0 %}

	        {% for opportunity in collection %}

	        {{ listing( opportunity.name, opportunity.description, opportunity.link, opportunity.link_text ) }}

	        {% endfor %}

          {% else %}

{{ no_opportunities|safe }}

          {% endif %}

{% endmacro %}


text:
import { Component, NgModule } from '@angular/core';
import { IgGridComponent } from "../../src/igniteui.angular2";
import { Northwind } from "./../data/northwind";
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic }	from '@angular/platform-browser-dynamic';

declare var jQuery: any;
@Component({
	selector: 'my-app',
	templateUrl: "./igGrid-TopLevelOptsTemplate.html"
})
export class AppComponent {
	private cols: Array<any>;
	private id: string;
	private data: any;
	private w: string;
	private h: string;
	private pKey: string;

	constructor() {
		this.data = Northwind.getData();

		this.id ='grid1';
		this.w = '100%';
		this.h = '400px';
		this.pKey = 'ProductID';

		this.cols = [
			{ key: "ProductID", headerText: "Product ID", width:"50px", dataType:"number" },
			{ key: "ProductName", headerText: "Name", width:"250px", dataType:"string" },
			{ key: "QuantityPerUnit", headerText: "Quantity per unit", width:"250px", dataType:"string" },
			{ key: "UnitPrice", headerText: "Unit Price", width:"100px", dataType:"number" }
		];
	}
}

@NgModule({
	imports:	  [ BrowserModule ],
	declarations: [ AppComponent, IgGridComponent ],
	bootstrap:	[ AppComponent ]
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);


text:
This folder contains trace files that we used in the HPCA'16 paper to evaluate ChargeCache.

[ChargeCache: Reducing DRAM Latency by Exploiting Row Access
  Locality](https://users.ece.cmu.edu/~omutlu/pub/chargecache_low-latency-dram_hpca16.pdf)
by Hassan et al. in HPCA 2016.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class ToscaParameter
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class ToscaParameter
   ">
    <meta name="generator" content="docfx 2.3.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

              Improve this Doc
              View Source

Class ToscaParameter

A parameter definition is essentially a TOSCA property definition;
however, it also allows a value to be assigned to it (as for a TOSCA property assignment).
In addition, in the case of output parameters, it can optionally inherit the data type of
the value assigned to it rather than have an explicit data type defined for it.

Inheritance

System.Object

ToscaParameter

Inherited Members

                  System.Object.ToString()

                  System.Object.Equals(System.Object)

                  System.Object.Equals(System.Object, System.Object)

                  System.Object.ReferenceEquals(System.Object, System.Object)

                  System.Object.GetHashCode()

                  System.Object.GetType()

                  System.Object.MemberwiseClone()

Namespace:Toscana

Assembly:Toscana.dll

Syntax

public class ToscaParameter

Constructors

                |
                Improve this Doc

                View Source

ToscaParameter()

Initializes an instance of ToscaParameter

Declaration

public ToscaParameter()

Properties

                |
                Improve this Doc

                View Source

Constraints

The optional list of sequenced constraint clauses for the parameter.

Declaration

public List<Dictionary<string, object>> Constraints { get; set; }

Property Value

                    Type
                    Description

                    System.Collections.Generic.List<System.Collections.Generic.Dictionary<System.String, System.Object>>

                |
                Improve this Doc

                View Source

Default

An optional key that may provide a value to be used as a default if not provided by another means.

Declaration

public object Default { get; set; }

Property Value

                    Type
                    Description

                    System.Object

                |
                Improve this Doc

                View Source

Description

The optional description for the parameter.

Declaration

public string Description { get; set; }

Property Value

                    Type
                    Description

                    System.String

                |
                Improve this Doc

                View Source

EntrySchema

The optional key that is used to declare the name of the Datatype definition for entries of set types such as the TOSCA list or map.

Declaration

public string EntrySchema { get; set; }

Property Value

                    Type
                    Description

                    System.String

                |
                Improve this Doc

                View Source

Required

An optional key that declares a parameter as required (true) or not (false).

Declaration

public bool Required { get; set; }

Property Value

                    Type
                    Description

                    System.Boolean

                |
                Improve this Doc

                View Source

Status

The optional status of the parameter relative to the specification or implementation.

Declaration

public ToscaPropertyStatus Status { get; set; }

Property Value

                    Type
                    Description

                    ToscaPropertyStatus

                |
                Improve this Doc

                View Source

StringDefaultValue

String representation of Default property.
Returns empty string when default is null

Declaration

public string StringDefaultValue { get; }

Property Value

                    Type
                    Description

                    System.String

                |
                Improve this Doc

                View Source

StringValue

String representation of Value property.
Returns empty string when Value is null

Declaration

public string StringValue { get; }

Property Value

                    Type
                    Description

                    System.String

                |
                Improve this Doc

                View Source

Type

The required data type for the parameter.

Note: This keyname is required for a TOSCA Property definition, but is not for a TOSCA Parameter definition.

Declaration

public string Type { get; set; }

Property Value

                    Type
                    Description

                    System.String

                |
                Improve this Doc

                View Source

Value

The type-compatible value to assign to the named parameter.
Parameter values may be provided as the result from the evaluation of an expression or a function.

Declaration

public object Value { get; set; }

Property Value

                    Type
                    Description

                    System.Object

Extension Methods

                  Toscana.Common.EnumerableExtensions.FromHierarchy<Toscana.ToscaParameter>(System.Func<Toscana.ToscaParameter, Toscana.ToscaParameter>, System.Func<Toscana.ToscaParameter, System.Boolean>)

                  Toscana.Common.EnumerableExtensions.FromHierarchy<Toscana.ToscaParameter>(System.Func<Toscana.ToscaParameter, Toscana.ToscaParameter>)

              Back to top

            Copyright © 2015-2016 Microsoft
Generated by DocFX