text:
package vcl

import (
    . "github.com/ying32/govcl/vcl/api"
    . "github.com/ying32/govcl/vcl/types"
    "unsafe"
)

type TIconOptions struct {
    IObject
    instance uintptr
    // 特殊情况下使用,主要应对Go的GC问题,与LCL没有太多关系。
    ptr unsafe.Pointer
}

// 动态转换一个已存在的对象实例。
//
// Dynamically convert an existing object instance.
func AsIconOptions(obj interface{}) *TIconOptions {
    instance, ptr := getInstance(obj)
    if instance == 0 { return nil }
    return &TIconOptions{instance: instance, ptr: ptr}
}

// -------------------------- Deprecated begin --------------------------
// 新建一个对象来自已经存在的对象实例指针。
//
// Create a new object from an existing object instance pointer.
// Deprecated: use AsIconOptions.
func IconOptionsFromInst(inst uintptr) *TIconOptions {
    return AsIconOptions(inst)
}

// 新建一个对象来自已经存在的对象实例。
//
// Create a new object from an existing object instance.
// Deprecated: use AsIconOptions.
func IconOptionsFromObj(obj IObject) *TIconOptions {
    return AsIconOptions(obj)
}

// 新建一个对象来自不安全的地址。注意:使用此函数可能造成一些不明情况,慎用。
//
// Create a new object from an unsecured address. Note: Using this function may cause some unclear situations and be used with caution..
// Deprecated: use AsIconOptions.
func IconOptionsFromUnsafePointer(ptr unsafe.Pointer) *TIconOptions {
    return AsIconOptions(ptr)
}

// -------------------------- Deprecated end --------------------------
// 返回对象实例指针。
//
// Return object instance pointer.
func (i *TIconOptions) Instance() uintptr {
    return i.instance
}

// 获取一个不安全的地址。
//
// Get an unsafe address.
func (i *TIconOptions) UnsafeAddr() unsafe.Pointer {
    return i.ptr
}

// 检测地址是否为空。
//
// Check if the address is empty.
func (i *TIconOptions) IsValid() bool {
    return i.instance != 0
}

// 检测当前对象是否继承自目标对象。
//
// Checks whether the current object is inherited from the target object.
func (i *TIconOptions) Is() TIs {
    return TIs(i.instance)
}

// 动态转换当前对象为目标对象。
//
// Dynamically convert the current object to the target object.
//func (i *TIconOptions) As() TAs {
//    return TAs(i.instance)
//}

// 获取类信息指针。
//
// Get class information pointer.
func TIconOptionsClass() TClass {
    return IconOptions_StaticClassType()
}

// 复制一个对象,如果对象实现了此方法的话。
//
// Copy an object, if the object implements this method.
func (i *TIconOptions) Assign(Source IObject) {
    IconOptions_Assign(i.instance, CheckPtr(Source))
}

// 获取类名路径。
//
// Get the class name path.
func (i *TIconOptions) GetNamePath() string {
    return IconOptions_GetNamePath(i.instance)
}

// 获取类的类型信息。
//
// Get class type information.
func (i *TIconOptions) ClassType() TClass {
    return IconOptions_ClassType(i.instance)
}

// 获取当前对象类名称。
//
// Get the current object class name.
func (i *TIconOptions) ClassName() string {
    return IconOptions_ClassName(i.instance)
}

// 获取当前对象实例大小。
//
// Get the current object instance size.
func (i *TIconOptions) InstanceSize() int32 {
    return IconOptions_InstanceSize(i.instance)
}

// 判断当前类是否继承自指定类。
//
// Determine whether the current class inherits from the specified class.
func (i *TIconOptions) InheritsFrom(AClass TClass) bool {
    return IconOptions_InheritsFrom(i.instance, AClass)
}

// 与一个对象进行比较。
//
// Compare with an object.
func (i *TIconOptions) Equals(Obj IObject) bool {
    return IconOptions_Equals(i.instance, CheckPtr(Obj))
}

// 获取类的哈希值。
//
// Get the hash value of the class.
func (i *TIconOptions) GetHashCode() int32 {
    return IconOptions_GetHashCode(i.instance)
}

// 文本类信息。
//
// Text information.
func (i *TIconOptions) ToString() string {
    return IconOptions_ToString(i.instance)
}

func (i *TIconOptions) Arrangement() TIconArrangement {
    return IconOptions_GetArrangement(i.instance)
}

func (i *TIconOptions) SetArrangement(value TIconArrangement) {
    IconOptions_SetArrangement(i.instance, value)
}

func (i *TIconOptions) AutoArrange() bool {
    return IconOptions_GetAutoArrange(i.instance)
}

func (i *TIconOptions) SetAutoArrange(value bool) {
    IconOptions_SetAutoArrange(i.instance, value)
}


text:
namespace ui {

namespace {

// Encodes a bitmap into a PNG and write to disk. Returns true on success. The
// parent directory does not have to exist.
bool WritePNGFile(const SkBitmap& bitmap, const FilePath& file_path) {
  std::vector<unsigned char> png_data;
  if (gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, &png_data) &&
      file_util::CreateDirectory(file_path.DirName())) {
    char* data = reinterpret_cast<char*>(&png_data[0]);
    int size = static_cast<int>(png_data.size());
    return file_util::WriteFile(file_path, data, size) == size;
  }
  return false;
}

// Reads and decodes a PNG image to a bitmap. Returns true on success. The PNG
// should have been encoded using |gfx::PNGCodec::Encode|.
bool ReadPNGFile(const FilePath& file_path, SkBitmap* bitmap) {
  DCHECK(bitmap);
  std::string png_data;
  return file_util::ReadFileToString(file_path, &png_data) &&
         gfx::PNGCodec::Decode(reinterpret_cast<unsigned char*>(&png_data[0]),
                               png_data.length(),
                               bitmap);
}

// Compares with a PNG file on disk, and returns true if it is the same as
// the given image. |ref_img_path| is absolute.
bool IsSameAsPNGFile(const SkBitmap& gen_bmp, FilePath ref_img_path) {
  SkBitmap ref_bmp;
  if (!ReadPNGFile(ref_img_path, &ref_bmp)) {
    LOG(ERROR) << "Cannot read reference image: " << ref_img_path.value();
    return false;
  }

  if (ref_bmp.width() != gen_bmp.width() ||
      ref_bmp.height() != gen_bmp.height()) {
    LOG(ERROR)
        << "Dimensions do not match (Expected) vs (Actual):"
        << "(" << ref_bmp.width() << "x" << ref_bmp.height()
            << ") vs. "
        << "(" << gen_bmp.width() << "x" << gen_bmp.height() << ")";
    return false;
  }

  // Compare pixels and create a simple diff image.
  int diff_pixels_count = 0;
  SkAutoLockPixels lock_bmp(gen_bmp);
  SkAutoLockPixels lock_ref_bmp(ref_bmp);
  // The reference images were saved with no alpha channel. Use the mask to
  // set alpha to 0.
  uint32_t kAlphaMask = 0x00FFFFFF;
  for (int x = 0; x < gen_bmp.width(); ++x) {
    for (int y = 0; y < gen_bmp.height(); ++y) {
      if ((*gen_bmp.getAddr32(x, y) & kAlphaMask) !=
          (*ref_bmp.getAddr32(x, y) & kAlphaMask)) {
        ++diff_pixels_count;
      }
    }
  }

  if (diff_pixels_count != 0) {
    LOG(ERROR) << "Images differ by pixel count: " << diff_pixels_count;
    return false;
  }

  return true;
}

// Returns a comma-separated list of the names of |layer|'s children in
// bottom-to-top stacking order.
std::string GetLayerChildrenNames(const Layer& layer) {
  std::string names;
  for (std::vector<Layer*>::const_iterator it = layer.children().begin();
       it != layer.children().end(); ++it) {
    if (!names.empty())
      names += ",";
    names += (*it)->name();
  }
  return names;
}

// There are three test classes in here that configure the Compositor and
// Layer's slightly differently:
// - LayerWithNullDelegateTest uses NullLayerDelegate as the LayerDelegate. This
//   is typically the base class you want to use.
// - LayerWithDelegateTest uses LayerDelegate on the delegates.
// - LayerWithRealCompositorTest when a real compositor is required for testing.
//    - Slow because they bring up a window and run the real compositor. This
//      is typically not what you want.

class ColoredLayer : public Layer, public LayerDelegate {
 public:
  explicit ColoredLayer(SkColor color)
      : Layer(Layer::LAYER_TEXTURED),
        color_(color) {
    set_delegate(this);
  }

  virtual ~ColoredLayer() { }

  // Overridden from LayerDelegate:
  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
    canvas->GetSkCanvas()->drawColor(color_);
  }

 private:
  SkColor color_;
};

class LayerWithRealCompositorTest : public testing::Test {
 public:
  LayerWithRealCompositorTest() {
    if (PathService::Get(gfx::DIR_TEST_DATA, &test_data_directory_)) {
      test_data_directory_ = test_data_directory_.AppendASCII("compositor");
    } else {
      LOG(ERROR) << "Could not open test data directory.";
    }
  }
  virtual ~LayerWithRealCompositorTest() {}

  // Overridden from testing::Test:
  virtual void SetUp() OVERRIDE {
    ui::DisableTestCompositor();
    const gfx::Rect host_bounds(10, 10, 500, 500);
    window_.reset(TestCompositorHost::Create(host_bounds));
    window_->Show();
  }

  virtual void TearDown() OVERRIDE {
  }

  Compositor* GetCompositor() {
    return window_->GetCompositor();
  }

  Layer* CreateLayer(Layer::LayerType type) {
    return new Layer(type);
  }

  Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) {
    Layer* layer = new ColoredLayer(color);
    layer->SetBounds(bounds);
    return layer;
  }

  Layer* CreateNoTextureLayer(const gfx::Rect& bounds) {
    Layer* layer = CreateLayer(Layer::LAYER_NOT_DRAWN);
    layer->SetBounds(bounds);
    return layer;
  }

  gfx::Canvas* CreateCanvasForLayer(const Layer* layer) {
    return gfx::Canvas::CreateCanvas(layer->bounds().size(), false);
  }

  void DrawTree(Layer* root) {
    GetCompositor()->SetRootLayer(root);
    GetCompositor()->Draw(false);
  }

  bool ReadPixels(SkBitmap* bitmap) {
    return GetCompositor()->ReadPixels(bitmap,
                                       gfx::Rect(GetCompositor()->size()));
  }

  void RunPendingMessages() {
    MessageLoopForUI::current()->RunAllPending();
  }

  // Invalidates the entire contents of the layer.
  void SchedulePaintForLayer(Layer* layer) {
    layer->SchedulePaint(
        gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height()));
  }

  const FilePath& test_data_directory() const { return test_data_directory_; }

 private:
  scoped_ptr<TestCompositorHost> window_;

  // The root directory for test files.
  FilePath test_data_directory_;

  DISALLOW_COPY_AND_ASSIGN(LayerWithRealCompositorTest);
};

// LayerDelegate that paints colors to the layer.
class TestLayerDelegate : public LayerDelegate {
 public:
  explicit TestLayerDelegate() : color_index_(0) {}
  virtual ~TestLayerDelegate() {}

  void AddColor(SkColor color) {
    colors_.push_back(color);
  }

  gfx::Size paint_size() const { return paint_size_; }
  int color_index() const { return color_index_; }

  // Overridden from LayerDelegate:
  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
    SkBitmap contents = canvas->AsCanvasSkia()->ExtractBitmap();
    paint_size_ = gfx::Size(contents.width(), contents.height());
    canvas->FillRect(colors_[color_index_],
                     gfx::Rect(gfx::Point(), paint_size_));
    color_index_ = (color_index_ + 1) % static_cast<int>(colors_.size());
  }

 private:
  std::vector<SkColor> colors_;
  int color_index_;
  gfx::Size paint_size_;

  DISALLOW_COPY_AND_ASSIGN(TestLayerDelegate);
};

// LayerDelegate that verifies that a layer was asked to update its canvas.
class DrawTreeLayerDelegate : public LayerDelegate {
 public:
  DrawTreeLayerDelegate() : painted_(false) {}
  virtual ~DrawTreeLayerDelegate() {}

  void Reset() {
    painted_ = false;
  }

  bool painted() const { return painted_; }

 private:
  // Overridden from LayerDelegate:
  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
    painted_ = true;
  }

  bool painted_;

  DISALLOW_COPY_AND_ASSIGN(DrawTreeLayerDelegate);
};

// The simplest possible layer delegate. Does nothing.
class NullLayerDelegate : public LayerDelegate {
 public:
  NullLayerDelegate() {}
  virtual ~NullLayerDelegate() {}

 private:
  // Overridden from LayerDelegate:
  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
  }

  DISALLOW_COPY_AND_ASSIGN(NullLayerDelegate);
};

// Remembers if it has been notified.
class TestCompositorObserver : public CompositorObserver {
 public:
  TestCompositorObserver() : notified_(false) {}

  bool notified() const { return notified_; }

  void Reset() { notified_ = false; }

 private:
  virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE {
    notified_ = true;
  }

  bool notified_;

  DISALLOW_COPY_AND_ASSIGN(TestCompositorObserver);
};

}  // namespace

#if defined(OS_WIN)
// These are disabled on windows as they don't run correctly on the buildbot.
// Reenable once we move to the real compositor.
#define MAYBE_Delegate DISABLED_Delegate
#define MAYBE_Draw DISABLED_Draw
#define MAYBE_DrawTree DISABLED_DrawTree
#define MAYBE_Hierarchy DISABLED_Hierarchy
#define MAYBE_HierarchyNoTexture DISABLED_HierarchyNoTexture
#define MAYBE_DrawPixels DISABLED_DrawPixels
#define MAYBE_SetRootLayer DISABLED_SetRootLayer
#define MAYBE_CompositorObservers DISABLED_CompositorObservers
#define MAYBE_ModifyHierarchy DISABLED_ModifyHierarchy
#define MAYBE_Opacity DISABLED_Opacity
#else
#define MAYBE_Delegate Delegate
#define MAYBE_Draw Draw
#define MAYBE_DrawTree DrawTree
#define MAYBE_Hierarchy Hierarchy
#define MAYBE_HierarchyNoTexture HierarchyNoTexture
#define MAYBE_DrawPixels DrawPixels
#define MAYBE_SetRootLayer SetRootLayer
#define MAYBE_CompositorObservers CompositorObservers
#define MAYBE_ModifyHierarchy ModifyHierarchy
#define MAYBE_Opacity Opacity
#endif

TEST_F(LayerWithRealCompositorTest, MAYBE_Draw) {
  scoped_ptr<Layer> layer(CreateColorLayer(SK_ColorRED,
                                           gfx::Rect(20, 20, 50, 50)));
  DrawTree(layer.get());
}

// Create this hierarchy:
// L1 - red
// +-- L2 - blue
// |   +-- L3 - yellow
// +-- L4 - magenta
//
TEST_F(LayerWithRealCompositorTest, MAYBE_Hierarchy) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));
  scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW,
                                        gfx::Rect(5, 5, 25, 25)));
  scoped_ptr<Layer> l4(CreateColorLayer(SK_ColorMAGENTA,
                                        gfx::Rect(300, 300, 100, 100)));

  l1->Add(l2.get());
  l1->Add(l4.get());
  l2->Add(l3.get());

  DrawTree(l1.get());
}

class LayerWithDelegateTest : public testing::Test, public CompositorDelegate {
 public:
  LayerWithDelegateTest() : schedule_draw_invoked_(false) {}
  virtual ~LayerWithDelegateTest() {}

  // Overridden from testing::Test:
  virtual void SetUp() OVERRIDE {
    ui::SetupTestCompositor();
    compositor_ = new ui::Compositor(this, NULL, gfx::Size(1000, 1000));
  }

  virtual void TearDown() OVERRIDE {
  }

  Compositor* compositor() { return compositor_.get(); }

  virtual Layer* CreateLayer(Layer::LayerType type) {
    return new Layer(type);
  }

  Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) {
    Layer* layer = new ColoredLayer(color);
    layer->SetBounds(bounds);
    return layer;
  }

  virtual Layer* CreateNoTextureLayer(const gfx::Rect& bounds) {
    Layer* layer = CreateLayer(Layer::LAYER_NOT_DRAWN);
    layer->SetBounds(bounds);
    return layer;
  }

  gfx::Canvas* CreateCanvasForLayer(const Layer* layer) {
    return gfx::Canvas::CreateCanvas(layer->bounds().size(), false);
  }

  void DrawTree(Layer* root) {
    compositor()->SetRootLayer(root);
    compositor()->Draw(false);
  }

  // Invalidates the entire contents of the layer.
  void SchedulePaintForLayer(Layer* layer) {
    layer->SchedulePaint(
        gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height()));
  }

  // Invokes DrawTree on the compositor.
  void Draw() {
    compositor_->Draw(false);
  }

  // CompositorDelegate overrides.
  virtual void ScheduleDraw() OVERRIDE {
    schedule_draw_invoked_ = true;
  }

 protected:
  // Set to true when ScheduleDraw (CompositorDelegate override) is invoked.
  bool schedule_draw_invoked_;

 private:
  scoped_refptr<ui::Compositor> compositor_;

  DISALLOW_COPY_AND_ASSIGN(LayerWithDelegateTest);
};

// L1
//  +-- L2
TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Simple) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));
  l1->Add(l2.get());
  DrawTree(l1.get());

  gfx::Point point1_in_l2_coords(5, 5);
  Layer::ConvertPointToLayer(l2.get(), l1.get(), &point1_in_l2_coords);
  gfx::Point point1_in_l1_coords(15, 15);
  EXPECT_EQ(point1_in_l1_coords, point1_in_l2_coords);

  gfx::Point point2_in_l1_coords(5, 5);
  Layer::ConvertPointToLayer(l1.get(), l2.get(), &point2_in_l1_coords);
  gfx::Point point2_in_l2_coords(-5, -5);
  EXPECT_EQ(point2_in_l2_coords, point2_in_l1_coords);
}

// L1
//  +-- L2
//       +-- L3
TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Medium) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));
  scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW,
                                        gfx::Rect(10, 10, 100, 100)));
  l1->Add(l2.get());
  l2->Add(l3.get());
  DrawTree(l1.get());

  gfx::Point point1_in_l3_coords(5, 5);
  Layer::ConvertPointToLayer(l3.get(), l1.get(), &point1_in_l3_coords);
  gfx::Point point1_in_l1_coords(25, 25);
  EXPECT_EQ(point1_in_l1_coords, point1_in_l3_coords);

  gfx::Point point2_in_l1_coords(5, 5);
  Layer::ConvertPointToLayer(l1.get(), l3.get(), &point2_in_l1_coords);
  gfx::Point point2_in_l3_coords(-15, -15);
  EXPECT_EQ(point2_in_l3_coords, point2_in_l1_coords);
}

TEST_F(LayerWithRealCompositorTest, MAYBE_Delegate) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorBLACK,
                                        gfx::Rect(20, 20, 400, 400)));
  GetCompositor()->SetRootLayer(l1.get());
  RunPendingMessages();

  TestLayerDelegate delegate;
  l1->set_delegate(&delegate);
  delegate.AddColor(SK_ColorWHITE);
  delegate.AddColor(SK_ColorYELLOW);
  delegate.AddColor(SK_ColorGREEN);

  l1->SchedulePaint(gfx::Rect(0, 0, 400, 400));
  RunPendingMessages();
  EXPECT_EQ(delegate.color_index(), 1);
  EXPECT_EQ(delegate.paint_size(), l1->bounds().size());

  l1->SchedulePaint(gfx::Rect(10, 10, 200, 200));
  RunPendingMessages();
  EXPECT_EQ(delegate.color_index(), 2);
  EXPECT_EQ(delegate.paint_size(), gfx::Size(200, 200));

  l1->SchedulePaint(gfx::Rect(5, 5, 50, 50));
  RunPendingMessages();
  EXPECT_EQ(delegate.color_index(), 0);
  EXPECT_EQ(delegate.paint_size(), gfx::Size(50, 50));
}

TEST_F(LayerWithRealCompositorTest, MAYBE_DrawTree) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));
  scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW,
                                        gfx::Rect(10, 10, 100, 100)));
  l1->Add(l2.get());
  l2->Add(l3.get());

  GetCompositor()->SetRootLayer(l1.get());
  RunPendingMessages();

  DrawTreeLayerDelegate d1;
  l1->set_delegate(&d1);
  DrawTreeLayerDelegate d2;
  l2->set_delegate(&d2);
  DrawTreeLayerDelegate d3;
  l3->set_delegate(&d3);

  l2->SchedulePaint(gfx::Rect(5, 5, 5, 5));
  RunPendingMessages();
  EXPECT_FALSE(d1.painted());
  EXPECT_TRUE(d2.painted());
  EXPECT_FALSE(d3.painted());
}

// Tests no-texture Layers.
// Create this hierarchy:
// L1 - red
// +-- L2 - NO TEXTURE
// |   +-- L3 - yellow
// +-- L4 - magenta
//
TEST_F(LayerWithRealCompositorTest, MAYBE_HierarchyNoTexture) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateNoTextureLayer(gfx::Rect(10, 10, 350, 350)));
  scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW,
                                        gfx::Rect(5, 5, 25, 25)));
  scoped_ptr<Layer> l4(CreateColorLayer(SK_ColorMAGENTA,
                                        gfx::Rect(300, 300, 100, 100)));

  l1->Add(l2.get());
  l1->Add(l4.get());
  l2->Add(l3.get());

  GetCompositor()->SetRootLayer(l1.get());
  RunPendingMessages();

  DrawTreeLayerDelegate d2;
  l2->set_delegate(&d2);
  DrawTreeLayerDelegate d3;
  l3->set_delegate(&d3);

  l2->SchedulePaint(gfx::Rect(5, 5, 5, 5));
  l3->SchedulePaint(gfx::Rect(5, 5, 5, 5));
  RunPendingMessages();

  // |d2| should not have received a paint notification since it has no texture.
  EXPECT_FALSE(d2.painted());
  // |d3| should have received a paint notification.
  EXPECT_TRUE(d3.painted());
}

class LayerWithNullDelegateTest : public LayerWithDelegateTest {
 public:
  LayerWithNullDelegateTest() {}
  virtual ~LayerWithNullDelegateTest() {}

  // Overridden from testing::Test:
  virtual void SetUp() OVERRIDE {
    LayerWithDelegateTest::SetUp();
    default_layer_delegate_.reset(new NullLayerDelegate());
  }

  virtual void TearDown() OVERRIDE {
  }

  Layer* CreateLayer(Layer::LayerType type) OVERRIDE {
    Layer* layer = new Layer(type);
    layer->set_delegate(default_layer_delegate_.get());
    return layer;
  }

  Layer* CreateTextureRootLayer(const gfx::Rect& bounds) {
    Layer* layer = CreateTextureLayer(bounds);
    compositor()->SetRootLayer(layer);
    return layer;
  }

  Layer* CreateTextureLayer(const gfx::Rect& bounds) {
    Layer* layer = CreateLayer(Layer::LAYER_TEXTURED);
    layer->SetBounds(bounds);
    return layer;
  }

  Layer* CreateNoTextureLayer(const gfx::Rect& bounds) OVERRIDE {
    Layer* layer = CreateLayer(Layer::LAYER_NOT_DRAWN);
    layer->SetBounds(bounds);
    return layer;
  }

  void RunPendingMessages() {
    MessageLoopForUI::current()->RunAllPending();
  }

 private:
  scoped_ptr<NullLayerDelegate> default_layer_delegate_;

  DISALLOW_COPY_AND_ASSIGN(LayerWithNullDelegateTest);
};

// Various visibile/drawn assertions.
TEST_F(LayerWithNullDelegateTest, Visibility) {
  scoped_ptr<Layer> l1(new Layer(Layer::LAYER_TEXTURED));
  scoped_ptr<Layer> l2(new Layer(Layer::LAYER_TEXTURED));
  scoped_ptr<Layer> l3(new Layer(Layer::LAYER_TEXTURED));
  l1->Add(l2.get());
  l2->Add(l3.get());

  NullLayerDelegate delegate;
  l1->set_delegate(&delegate);
  l2->set_delegate(&delegate);
  l3->set_delegate(&delegate);

  // Layers should initially be drawn.
  EXPECT_TRUE(l1->IsDrawn());
  EXPECT_TRUE(l2->IsDrawn());
  EXPECT_TRUE(l3->IsDrawn());
  EXPECT_EQ(1.f, l1->web_layer().opacity());
  EXPECT_EQ(1.f, l2->web_layer().opacity());
  EXPECT_EQ(1.f, l3->web_layer().opacity());

  compositor()->SetRootLayer(l1.get());

  Draw();

  l1->SetVisible(false);
  EXPECT_FALSE(l1->IsDrawn());
  EXPECT_FALSE(l2->IsDrawn());
  EXPECT_FALSE(l3->IsDrawn());
  EXPECT_EQ(0.f, l1->web_layer().opacity());

  l3->SetVisible(false);
  EXPECT_FALSE(l1->IsDrawn());
  EXPECT_FALSE(l2->IsDrawn());
  EXPECT_FALSE(l3->IsDrawn());
  EXPECT_EQ(0.f, l3->web_layer().opacity());

  l1->SetVisible(true);
  EXPECT_TRUE(l1->IsDrawn());
  EXPECT_TRUE(l2->IsDrawn());
  EXPECT_FALSE(l3->IsDrawn());
  EXPECT_EQ(1.f, l1->web_layer().opacity());
}

// Checks that stacking-related methods behave as advertised.
TEST_F(LayerWithNullDelegateTest, Stacking) {
  scoped_ptr<Layer> root(new Layer(Layer::LAYER_NOT_DRAWN));
  scoped_ptr<Layer> l1(new Layer(Layer::LAYER_TEXTURED));
  scoped_ptr<Layer> l2(new Layer(Layer::LAYER_TEXTURED));
  scoped_ptr<Layer> l3(new Layer(Layer::LAYER_TEXTURED));
  l1->set_name("1");
  l2->set_name("2");
  l3->set_name("3");
  root->Add(l3.get());
  root->Add(l2.get());
  root->Add(l1.get());

  // Layers' children are stored in bottom-to-top order.
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackAtTop(l3.get());
  EXPECT_EQ("2,1,3", GetLayerChildrenNames(*root.get()));

  root->StackAtTop(l1.get());
  EXPECT_EQ("2,3,1", GetLayerChildrenNames(*root.get()));

  root->StackAtTop(l1.get());
  EXPECT_EQ("2,3,1", GetLayerChildrenNames(*root.get()));

  root->StackAbove(l2.get(), l3.get());
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackAbove(l1.get(), l3.get());
  EXPECT_EQ("3,1,2", GetLayerChildrenNames(*root.get()));

  root->StackAbove(l2.get(), l1.get());
  EXPECT_EQ("3,1,2", GetLayerChildrenNames(*root.get()));

  root->StackAtBottom(l2.get());
  EXPECT_EQ("2,3,1", GetLayerChildrenNames(*root.get()));

  root->StackAtBottom(l3.get());
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackAtBottom(l3.get());
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackBelow(l2.get(), l3.get());
  EXPECT_EQ("2,3,1", GetLayerChildrenNames(*root.get()));

  root->StackBelow(l1.get(), l3.get());
  EXPECT_EQ("2,1,3", GetLayerChildrenNames(*root.get()));

  root->StackBelow(l3.get(), l2.get());
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackBelow(l3.get(), l2.get());
  EXPECT_EQ("3,2,1", GetLayerChildrenNames(*root.get()));

  root->StackBelow(l3.get(), l1.get());
  EXPECT_EQ("2,3,1", GetLayerChildrenNames(*root.get()));
}

// Verifies SetBounds triggers the appropriate painting/drawing.
TEST_F(LayerWithNullDelegateTest, SetBoundsSchedulesPaint) {
  scoped_ptr<Layer> l1(CreateTextureLayer(gfx::Rect(0, 0, 200, 200)));
  compositor()->SetRootLayer(l1.get());

  Draw();

  schedule_draw_invoked_ = false;
  l1->SetBounds(gfx::Rect(5, 5, 200, 200));

  // The CompositorDelegate (us) should have been told to draw for a move.
  EXPECT_TRUE(schedule_draw_invoked_);

  schedule_draw_invoked_ = false;
  l1->SetBounds(gfx::Rect(5, 5, 100, 100));

  // The CompositorDelegate (us) should have been told to draw for a resize.
  EXPECT_TRUE(schedule_draw_invoked_);
}

// Checks that pixels are actually drawn to the screen with a read back.
TEST_F(LayerWithRealCompositorTest, MAYBE_DrawPixels) {
  scoped_ptr<Layer> layer(CreateColorLayer(SK_ColorRED,
                                           gfx::Rect(0, 0, 500, 500)));
  scoped_ptr<Layer> layer2(CreateColorLayer(SK_ColorBLUE,
                                            gfx::Rect(0, 0, 500, 10)));

  layer->Add(layer2.get());

  DrawTree(layer.get());

  SkBitmap bitmap;
  gfx::Size size = GetCompositor()->size();
  ASSERT_TRUE(GetCompositor()->ReadPixels(&bitmap,
                                          gfx::Rect(0, 10,
                                          size.width(), size.height() - 10)));
  ASSERT_FALSE(bitmap.empty());

  SkAutoLockPixels lock(bitmap);
  bool is_all_red = true;
  for (int x = 0; is_all_red && x < 500; x++)
    for (int y = 0; is_all_red && y < 490; y++)
      is_all_red = is_all_red && (bitmap.getColor(x, y) == SK_ColorRED);

  EXPECT_TRUE(is_all_red);
}

// Checks the logic around Compositor::SetRootLayer and Layer::SetCompositor.
TEST_F(LayerWithRealCompositorTest, MAYBE_SetRootLayer) {
  Compositor* compositor = GetCompositor();
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));

  EXPECT_EQ(NULL, l1->GetCompositor());
  EXPECT_EQ(NULL, l2->GetCompositor());

  compositor->SetRootLayer(l1.get());
  EXPECT_EQ(compositor, l1->GetCompositor());

  l1->Add(l2.get());
  EXPECT_EQ(compositor, l2->GetCompositor());

  l1->Remove(l2.get());
  EXPECT_EQ(NULL, l2->GetCompositor());

  l1->Add(l2.get());
  EXPECT_EQ(compositor, l2->GetCompositor());

  compositor->SetRootLayer(NULL);
  EXPECT_EQ(NULL, l1->GetCompositor());
  EXPECT_EQ(NULL, l2->GetCompositor());
}

// Checks that compositor observers are notified when:
// - DrawTree is called,
// - After ScheduleDraw is called, or
// - Whenever SetBounds, SetOpacity or SetTransform are called.
// TODO(vollick): could be reorganized into compositor_unittest.cc
TEST_F(LayerWithRealCompositorTest, MAYBE_CompositorObservers) {
  scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(20, 20, 400, 400)));
  scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE,
                                        gfx::Rect(10, 10, 350, 350)));
  l1->Add(l2.get());
  TestCompositorObserver observer;
  GetCompositor()->AddObserver(&observer);

  // Explicitly called DrawTree should cause the observers to be notified.
  // NOTE: this call to DrawTree sets l1 to be the compositor's root layer.
  DrawTree(l1.get());
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // As should scheduling a draw and waiting.
  observer.Reset();
  l1->ScheduleDraw();
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // Moving, but not resizing, a layer should alert the observers.
  observer.Reset();
  l2->SetBounds(gfx::Rect(0, 0, 350, 350));
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // So should resizing a layer.
  observer.Reset();
  l2->SetBounds(gfx::Rect(0, 0, 400, 400));
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // Opacity changes should alert the observers.
  observer.Reset();
  l2->SetOpacity(0.5f);
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // So should setting the opacity back.
  observer.Reset();
  l2->SetOpacity(1.0f);
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  // Setting the transform of a layer should alert the observers.
  observer.Reset();
  Transform transform;
  transform.ConcatTranslate(-200, -200);
  transform.ConcatRotate(90.0f);
  transform.ConcatTranslate(200, 200);
  l2->SetTransform(transform);
  RunPendingMessages();
  EXPECT_TRUE(observer.notified());

  GetCompositor()->RemoveObserver(&observer);

  // Opacity changes should no longer alert the removed observer.
  observer.Reset();
  l2->SetOpacity(0.5f);
  RunPendingMessages();
  EXPECT_FALSE(observer.notified());
}

// Checks that modifying the hierarchy correctly affects final composite.
TEST_F(LayerWithRealCompositorTest, MAYBE_ModifyHierarchy) {
  GetCompositor()->WidgetSizeChanged(gfx::Size(50, 50));

  // l0
  //  +-l11
  //  | +-l21
  //  +-l12
  scoped_ptr<Layer> l0(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(0, 0, 50, 50)));
  scoped_ptr<Layer> l11(CreateColorLayer(SK_ColorGREEN,
                                         gfx::Rect(0, 0, 25, 25)));
  scoped_ptr<Layer> l21(CreateColorLayer(SK_ColorMAGENTA,
                                         gfx::Rect(0, 0, 15, 15)));
  scoped_ptr<Layer> l12(CreateColorLayer(SK_ColorBLUE,
                                         gfx::Rect(10, 10, 25, 25)));

  FilePath ref_img1 = test_data_directory().AppendASCII("ModifyHierarchy1.png");
  FilePath ref_img2 = test_data_directory().AppendASCII("ModifyHierarchy2.png");
  SkBitmap bitmap;

  l0->Add(l11.get());
  l11->Add(l21.get());
  l0->Add(l12.get());
  DrawTree(l0.get());
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  // WritePNGFile(bitmap, ref_img1);
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img1));

  l0->StackAtTop(l11.get());
  DrawTree(l0.get());
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  // WritePNGFile(bitmap, ref_img2);
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img2));

  // l11 is already at the front, should have no effect.
  l0->StackAtTop(l11.get());
  DrawTree(l0.get());
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img2));

  // l11 is already at the front, should have no effect.
  l0->StackAbove(l11.get(), l12.get());
  DrawTree(l0.get());
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img2));

  // should restore to original configuration
  l0->StackAbove(l12.get(), l11.get());
  DrawTree(l0.get());
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img1));
}

// Opacity is rendered correctly.
// Checks that modifying the hierarchy correctly affects final composite.
TEST_F(LayerWithRealCompositorTest, MAYBE_Opacity) {
  GetCompositor()->WidgetSizeChanged(gfx::Size(50, 50));

  // l0
  //  +-l11
  scoped_ptr<Layer> l0(CreateColorLayer(SK_ColorRED,
                                        gfx::Rect(0, 0, 50, 50)));
  scoped_ptr<Layer> l11(CreateColorLayer(SK_ColorGREEN,
                                         gfx::Rect(0, 0, 25, 25)));

  FilePath ref_img = test_data_directory().AppendASCII("Opacity.png");

  l11->SetOpacity(0.75);
  l0->Add(l11.get());
  DrawTree(l0.get());
  SkBitmap bitmap;
  ASSERT_TRUE(ReadPixels(&bitmap));
  ASSERT_FALSE(bitmap.empty());
  // WritePNGFile(bitmap, ref_img);
  EXPECT_TRUE(IsSameAsPNGFile(bitmap, ref_img));
}

namespace {

class SchedulePaintLayerDelegate : public LayerDelegate {
 public:
  SchedulePaintLayerDelegate() : paint_count_(0), layer_(NULL) {}

  virtual ~SchedulePaintLayerDelegate() {}

  void set_layer(Layer* layer) {
    layer_ = layer;
    layer_->set_delegate(this);
  }

  void SetSchedulePaintRect(const gfx::Rect& rect) {
    schedule_paint_rect_ = rect;
  }

  int GetPaintCountAndClear() {
    int value = paint_count_;
    paint_count_ = 0;
    return value;
  }

  const gfx::Rect& last_clip_rect() const { return last_clip_rect_; }

 private:
  // Overridden from LayerDelegate:
  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
    paint_count_++;
    if (!schedule_paint_rect_.IsEmpty()) {
      layer_->SchedulePaint(schedule_paint_rect_);
      schedule_paint_rect_ = gfx::Rect();
    }
    SkRect sk_clip_rect;
    if (canvas->GetSkCanvas()->getClipBounds(&sk_clip_rect))
      last_clip_rect_ = gfx::SkRectToRect(sk_clip_rect);
  }

  int paint_count_;
  Layer* layer_;
  gfx::Rect schedule_paint_rect_;
  gfx::Rect last_clip_rect_;

  DISALLOW_COPY_AND_ASSIGN(SchedulePaintLayerDelegate);
};

}  // namespace

// Verifies that if SchedulePaint is invoked during painting the layer is still
// marked dirty.
TEST_F(LayerWithDelegateTest, SchedulePaintFromOnPaintLayer) {
  scoped_ptr<Layer> root(CreateColorLayer(SK_ColorRED,
                                          gfx::Rect(0, 0, 500, 500)));
  SchedulePaintLayerDelegate child_delegate;
  scoped_ptr<Layer> child(CreateColorLayer(SK_ColorBLUE,
                                           gfx::Rect(0, 0, 200, 200)));
  child_delegate.set_layer(child.get());

  root->Add(child.get());

  SchedulePaintForLayer(root.get());
  DrawTree(root.get());
  schedule_draw_invoked_ = false;
  child->SchedulePaint(gfx::Rect(0, 0, 20, 20));
  child_delegate.GetPaintCountAndClear();
  EXPECT_TRUE(schedule_draw_invoked_);
  schedule_draw_invoked_ = false;
  // Set a rect so that when OnPaintLayer() is invoked SchedulePaint is invoked
  // again.
  child_delegate.SetSchedulePaintRect(gfx::Rect(10, 10, 30, 30));
  DrawTree(root.get());
  // |child| should have been painted once.
  EXPECT_EQ(1, child_delegate.GetPaintCountAndClear());
  // ScheduleDraw() should have been invoked.
  EXPECT_TRUE(schedule_draw_invoked_);
  // Because SchedulePaint() was invoked from OnPaintLayer() |child| should
  // still need to be painted.
  DrawTree(root.get());
  EXPECT_EQ(1, child_delegate.GetPaintCountAndClear());
  EXPECT_TRUE(child_delegate.last_clip_rect().Contains(
                  gfx::Rect(10, 10, 30, 30)));
}

} // namespace ui

redpajama_set_name: RedPajamaGithub


text:
from django.contrib.syndication.feeds import Feed
from django.core.exceptions import ObjectDoesNotExist

# tagging imports
from tagging.managers import ModelTaggedItemManager

# lfc imports
import lfc.utils
from lfc.models import BaseContent

class PageTagFeed(Feed):
    """Provides a feed for a given object restricted by given tags
    url, e.g.

    http://www.lfcproject.com/information/blog?tags=python
    """
    def get_object(self, bits):
        if len(bits) < 1:
            raise ObjectDoesNotExist

        return lfc.utils.traverse_object(self.request, "/".join(bits))

    def title(self, obj):
        portal = lfc.utils.get_portal()
        return "%s - %s" % (portal.title, obj.title)

    def link(self, obj):
        return obj.get_absolute_url()

    def description(self, obj):
        return obj.description

    def items(self, obj):
        paths_objs = obj.get_descendants()

        tags = self.request.GET.getlist("tags")
        if not tags:
            return paths_objs
        else:
            objs = []
            tagged_objs = ModelTaggedItemManager().with_all(tags, BaseContent.objects.all())
            for obj in tagged_objs:
                if obj.get_content_object() in paths_objs:
                    objs.append(obj.get_content_object())
            return objs


text:
import inspect
import os.path

import six
from yaql.language import expressions as yaql_expressions
from yaql.language import utils
from yaql.language import yaqltypes
from yaql import yaql_interface

from murano.dsl import constants
from murano.dsl import dsl_types
from murano.dsl import helpers

NO_VALUE = utils.create_marker('NO_VALUE')

def name(dsl_name):
    def wrapper(cls):
        cls.__murano_name = dsl_name
        return cls
    return wrapper

class MuranoType(yaqltypes.PythonType):
    def __init__(self, murano_class, nullable=False, version_spec=None):
        self.murano_class = murano_class
        self.version_spec = version_spec
        super(MuranoType, self).__init__(
            (dsl_types.MuranoObject, MuranoObjectInterface), nullable)

    def check(self, value, context, *args, **kwargs):
        if not super(MuranoType, self).check(
                value, context, *args, **kwargs):
            return False
        if isinstance(value, MuranoObjectInterface):
            value = value.object
        if value is None or isinstance(value, yaql_expressions.Expression):
            return True
        murano_class = self.murano_class
        if isinstance(murano_class, six.string_types):
            murano_class_name = murano_class
        else:
            murano_class_name = murano_class.name
        return helpers.is_instance_of(
            value, murano_class_name,
            self.version_spec or helpers.get_type(context))

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        result = super(MuranoType, self).convert(
            value, sender, context, function_spec, engine, *args, **kwargs)
        if isinstance(result, dsl_types.MuranoObject):
            return MuranoObjectInterface(result)
        return result

class ThisParameterType(yaqltypes.HiddenParameterType, yaqltypes.SmartType):
    def __init__(self):
        super(ThisParameterType, self).__init__(False)

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        this = helpers.get_this(context)
        executor = helpers.get_executor(context)
        return MuranoObjectInterface(this, executor)

class InterfacesParameterType(yaqltypes.HiddenParameterType,
                              yaqltypes.SmartType):
    def __init__(self):
        super(InterfacesParameterType, self).__init__(False)

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        this = helpers.get_this(context)
        return Interfaces(this)

class MuranoTypeName(yaqltypes.PythonType):
    def __init__(self, nullable=False, context=None):
        self._context = context
        super(MuranoTypeName, self).__init__(
            (dsl_types.MuranoTypeReference,
             six.string_types), nullable)

    def convert(self, value, sender, context, function_spec, engine,
                *args, **kwargs):
        context = self._context or context
        if isinstance(value, yaql_expressions.Expression):
            value = value(utils.NO_VALUE, context, engine)
        value = super(MuranoTypeName, self).convert(
            value, sender, context, function_spec, engine)
        if isinstance(value, six.string_types):
            if function_spec.meta.get(constants.META_MURANO_METHOD):
                context = helpers.get_caller_context(context)
            murano_type = helpers.get_type(context)
            value = helpers.get_class(
                murano_type.namespace_resolver.resolve_name(value),
                context).get_reference()
        return value

class MuranoObjectInterface(dsl_types.MuranoObjectInterface):
    class DataInterface(object):
        def __init__(self, object_interface):
            object.__setattr__(self, '__object_interface', object_interface)

        def __getattr__(self, item):
            oi = getattr(self, '__object_interface')
            return oi[item]

        def __setattr__(self, key, value):
            oi = getattr(self, '__object_interface')
            oi[key] = value

    class CallInterface(object):
        def __init__(self, mpl_object, executor):
            self.__object = mpl_object
            self.__executor = executor

        def __getattr__(self, item):
            executor = self.__executor or helpers.get_executor()

            def func(*args, **kwargs):
                self._insert_instruction()
                return self.__object.type.invoke(
                    item, executor, self.__object, args, kwargs,
                    helpers.get_context())
            return func

        @staticmethod
        def _insert_instruction():
            context = helpers.get_context()
            if context:
                frame = inspect.stack()[2]
                location = dsl_types.ExpressionFilePosition(
                    os.path.abspath(frame[1]), frame[2],
                    -1, frame[2], -1)
                context[constants.CTX_CURRENT_INSTRUCTION] = NativeInstruction(
                    frame[4][0].strip(), location)

    def __init__(self, mpl_object, executor=None):
        self.__object = mpl_object
        self.__executor = executor

    @property
    def object(self):
        return self.__object

    @property
    def id(self):
        return self.__object.object_id

    @property
    def owner(self):
        return self.__object.owner

    def find_owner(self, type, optional=False):
        context = helpers.get_context().create_child_context()
        yaql_engine = helpers.get_yaql_engine(context)
        context['$1'] = self.object
        context['$2'] = type
        expr_str = '$1.find($2)'
        if not optional:
            expr_str += '.require()'
        result = yaql_engine(expr_str).evaluate(context=context)
        return None if result is None else MuranoObjectInterface(result)

    @property
    def type(self):
        return self.__object.type

    @property
    def package(self):
        return self.type.package

    def data(self):
        return MuranoObjectInterface.DataInterface(self)

    @property
    def extension(self):
        return self.__object.extension

    def cast(self, murano_class, version_spec=None):
        return MuranoObjectInterface(
            helpers.cast(
                self.__object, murano_class,
                version_spec or helpers.get_type()),
            self.__executor)

    def is_instance_of(self, murano_class, version_spec=None):
        return helpers.is_instance_of(
            self.__object, murano_class,
            version_spec or helpers.get_type())

    def ancestors(self):
        return self.type.ancestors()

    def __getitem__(self, item):
        context = helpers.get_context()
        return to_mutable(
            self.__object.get_property(item, context),
            helpers.get_yaql_engine(context))

    def __setitem__(self, key, value):
        context = helpers.get_context()
        value = helpers.evaluate(value, context)
        self.__object.set_property(key, value, context)

    def __call__(self):
        return MuranoObjectInterface.CallInterface(
            self.object, self.__executor)

    def __repr__(self):
        return '<{0}>'.format(repr(self.object))

class Interfaces(object):
    def __init__(self, mpl_object):
        self.__object = mpl_object

    def yaql(self, receiver=utils.NO_VALUE):
        return yaql_interface.YaqlInterface(
            helpers.get_context(), helpers.get_yaql_engine(), receiver)

    def this(self):
        return self.methods(self.__object)

    def methods(self, mpl_object):
        if mpl_object is None:
            return None
        return MuranoObjectInterface(mpl_object)

    @property
    def execution_session(self):
        return helpers.get_execution_session()

    @property
    def caller(self):
        caller_context = helpers.get_caller_context()
        if caller_context is None:
            return None
        caller = helpers.get_this(caller_context)
        if caller is None:
            return None
        return MuranoObjectInterface(caller)

    @property
    def attributes(self):
        executor = helpers.get_executor()
        return executor.attribute_store

    @property
    def class_config(self):
        return self.__object.type.package.get_class_config(
            self.__object.type.name)

    @property
    def package_loader(self):
        return helpers.get_package_loader()

class NativeInstruction(object):
    def __init__(self, instruction, location):
        self.instruction = instruction
        self.source_file_position = location

    def __str__(self):
        return self.instruction

def to_mutable(obj, yaql_engine=None):
    if yaql_engine is None:
        yaql_engine = helpers.get_yaql_engine()

    def converter(value, limit_func, engine, rec):
        if isinstance(value, dsl_types.MuranoObject):
            return MuranoObjectInterface(value)
        else:
            return utils.convert_output_data(value, limit_func, engine, rec)

    limiter = lambda it: utils.limit_iterable(it, constants.ITERATORS_LIMIT)
    return converter(obj, limiter, yaql_engine, converter)

class MuranoObjectParameterType(yaqltypes.PythonType):
    def __init__(self, nullable=False, interface=False):
        self.interface = interface
        super(MuranoObjectParameterType, self).__init__(
            (dsl_types.MuranoObject, MuranoObjectInterface), nullable=nullable)

    def convert(self, value, *args, **kwargs):
        result = super(MuranoObjectParameterType, self).convert(
            value, *args, **kwargs)
        if result is None:
            return None
        if self.interface:
            if isinstance(result, MuranoObjectInterface):
                return result
            return MuranoObjectInterface(result)
        else:
            if isinstance(result, dsl_types.MuranoObject):
                return result
            return result.object


text:
In the previous chapter we learned about how [Hooks](../hooks/readme.md) are used as data-oriented middleware for services.

A slightly different kind of middleware is one of the key concepts behind Express and since Feathers just extends Express, it can use all existing Express middleware and features.

In this chapter we will look at how [services and Express middleware](express.md) play together and how [routing and versioning](routing.md) works for Feathers APIs.


text:
import {RubricsElement} from "./rubrics-element.js";
import {html} from "/webcomponents/assets/lit-element/lit-element.js";
import {repeat} from "/webcomponents/assets/lit-html/directives/repeat.js";
import {SakaiRubricStudentComment} from "./sakai-rubric-student-comment.js";

export class SakaiRubricCriterionStudent extends RubricsElement {

  static get properties() {

    return {
      criteria: { type: Array},
      totalPoints: Number,
      rubricAssociation: { attribute: "rubric-association", type: Object },
      evaluationDetails: { attribute: "evaluation-details", type: Array },
      preview: Boolean,
      entityId: { attribute: "entity-id", type: String },
    };
  }

  set criteria(newVal) {

    var oldVal = this._criteria;
    this._criteria = newVal;
    this.criteria.forEach(c => {

      if (!c.selectedvalue) {
        c.selectedvalue = 0;
      }
      c.pointrange = this.getHighLow(c.ratings, "points");
    });

    if (this.evaluationDetails) {
      this.handleEvaluationDetails();
    }
  }

  get criteria() { return this._criteria; }

  set evaluationDetails(newValue) {

    this._evaluationDetails = newValue;

    if (this.criteria) {
      this.handleEvaluationDetails();
    }
  }

  get evaluationDetails() { return this._evaluationDetails; }

  render() {

    return html`

        ${this.criteria.map(c => html`

${c.title}

${c.description}

                ${repeat(c.ratings, r => r.id, r => html`

${r.title}

${r.description}

                    ${r.points.toLocaleString(this.locale)} Points

                `)}

            ${!this.preview ? html`
              <sakai-rubric-student-comment criterion="${JSON.stringify(c)}"></sakai-rubric-student-comment>

                ${c.selectedvalue}
                ${!c.selectedRatingId ? "0" : ""}

              ${this.isOverridden(c.pointoverride,c.selectedvalue) ?
                html`<strong class="points-display">${c.pointoverride}</strong>`
                : html``}
            ` : html``}

        `)}

      ${!this.preview ? html`

<sr-lang key="total">Total</sr-lang>: ${this.totalPoints.toLocaleString(this.locale)}

      ` : html``}
    `;
  }

  handleEvaluationDetails() {

    this.evaluationDetails.forEach(ed => {

      this.criteria.forEach(c => {

        if (ed.criterionId === c.id) {

          var selectedRatingItem;
          c.ratings.forEach(r => {
            if (r.id == ed.selectedRatingId) {
              r.selected = true;
              selectedRatingItem = r;
            } else {
              r.selected = false;
            }
          });

          c.selectedRatingId = ed.selectedRatingId;
          if (ed.pointsAdjusted) {
            c.pointoverride = ed.points;
            c.selectedvalue = selectedRatingItem.points;
          } else {
            c.pointoverride = "";
            c.selectedvalue = ed.points;
          }

          c.comments = ed.comments;
          if (c.comments === "undefined") {
            // This can happen if undefined gets passed to the server when the evaluation is saved.
            c.comments = "";
          }
        }
      });
    });

    this.updateTotalPoints();
  }

  isOverridden(pointoverride, selected) {

    if (!this.rubricAssociation.parameters.fineTunePoints) {
      return false;
    }

    if ((pointoverride || pointoverride === 0) && (parseFloat(pointoverride) !== parseFloat(selected))) {
      return true;
    } else {
      return false;
    }
  }

  updateTotalPoints() {

    this.totalPoints = this.criteria.reduce((a, c) => {

      if (c.pointoverride) {
        return a + parseFloat(c.pointoverride);
      } else if (c.selectedvalue) {
        return a + parseFloat(c.selectedvalue);
      } else {
        return a;
      }
    }, 0);

    this.ready = true;
  }

  getOverriddenClass(ovrdvl,selected) {

    if (!this.rubricAssociation.parameters.fineTunePoints) {
      return '';
    }

    if ((ovrdvl || ovrdvl === 0) && (parseFloat(ovrdvl) !== parseFloat(selected))) {
      return 'strike';
    } else {
      return '';
    }
  }
}

customElements.define("sakai-rubric-criterion-student", SakaiRubricCriterionStudent);


text:
import {bind, wire} from 'hyperhtml';

/**
 * The HyperHTML view displaying toolbar and program image background.
 */
export default class Toolbar {
  /**
   * Default constructor for setting the values
   *
   * @param {HTMLElement} element - The HTML element to bind/adopt
   * @param {Object} [program=null] - The program to render
   * @param {Array<Object>} [channels=null] - The channels to show in the guide
   */
  constructor(element, program, channels) {
    this.element = element;
    this.program = program;
    this.channels = channels;

    // We handle the elements separately because HyperHTML computes the delta bad.
    this.headerTitle = element.querySelector('.mdc-toolbar__title');
    this.tabBar = element.querySelector('.mdc-tab-bar');
    this.headerBackground = element.querySelector('.header-background');
  }

  /**
   * Infer the tab style for a given channel.
   *
   * @param {Object} channel - The channel POJO to pick the channel from
   * @return {String} Style (mdc-tab with or without mdc-tab--active)
   */
  tabStyle(channel) {
    return `mdc-tab ${ channel.id === this.program.channelId ? 'mdc-tab--active' : ''}`;
  }

  /**
   * Renders the toolbar.
   *
   * @return {HTMLElement} The rendered element
   */
  render() {
    console.log('Render toolbar');

    const transform = `w_${this.element.clientWidth},h_${this.element.clientHeight},c_fit`;
    const url = `http://images.cdn.yle.fi/image/upload/${transform}/${this.program.imageId}.png`;
    const backgroundStyle = `
      background: url(${url}) no-repeat center bottom;
      background-size: cover;
      width: 100%;
      height: 100%;
    `;

    // Render the elements
    bind(this.headerTitle)`${ this.program.channel }`;
    bind(this.tabBar)`${
      this.channels.map((c) => wire(c)`
        <a class="${ this.tabStyle(c) }" href="${ `#channels/${c.id}` }">${ c.title }
      `)
    }`;
    bind(this.headerBackground)`<div style="${backgroundStyle}"></div>`;

    return this.element;
  }
}


text:
package io.katharsis.errorhandling.mapper;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;

public class ExceptionMapperTypeTest {

    @Test
    public void shouldFulfillHashCodeEqualsContract() throws Exception {
        EqualsVerifier.forClass(ExceptionMapperType.class).verify();
    }
}


text:
namespace crosapi {

namespace {
void EvaluateGetSessionStateResult(base::OnceClosure closure,
                                   mojom::GetSessionStateResultPtr expected,
                                   mojom::GetSessionStateResultPtr found) {
  ASSERT_EQ(expected->which(), found->which());
  if (expected->which() == mojom::GetSessionStateResult::Tag::ERROR_MESSAGE) {
    ASSERT_EQ(expected->get_error_message(), found->get_error_message());
  } else {
    ASSERT_EQ(expected->get_session_state(), found->get_session_state());
  }
  std::move(closure).Run();
}
}  // namespace

class LoginStateAshTest : public testing::Test {
 public:
  class MockSessionStateChangedEventObserver
      : public mojom::SessionStateChangedEventObserver {
   public:
    MockSessionStateChangedEventObserver() = default;
    ~MockSessionStateChangedEventObserver() = default;
    MOCK_METHOD1(OnSessionStateChanged, void(mojom::SessionState state));
    mojo::Receiver<mojom::SessionStateChangedEventObserver> receiver_{this};
  };

  LoginStateAshTest() : local_state_(TestingBrowserProcess::GetGlobal()) {}
  ~LoginStateAshTest() override = default;

  void SetUp() override {
    // |session_manager::SessionManager| is not initialized by default.
    // This sets up the static instance of |SessionManager| so
    // |session_manager::SessionManager::Get()| will return this particular
    // instance.
    session_manager_ = std::make_unique<session_manager::SessionManager>();
    login_state_ash_ = std::make_unique<LoginStateAsh>();
    login_state_ash_->BindReceiver(
        login_state_remote_.BindNewPipeAndPassReceiver());
  }

  void TearDown() override { login_state_ash_.reset(); }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  ScopedTestingLocalState local_state_;

  std::unique_ptr<session_manager::SessionManager> session_manager_;
  mojo::Remote<mojom::LoginState> login_state_remote_;
  std::unique_ptr<LoginStateAsh> login_state_ash_;
};

// Test that calling |GetSessionState()| returns the correctly mapped state.
TEST_F(LoginStateAshTest, GetSessionState) {
  const struct {
    const session_manager::SessionState session_state;
    const mojom::SessionState expected;
  } kTestCases[] = {
      {session_manager::SessionState::UNKNOWN, mojom::SessionState::kUnknown},
      {session_manager::SessionState::OOBE, mojom::SessionState::kInOobeScreen},
      {session_manager::SessionState::LOGIN_PRIMARY,
       mojom::SessionState::kInLoginScreen},
      {session_manager::SessionState::LOGGED_IN_NOT_ACTIVE,
       mojom::SessionState::kInLoginScreen},
      {session_manager::SessionState::LOGIN_SECONDARY,
       mojom::SessionState::kInLoginScreen},
      {session_manager::SessionState::ACTIVE, mojom::SessionState::kInSession},
      {session_manager::SessionState::LOCKED,
       mojom::SessionState::kInLockScreen},
      {session_manager::SessionState::RMA, mojom::SessionState::kInRmaScreen},
  };

  for (const auto& test : kTestCases) {
    session_manager_->SetSessionState(test.session_state);

    mojom::GetSessionStateResultPtr expected_result_ptr =
        mojom::GetSessionStateResult::New();
    expected_result_ptr->set_session_state(test.expected);

    base::RunLoop run_loop;
    login_state_remote_->GetSessionState(
        base::BindOnce(&EvaluateGetSessionStateResult, run_loop.QuitClosure(),
                       std::move(expected_result_ptr)));
    run_loop.Run();
  }
}

// Test that |OnSessionStateChanged| is dispatched when the session state
// changes.
TEST_F(LoginStateAshTest, OnSessionStateChangedIsDispatched) {
  testing::StrictMock<MockSessionStateChangedEventObserver> observer;

  login_state_remote_->AddObserver(
      observer.receiver_.BindNewPipeAndPassRemote());
  login_state_remote_.FlushForTesting();

  EXPECT_CALL(observer, OnSessionStateChanged(mojom::SessionState::kInSession))
      .Times(1);
  session_manager_->SetSessionState(session_manager::SessionState::ACTIVE);
  observer.receiver_.FlushForTesting();
}

// Test that |OnSessionStateChanged| is not dispatched when the mapped state is
// the same even when the |session_manager::SessionState| is different.
TEST_F(LoginStateAshTest, OnSessionStateChangedIsNotDispatchedWhenStateIsSame) {
  testing::StrictMock<MockSessionStateChangedEventObserver> observer;

  login_state_remote_->AddObserver(
      observer.receiver_.BindNewPipeAndPassRemote());
  login_state_remote_.FlushForTesting();

  EXPECT_CALL(observer,
              OnSessionStateChanged(mojom::SessionState::kInLoginScreen))
      .Times(1);
  session_manager_->SetSessionState(
      session_manager::SessionState::LOGIN_PRIMARY);
  observer.receiver_.FlushForTesting();

  session_manager_->SetSessionState(
      session_manager::SessionState::LOGGED_IN_NOT_ACTIVE);
  observer.receiver_.FlushForTesting();
}

}  // namespace crosapi


text:
package org.apache.hadoop.yarn.server.resourcemanager.recovery;

import com.google.protobuf.InvalidProtocolBufferException;
import io.hops.exception.StorageException;
import io.hops.exception.StorageInitializtionException;
import io.hops.metadata.util.RMStorageFactory;
import io.hops.metadata.util.RMUtilities;
import io.hops.metadata.util.YarnAPIStorageFactory;
import io.hops.metadata.yarn.dal.rmstatestore.ApplicationStateDataAccess;
import io.hops.metadata.yarn.dal.util.YARNOperationType;
import io.hops.metadata.yarn.entity.rmstatestore.ApplicationState;
import io.hops.transaction.handler.LightWeightRequestHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.api.records.URL;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMStateVersionProto;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.RMStateVersionPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Test class for the NDBRMStateStore class.
 */
public class TestNDBRMStateStore extends RMStateStoreTestBase {

  public static final Log LOG = LogFactory.getLog(TestNDBRMStateStore.class);
  private YarnConfiguration conf;

  class TestNDBRMStateStoreTester implements RMStateStoreHelper {

    TestNDBRMStoreInternal store;

    class TestNDBRMStoreInternal extends NDBRMStateStore {

      public TestNDBRMStoreInternal(Configuration conf) throws IOException {
        try {
          RMStorageFactory.setConfiguration(conf);
          init(conf);
          start();
        } catch (StorageInitializtionException ex) {
          LOG.error("Error initializing Configuration", ex);
        }
      }

      protected boolean applicationIdExists(String applicationId)
          throws IOException {
        boolean exists = false;
        io.hops.metadata.yarn.entity.rmstatestore.ApplicationState
            appStateFound = getApplicationState(applicationId);
        if (appStateFound != null) {
          exists = true;
        }
        return exists;
      }
    }

    @Override
    public RMStateStore getRMStateStore() throws Exception {
      return store = new TestNDBRMStoreInternal(new YarnConfiguration());
    }

    @Override
    public boolean isFinalStateValid() throws Exception {
      //TODO: Is returning true valid?
      return true;
    }

    @Override
    public void writeVersion(RMStateVersion version) throws Exception {
      store.storeVersion(((RMStateVersionPBImpl) version));
    }

    @Override
    public RMStateVersion getCurrentVersion() throws Exception {
      return store.getCurrentVersion();
    }

    @Override
    public boolean appExists(RMApp app) throws Exception {
      return store.applicationIdExists(app.getApplicationId().toString());
    }
  }

  /**
   * Basic testing method, iused RMStateStore testing interfaces.
   *
   * @throws Exception
   */
  @Test(timeout = 60000)
  public void testNDBRMStateStoreRealNDB() throws Exception {
    TestNDBRMStateStoreTester ndbTester = new TestNDBRMStateStoreTester();
    testRMAppStateStore(ndbTester);
    testRMDTSecretManagerStateStore(ndbTester);
    testCheckVersion(ndbTester);
    testAppDeletion(ndbTester);
  }

  /**
   * Runs before individual testing methods to initialize NDB connections.
   */
  @Before
  public void setup() throws IOException {
    LOG.info("HOP :: Setting up Factories");
    conf = new YarnConfiguration();
    try {
      YarnAPIStorageFactory.setConfiguration(conf);
      RMStorageFactory.setConfiguration(conf);
      RMUtilities.InitializeDB();
    } catch (StorageInitializtionException ex) {
      LOG.error("Error initializing Configuration", ex);
    }
  }

  /**
   * Test method for storing/retrieving RMStateVersion.
   *
   * @throws InvalidProtocolBufferException
   */
  @Test
  public void testVersionStoreRetrieve()
      throws InvalidProtocolBufferException, IOException {
    RMStateVersion versionStore = RMStateVersion.newInstance(1, 1);
    byte[] store =
        ((RMStateVersionPBImpl) versionStore).getProto().toByteArray();
    RMUtilities.setRMStateVersionLightweight(store);
    byte[] retrieve = RMUtilities.getRMStateVersionBinaryLightweight(0);
    RMStateVersion versionRetrieve =
        new RMStateVersionPBImpl(RMStateVersionProto.parseFrom(retrieve));
    Assert.assertEquals(versionStore.getMinorVersion(),
        versionRetrieve.getMinorVersion());
    Assert.assertEquals(versionStore.getMajorVersion(),
        versionRetrieve.getMajorVersion());
    Assert.assertEquals(versionStore, versionRetrieve);
  }

  /**
   * Creates appState, appAttemptState, security tokens. Modify before using
   * according to testing preferences.
   *
   * @throws IOException
   * @throws Exception
   */
  @Test
  public void testAppStateAndSecurityStoreRetrieve()
      throws IOException, Exception {
    //Store Application and Attempt
    ApplicationId appId =
        ApplicationId.newInstance(System.currentTimeMillis(), 1);
    ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(appId, 2);
    ApplicationStateDataPBImpl appState = new ApplicationStateDataPBImpl();
    ByteBuffer tokens = ByteBuffer.wrap("BOGUS".getBytes());
    URL url = URL.newInstance("scheme", "host", 1234, "file");
    long time = System.currentTimeMillis();
    LocalResource local = LocalResource.newInstance(url, LocalResourceType.FILE,
        LocalResourceVisibility.PUBLIC, time, time);
    Map<String, LocalResource> map1 = new HashMap<String, LocalResource>();
    map1.put("localresource", local);
    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("test", "test");
    Map<ApplicationAccessType, String> map3 =
        new HashMap<ApplicationAccessType, String>();
    map3.put(ApplicationAccessType.VIEW_APP, "type");
    List<String> commands = new ArrayList<String>();
    commands.add("command1");
    commands.add("command2");
    Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>();
    serviceData.put("BOGUS", ByteBuffer.wrap("BOGUS".getBytes()));
    ContainerLaunchContext clx = ContainerLaunchContext
        .newInstance(map1, map2, commands, serviceData, tokens, map3);
    appState.setApplicationSubmissionContext(ApplicationSubmissionContext
            .newInstance(appId, "appName", "queue", Priority.newInstance(1),
                clx, false, false, 1, Resource.newInstance(5012, 8)));

    ApplicationAttemptStateDataPBImpl appAttemptState =
        new ApplicationAttemptStateDataPBImpl();
    appAttemptState.setAttemptId(attemptId);
    appAttemptState.setDiagnostics("diagnostics");
    appAttemptState.setFinalApplicationStatus(FinalApplicationStatus.UNDEFINED);
    appAttemptState.setFinalTrackingUrl("http://testurl.se");
    String identifier = "identifier";
    String password = "password";

    appAttemptState.setMasterContainer(Container
            .newInstance(ContainerId.newInstance(attemptId, 1),
                NodeId.newInstance("host", 0), "host",
                Resource.newInstance(5012, 8), Priority.newInstance(1), Token
                .newInstance(identifier.getBytes(), "kind", password.getBytes(),
                    "service")));
    byte[] appArray = appState.getProto().toByteArray();
    byte[] appAttemptArray = appAttemptState.getProto().toByteArray();
    String appStateStr = appState.toString();
    String appAttemptStateStr = appAttemptState.toString();
    LOG.info(
        "HOP :: appState=" + appStateStr + ", byte length=" + appArray.length);
    LOG.info("HOP :: appAttemptState=" + appAttemptStateStr + ", byte length=" +
        appAttemptArray.length);
  }

  /**
   * Find applicationState by its applicationId string representation.
   *
   * @param applicationId
   * @return
   * @throws IOException
   */
  public static ApplicationState getApplicationState(final String applicationId)
      throws IOException {
    LightWeightRequestHandler getApplicationStateHandler =
        new LightWeightRequestHandler(YARNOperationType.TEST) {
          @Override
          public Object performTask() throws StorageException {
            connector.beginTransaction();
            connector.writeLock();
            ApplicationStateDataAccess DA =
                (ApplicationStateDataAccess) RMStorageFactory
                    .getDataAccess(ApplicationStateDataAccess.class);
            ApplicationState appState =
                (ApplicationState) DA.findByApplicationId(applicationId);

            connector.commit();
            return appState;
          }
        };
    return (ApplicationState) getApplicationStateHandler.handle();
  }

}


text:
package graph

import (
	"testing"

	"github.com/skydive-project/skydive/filters"
)

type simpleLinker struct {
	g *Graph
}

func (l *simpleLinker) GetABLinks(n *Node) (edges []*Edge) {
	n2 := l.g.GetNode("node2")
	if n2 == nil {
		return nil
	}

	edge := l.g.CreateEdge("", n, n2, Metadata{}, TimeUTC())
	return []*Edge{edge}
}

func (l *simpleLinker) GetBALinks(n *Node) []*Edge {
	return nil
}

type metadataLinker struct {
	g *Graph
}

func (l *metadataLinker) GetABLinks(n *Node) []*Edge {
	return nil
}

func (l *metadataLinker) GetBALinks(n *Node) (edges []*Edge) {
	filter := filters.NewAndFilter(
		filters.NewTermStringFilter("Name", "host1"),
	)
	m := NewElementFilter(filter)
	nodes := l.g.GetNodes(m)

	for _, node := range nodes {
		if node.ID != n.ID {
			edges = append(edges, l.g.CreateEdge("", node, n, Metadata{}, TimeUTC()))
		}
	}
	return
}

func TestSimpleLinker(t *testing.T) {
	g := newGraph(t)

	m1 := Metadata{
		"Type": "host",
		"Name": "host1",
	}

	m2 := Metadata{
		"Type": "host",
		"Name": "host2",
	}

	linker := NewResourceLinker(g, []ListenerHandler{g.eventHandler}, nil, &simpleLinker{g: g}, Metadata{"RelationType": "simpleLinker"})
	linker.Start()

	n1, _ := g.NewNode("node1", m1, "host")
	n2, _ := g.NewNode("node2", m2, "host")

	if g.AreLinked(n1, n2, Metadata{"RelationType": "simpleLinker"}) {
		t.Error("nodes should not be linked by an edge of type 'simpleLinker'")
	}

	g.DelNode(n1)
	g.AddNode(n1)

	if !g.AreLinked(n1, n2, Metadata{"RelationType": "simpleLinker"}) {
		t.Error("nodes should be linked by an edge of type 'simpleLinker'")
	}

	filter := filters.NewAndFilter(
		filters.NewTermStringFilter("RelationType", "simpleLinker"),
		filters.NewTermStringFilter("Parent", "node1"),
		filters.NewTermStringFilter("Child", "node2"),
	)
	m := NewElementFilter(filter)

	if l := len(g.GetEdges(m)); l != 1 {
		t.Errorf("there should be only one edge between node1 and node2, got %d", l)
	}

	g.DelNode(n1)
	g.DelNode(n2)

	g.AddNode(n2)
	g.AddNode(n1)

	if !g.AreLinked(n1, n2, Metadata{"RelationType": "simpleLinker"}) {
		t.Error("nodes should be linked by an edge of type 'simpleLinker'")
	}

	linker.Stop()

	g.DelNode(n1)
	g.DelNode(n2)
}

func TestMetadataLinker(t *testing.T) {
	g := newGraph(t)

	m1 := Metadata{
		"Type": "host",
		"Name": "host1",
	}

	m2 := Metadata{
		"Type": "host",
		"Name": "host2",
	}

	linker := NewResourceLinker(g, []ListenerHandler{g.eventHandler}, []ListenerHandler{g.eventHandler}, &metadataLinker{g: g}, Metadata{"RelationType": "metadataLinker"})
	linker.Start()

	n1, _ := g.NewNode("node1", m1, "host")
	n2, _ := g.NewNode("node2", m2, "host")

	if !g.AreLinked(n1, n2, Metadata{"RelationType": "metadataLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataLinker'")
	}

	g.AddMetadata(n1, "Name", "unknownHost")

	if g.AreLinked(n1, n2, Metadata{"RelationType": "metadataLinker"}) {
		t.Error("nodes should not be linked by an edge of type 'metadataLinker'")
	}
}

func TestMetadataIndexerLinker(t *testing.T) {
	g := newGraph(t)

	m1 := Metadata{
		"Type": "host",
		"Name": "host1",
	}

	m2 := Metadata{
		"Type": "host",
		"Name": "host2",
	}

	m3 := Metadata{
		"Type":       "host",
		"ParentHost": "host1",
	}

	hasNameFilter := NewElementFilter(filters.NewNotNullFilter("Name"))
	indexer1 := NewMetadataIndexer(g, g, hasNameFilter, "Name")
	indexer1.Start()

	hasParentNameFilter := NewElementFilter(filters.NewNotNullFilter("ParentHost"))
	indexer2 := NewMetadataIndexer(g, g, hasParentNameFilter, "ParentHost")
	indexer2.Start()

	linker := NewMetadataIndexerLinker(g, indexer1, indexer2, Metadata{"RelationType": "metadataIndexerLinker"})
	linker.Start()

	n1, _ := g.NewNode("node1", m1, "host")
	n2, _ := g.NewNode("node2", m2, "host")
	n3, _ := g.NewNode("node3", m3, "host")

	if !g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	g.AddMetadata(n3, "ParentHost", "host2")

	if !g.AreLinked(n2, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	if g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}
}

func TestMetadataIndexerLinkerWithArray(t *testing.T) {
	g := newGraph(t)

	vfCache := NewMetadataIndexer(g, g, nil, "VFS.MAC")
	vfCache.Start()

	macCache := NewMetadataIndexer(g, g, nil, "MAC")
	macCache.Start()

	vf1 := Metadata{
		"Name": "vf1",
		"VFS": []interface{}{
			map[string]interface{}{
				"MAC": "00:11:22:33:44:55",
			},
			map[string]interface{}{
				"MAC": "01:23:45:67:89:ab",
			},
		},
	}

	m1 := Metadata{
		"Name": "m1",
		"MAC":  "00:11:22:33:44:55",
	}

	m2 := Metadata{
		"Name": "m2",
		"MAC":  "01:23:45:67:89:ab",
	}

	linker := NewMetadataIndexerLinker(g, vfCache, macCache, Metadata{"RelationType": "metadataIndexerLinker"})
	linker.Start()

	n1, _ := g.NewNode(GenID(), vf1, "host")
	n2, _ := g.NewNode(GenID(), m1, "host")
	n3, _ := g.NewNode(GenID(), m2, "host")

	if !g.AreLinked(n1, n2, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	if !g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	g.SetMetadata(n3, Metadata{
		"Name": "m2",
		"MAC":  "01:23:45:67:89:af",
	})

	if !g.AreLinked(n1, n2, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	if g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}

	g.SetMetadata(n1, Metadata{
		"Name": "vf1",
		"VFS": []interface{}{
			map[string]interface{}{
				"MAC": "00:11:22:33:44:59",
			},
			map[string]interface{}{
				"MAC": "01:23:45:67:89:ab",
			},
		},
	})

	if g.AreLinked(n1, n2, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}

	if g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}

	g.SetMetadata(n1, Metadata{
		"Name": "vf1",
		"VFS": []interface{}{
			map[string]interface{}{
				"MAC": "00:11:22:33:44:59",
			},
			map[string]interface{}{
				"MAC": "01:23:45:67:89:af",
			},
		},
	})

	if g.AreLinked(n1, n2, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}

	if !g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be linked by an edge of type 'metadataIndexerLinker'")
	}

	g.SetMetadata(n1, Metadata{
		"Name": "vf1",
	})

	if g.AreLinked(n1, n2, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}

	if g.AreLinked(n1, n3, Metadata{"RelationType": "metadataIndexerLinker"}) {
		t.Error("nodes should be not linked by an edge of type 'metadataIndexerLinker'")
	}
}


text:
Crypto Implementations
======================

This is my collection of various cryptographic techniques implemented in various languages.
The idea is for these to be simple and thoroughly commented, with a document explaining how they work, so that you can learn how the magic of cryptography actually isn't really all that difficult to understand.
They're certainly not intended for production use. There are lots of better pre-existing libraries for that.

Documents
---------
Documentation is in here, as well as on my scribd account:

* [How to Implement AES in Ruby](http://www.scribd.com/doc/33686967/How-to-Implement-AES-in-Ruby)
* [How to Implement DES in Ruby](http://www.scribd.com/doc/33810102/How-to-Implement-DES-in-Ruby)

Blog
----
I also have these tutorials on my blog:

* [http://splinter.com.au/blog](http://splinter.com.au/blog)


text:
<oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <plugins pluginpoint="oracle.iam.platform.kernel.spi.EventHandler">
      <plugin pluginclass="com.blogspot.oraclestack.eventhandlers.UserLockPreprocessEH" version="1.0" name="UserLockPreprocessEH"/>
   </plugins>
</oimplugins>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CivilOctave: amarjeet@lba.gdy.club/namespacesagemath_1_1main.tex Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

CivilOctave

Main Page

Related Pages

Packages

Files

File List

File Members

amarjeet@lba.gdy.club

namespacesagemath_1_1main.tex

Go to the documentation of this file.

    1 \hypertarget{namespacesagemath_1_1main}{}\section{sagemath.\+main Namespace Reference}

    2 \label{namespacesagemath_1_1main}\index{sagemath.\+main@{sagemath.\+main}}

    3

    4

    5 This module contain code to process the data obtain from \hyperlink{input_8sage}{input.\+sage}.

    6

    7

    8

    9

   10 \subsection{Detailed Description}

   11 This module contain code to process the data obtain from \hyperlink{input_8sage}{input.\+sage}.

   12

   13 \begin{DoxyAuthor}{Author}

   14 amarjeet kapoor

   15 \end{DoxyAuthor}

<address class="footer">
Generated on Fri Dec 18 2015 16:53:12 for CivilOctave by

 1.8.11
</address>


text:
copyright:
  years: 2015, 2017
lastupdated: "2017-02-06"

---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}

# Versions disponibles
{: #available_versions}

{{site.data.keyword.Bluemix}} fournit tous les
[contextes d'exécution Node.js disponibles actuellement](http://nodejs.org/dist/). Pour ceux-ci, IBM propose des versions comportant des améliorations et des correctifs. Pour plus d'informations, voir [Mises à jour les plus récentes du pack de construction Node.js](/docs/runtimes/nodejs/updates.html).
{: shortdesc}

Le pack de construction IBM Node.js met en cache les versions de l'environnement d'exécution IBM. Par conséquent, si vous utilisez l'environnement d'exécution IBM SDK for Node.js dans votre
application, vous obtenez de meilleures performances pour l'application lorsque celle-ci est envoyée dans Bluemix.

Utilisez le paramètre **node** de la section **engines** du fichier **package.json** pour définir la version
de l'environnement d'exécution Node.js à exécuter.

Utilisez le paramètre **npm** de la section **engines** du fichier **package.json** pour définir une version de npm différente de celle qui est intégrée à Node.js.

Voir l'exemple suivant :

```
{
  "name": "myapp",
  "description": "this is my app",
  "version": "0.1",
  "engines": {
     "node": "4.2.4",
     "npm": "3.10.10"
  }
}
```
{: codeblock}

La version de Node doit toujours être précisée dans le fichier **package.json**. Si elle est omise, la version la plus
récente est utilisée.


text:
using System;
using System.Collections.Generic;
using Gallio.Common.Reflection;
using Gallio.Common.Reflection.Impl;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;

#if RESHARPER_31
using JetBrains.ReSharper.Editor;
using ReSharperDocumentRange = JetBrains.ReSharper.Editor.DocumentRange;
#else
using JetBrains.DocumentModel;
using ConstantValue = Gallio.Common.Reflection.ConstantValue;
using ReSharperDocumentRange = JetBrains.DocumentModel.DocumentRange;
#endif

namespace Gallio.ReSharperRunner.Reflection
{
    /// <summary>
    /// Base class for ReSharper reflection policies.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Provides additional support for getting the <see cref="IProject" /> and <see cref="IDeclaredElement" />
    /// associated with a code element, if available.
    /// </para>
    /// </remarks>
    public abstract class ReSharperReflectionPolicy : StaticReflectionPolicy
    {
        /// <summary>
        /// Gets the declared element resolver associated with the code element, or null if none.
        /// </summary>
        public static IDeclaredElementResolver GetDeclaredElementResolver(ICodeElementInfo codeElement)
        {
            StaticWrapper element = codeElement as StaticWrapper;
            if (element == null)
                return null;

            ReSharperReflectionPolicy policy = element.ReflectionPolicy as ReSharperReflectionPolicy;
            return policy != null ? policy.GetDeclaredElementResolver(element) : null;
        }

        /// <summary>
        /// Gets the project to which a code element belongs, or null if none.
        /// </summary>
        public static IProject GetProject(ICodeElementInfo codeElement)
        {
            StaticWrapper element = codeElement as StaticWrapper;
            if (element == null)
                return null;

            ReSharperReflectionPolicy policy = element.ReflectionPolicy as ReSharperReflectionPolicy;
            return policy != null ? policy.GetProject(element) : null;
        }

        /// <summary>
        /// Gets the declared element resolver associated with the code element, or null if none.
        /// </summary>
        protected abstract IDeclaredElementResolver GetDeclaredElementResolver(StaticWrapper element);

        /// <summary>
        /// Gets the project to which a code element belongs, or null if none.
        /// </summary>
        protected abstract IProject GetProject(StaticWrapper element);

        /// <summary>
        /// Converts constant values from a foreign form to a native one.
        /// </summary>
        /// <param name="value">The foreign constant value.</param>
        /// <param name="typeConstructor">A function for resolving types.</param>
        /// <returns>The native constant value.</returns>
        protected static ConstantValue ConvertConstantValue<TType>(object value, Common.Func<TType, ITypeInfo> typeConstructor)
            where TType : class
        {
            if (value == null)
                return new ConstantValue(Reflector.Wrap(typeof(object)), null);

            if (value != null)
            {
                TType type = value as TType;
                if (type != null)
                    return new ConstantValue(Reflector.Wrap(typeof(Type)), typeConstructor(type));

                Type valueType = value.GetType();
                if (valueType.IsArray)
                {
                    Array valueArray = (Array) value;
                    int length = valueArray.Length;
                    ConstantValue[] array = new ConstantValue[length];

                    for (int i = 0; i < length; i++)
                        array[i] = ConvertConstantValue(valueArray.GetValue(i), typeConstructor);

                    return new ConstantValue(Reflector.Wrap(MapConstantArrayElementType<TType>(valueType).MakeArrayType()), array);
                }
            }

            return new ConstantValue(Reflector.Wrap(value.GetType()), value);
        }

        /// <summary>
        /// Gets the location associated with a declared element.
        /// </summary>
        /// <param name="declaredElement">The declared element.</param>
        /// <returns>The resulting code location.</returns>
        protected static CodeLocation GetDeclaredElementSourceLocation(IDeclaredElement declaredElement)
        {
            IList<IDeclaration> decl = declaredElement.GetDeclarations();
            if (decl.Count == 0)
                return CodeLocation.Unknown;

            ReSharperDocumentRange range = decl[0].GetDocumentRange();
#if RESHARPER_31 || RESHARPER_40 || RESHARPER_41
            bool isValid = range.IsValid;
#else
            bool isValid = range.IsValid();
#endif
            if (isValid)
                return CodeLocation.Unknown;

#if RESHARPER_60_OR_NEWER
            var projectFile = decl[0].GetSourceFile().ToProjectFile();
#else
			var projectFile = decl[0].GetProjectFile();
#endif
            if (projectFile == null)
                return CodeLocation.Unknown;

            string filename = projectFile.Location.FullPath;
            DocumentCoords start = range.Document.GetCoordsByOffset(range.TextRange.StartOffset);

#if ! RESHARPER_50_OR_NEWER
            return new CodeLocation(filename, start.Line, start.Column);
#else
            return new CodeLocation(filename, (int) start.Line.Plus1(), (int) start.Column.Plus1());
#endif

        }

        private static Type MapConstantArrayElementType<TType>(Type arrayType)
        {
            Type elementType = arrayType.GetElementType();
            if (elementType.IsArray)
                return MapConstantArrayElementType<TType>(elementType).MakeArrayType();

            if (typeof(TType).IsAssignableFrom(elementType))
                return typeof(Type);

            return elementType;
        }
    }
}


text:
import sbt.Keys._
import sbt._
import sbt.io.Using

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.collection.mutable
import scala.collection.immutable.SortedSet
import scala.util.matching.Regex
import scala.xml.Elem
import scala.xml.transform.{RewriteRule, RuleTransformer}

final case class MonixScalaVersion(value: String) {
  lazy val parts = value.split("[.]").filter(_.nonEmpty).toList
}

object MonixScalaVersion {
  implicit object Ord extends Ordering[MonixScalaVersion] {
    override def compare(x: MonixScalaVersion, y: MonixScalaVersion): Int =
      -1 * compare(x.parts, y.parts)

    @tailrec
    private def compare(l1: List[String], l2: List[String]): Int =
      l1 match {
        case h1 :: r1 =>
          l2 match {
            case h2 :: r2 =>
              h1.compare(h2) match {
                case 0 => compare(r1, r2)
                case r => r
              }
            case Nil =>
              1
          }
        case Nil =>
          -1
      }
  }
}

final case class MonixCrossModule(
  jvm: Project => Project,
  js: Project => Project
)

object MonixBuildUtils {
  /**
    * Applies [[filterOutDependencyFromGeneratedPomXml]] to a list of multiple dependencies.
    */
  def filterOutMultipleDependenciesFromGeneratedPomXml(list: List[(String, Regex)]*) =
    list.foldLeft(List.empty[Def.Setting[_]]) { (acc, elem) =>
      acc ++ filterOutDependencyFromGeneratedPomXml(elem:_*)
    }

  /**
    * Filter out dependencies from the generated `pom.xml`.
    *
    * E.g. to exclude Scoverage:
    * {{{
    *   filterOutDependencyFromGeneratedPomXml("groupId" -> "org.scoverage")
    * }}}
    *
    * Or to exclude based on both `groupId` and `artifactId`:
    * {{{
    *   filterOutDependencyFromGeneratedPomXml("groupId" -> "io\\.estatico".r, "artifactId" -> "newtype".r)
    * }}}
    */
  def filterOutDependencyFromGeneratedPomXml(conditions: (String, Regex)*) = {
    def shouldExclude(e: Elem) =
      e.label == "dependency" && {
        conditions.forall { case (key, regex) =>
          e.child.exists(child => child.label == key && regex.findFirstIn(child.text).isDefined)
        }
      }

    if (conditions.isEmpty) Nil else {
      Seq(
        // For evicting Scoverage out of the generated POM
        // See: https://github.com/scoverage/sbt-scoverage/issues/153
        pomPostProcess := { (node: xml.Node) =>
          new RuleTransformer(new RewriteRule {
            override def transform(node: xml.Node): Seq[xml.Node] = node match {
              case e: Elem if shouldExclude(e) => Nil
              case _ => Seq(node)
            }
          }).transform(node).head
        }
      )
    }
  }

  /**
    * Reads the Scala versions from `.github/workflows/build.yml`, ensuring that
    * they are compatible with the selected SCALAJS_VERSION.
    */
  def scalaVersionsFromBuildYaml(manifest: File, customScalaJSVersion: Option[String]): SortedSet[MonixScalaVersion] = {
    Using.fileInputStream(manifest) { fis =>
      val yaml = new org.yaml.snakeyaml.Yaml()
        .loadAs(fis, classOf[java.util.Map[Any, Any]])
        .asScala

      val sjsAssocs = yaml
        .get("jobs")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("js-tests")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("strategy")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("matrix")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("include")
        .collect { case list: java.util.List[Any] @unchecked => list.asScala }
        .getOrElse(Iterable.empty[Any])
        .collect { case javaMap: java.util.Map[Any, Any]@unchecked =>
          val map = javaMap.asScala
          val scalaV = map.get("scala").collect { case s: String => s }
          val sjsV = map.get("scalajs").collect { case s: String => s }
          for (v1 <- sjsV; v2 <- scalaV) yield (v1, v2)
        }
        .flatMap(x => x)
        .toSeq

      val allSjsVersions = SortedSet(sjsAssocs.map(v => MonixScalaVersion(v._1)):_*)
      assert(allSjsVersions.nonEmpty, "Configuration Issue: Scala.js versions couldn't be extracted from build.yml")
      val sjsVersion = customScalaJSVersion.getOrElse(allSjsVersions.head.value)

      // Super ugly, but whatever get gets the job done
      val isVersionValid: String => Boolean = {
        val map = sjsAssocs.foldLeft(Map.empty[String, Map[String, Boolean]]) {
          case (acc, (v1, v2)) =>
            acc.updated(v1, acc.getOrElse(v1, Map.empty).updated(v2, true))
        }
        scalaVersion => {
          map.get(sjsVersion).flatMap(_.get(scalaVersion)).getOrElse(false)
        }
      }

      val scalaVersions = yaml
        .get("jobs")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("jvm-tests")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("strategy")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("matrix")
        .collect { case map: java.util.Map[Any, Any] @unchecked => map.asScala }
        .getOrElse(mutable.Map.empty[Any, Any])
        .get("scala")
        .collect { case list: java.util.List[Any] @unchecked => list.asScala }
        .getOrElse(Iterable.empty[Any])
        .collect { case v: String if isVersionValid(v) => MonixScalaVersion(v) }
        .toSeq

      assert(scalaVersions.nonEmpty, "build.yml is corrupt, suitable scala_version_* keys missing")
      SortedSet(scalaVersions:_*)
    }
  }
}


text:
const AdmZip = require('adm-zip');
const fs = require('fs');

module.exports = {
    readFileToBuffer: function (path) {
        return Buffer.from(fs.readFileSync(path));
    },
    extractProjectJson: function (path) {
        const zip = new AdmZip(path);
        const projectEntry = zip.getEntries().find(item => item.entryName.match(/project\.json/));
        if (projectEntry) {
            return JSON.parse(zip.readAsText(projectEntry.entryName, 'utf8'));
        }
        return null;
    },
    extractAsset: function (path, assetFileName) {
        const zip = new AdmZip(path);
        const assetEntry = zip.getEntries().find(item => item.entryName.match(assetFileName));
        return assetEntry.getData();
    }
};


text:
require 'teststrap'
require 'contributions'

context "Contributions public api with mocked .new" do
  hookup do
    stub(Contributions::GithubAPI).forks(anything) { ['r/r', 's/s'] }
  end

  setup { Contributions::Contributions.new(:username => 'charlietanksley') }

  context ".new" do
    context "assignments" do
      asserts_topic.assigns :username
      asserts_topic.assigns :repositories
    end

    asserts(:repositories).equals ['r/r', 's/s']
  end

  context ".add will add repositories" do
    context "if given a string" do
      setup { topic.add 'added/added' }
      asserts_topic.includes 'added/added'
    end

    context "if given an array" do
      setup { topic.add ['added/first', 'added/second'] }
      asserts_topic.includes 'added/first'
      asserts_topic.includes 'added/second'
    end
  end

  context ".contributions_as_hash" do
    context "does not reload hash if it already exists" do
      hookup do
        topic.contributions = Hash[:k => 'v']
        dont_allow(topic).load_contributions
      end

      asserts(:contributions_as_hash).equals Hash[:k => 'v']
    end

    context "calls #load_contributions if there aren't any contributions yet" do
      hookup { mock(topic).load_contributions { topic.contributions = Hash[:k => 'v'] } }
      asserts(:contributions_as_hash).equals Hash[:k => 'v']
    end
  end

  context ".only will trade out repositories" do
    context "if given a string" do
      setup { topic.only 'added/added' }
      asserts_topic.includes 'added/added'
      denies_topic.includes 'r/r'
      denies_topic.includes 's/s'
    end

    context "if given an array" do
      setup { topic.only ['added/first', 'added/second'] }
      asserts_topic.includes 'added/first'
      asserts_topic.includes 'added/second'
      denies_topic.includes 'r/r'
      denies_topic.includes 's/s'
    end
  end

  context ".project_names returns an array of project names" do
    asserts(:project_names).equals { ['r', 's'] }
  end

  context ".load_contributions" do
    context "actually calls out to get the contributions for each fork" do
      hookup do
        mock(Contributions::Git).contributions('Charlie Tanksley', 'r/r') { Hash[:sha => 1] }
        mock(Contributions::Git).contributions('Charlie Tanksley', 's/s') { Hash[:sha => 2] }
      end

      denies(:load_contributions).nil
    end

    context "returns a hash with repository names as keys" do
      hookup do
        stub(Contributions::Git).contributions('Charlie Tanksley', 'r/r') { Hash[:sha => 1] }
        stub(Contributions::Git).contributions('Charlie Tanksley', 's/s') { Hash[:sha => 2] }
      end

      asserts(:load_contributions).equals Hash['r/r' => Hash[:sha => 1], 's/s' => Hash[:sha => 2]]
    end

    context "stashes the results in an instance variable" do
      hookup do
        stub(Contributions::Git).contributions('Charlie Tanksley', 'r/r') { Hash[:sha => 1] }
        stub(Contributions::Git).contributions('Charlie Tanksley', 's/s') { Hash[:sha => 2] }
        topic.load_contributions
      end

      asserts(:contributions).equals Hash['r/r' => Hash[:sha => 1], 's/s' => Hash[:sha => 2]]
    end
  end

  context ".remove will drop repositories" do
    context "if given a string" do
      setup { topic.remove 'r/r' }
      denies_topic.includes 'added/added'
    end

    context "if given an array" do
      setup { topic.remove ['r/r', 's/s'] }
      denies_topic.includes 'r/r'
      denies_topic.includes 's/s'
    end
  end
end


text:
package p05_onlineRadioDatabase.exceptions;

public class InvalidSongException extends IllegalArgumentException {

    private static final String DEFAULT_MESSAGE = "Invalid song.";

    public InvalidSongException() {
        super(DEFAULT_MESSAGE);
    }

    public InvalidSongException(String message) {
        super(message);
    }
}


text:
<?php

namespace InstagramAPI\Response\Model;

class ThreadItem extends \InstagramAPI\Response
{
    /**
     * @var string
     */
    public $item_id;
    public $item_type;
    public $text;
    /**
     * @var Item
     */
    public $media_share;
    /**
     * @var ThreadItemMedia
     */
    public $media;
    /**
     * @var string
     */
    public $user_id;
    public $timestamp;
    public $client_context;
}


text:
using System;
using System.Collections.Generic;

namespace Exceptionless.Core.Models.Stats {
    public class EventTermStatsResult {
        public EventTermStatsResult() {
            Terms = new List<EventTermStatsItem>();
        }

        public DateTime Start { get; set; }
        public DateTime End { get; set; }
        public long Total { get; set; }
        public long Unique { get; set; }
        public long New { get; set; }
        public DateTime FirstOccurrence { get; set; }
        public DateTime LastOccurrence { get; set; }
        public ICollection<EventTermStatsItem> Terms { get; private set; }
    }
}


text:
var data = require('../data.json');

exports.create = function(req, res){
  res.render('user/create');
};

exports.edit = function(myData, res){
  var myQuery = myData.query;
  var searchField = "id";
  var results = [];
  var searchVal = 1;
  for (var i=0 ; i < data.users.length ; i++)
  {
    if (data.users[i][searchField] == searchVal) {
        data.users[i]["name"] = myQuery["name"];
        data.users[i]["bio"] = myQuery["bio"];
        data.users[i]["study_pref"]["time"] = myQuery["time"];
        data.users[i]["study_pref"]["personality"] = myQuery["personality"];
        data.users[i]["study_pref"]["loc"] = myQuery["loc"];
        data.users[i]["study_pref"]["chill"] = myQuery["chill"];
        results.push(data.users[i]);
    }
  }
  console.log(myQuery);

  res.render('user/show', results[0]);
}

exports.show = function(req, res){
  var id = req.params.id;
  var results = [];
  var searchField = "id";
  var searchVal = id;
  for (var i=0 ; i < data.users.length ; i++)
  {
    if (data.users[i][searchField] == searchVal) {
        results.push(data.users[i]);
    }
  }
  //console.log(results);
  res.render('user/show', results[0]);
};