text:
using cc::CheckerboardDrawQuad;
using cc::DelegatedFrameData;
using cc::DebugBorderDrawQuad;
using cc::DrawQuad;
using cc::FilterOperation;
using cc::FilterOperations;
using cc::IOSurfaceDrawQuad;
using cc::PictureDrawQuad;
using cc::RenderPass;
using cc::RenderPassId;
using cc::RenderPassDrawQuad;
using cc::ResourceProvider;
using cc::SharedQuadState;
using cc::SoftwareFrameData;
using cc::SolidColorDrawQuad;
using cc::SurfaceDrawQuad;
using cc::TextureDrawQuad;
using cc::TileDrawQuad;
using cc::TransferableResource;
using cc::StreamVideoDrawQuad;
using cc::YUVVideoDrawQuad;
using gfx::Transform;

namespace content {
namespace {

class CCMessagesTest : public testing::Test {
 protected:
  void Compare(const RenderPass* a, const RenderPass* b) {
    EXPECT_EQ(a->id, b->id);
    EXPECT_EQ(a->output_rect.ToString(), b->output_rect.ToString());
    EXPECT_EQ(a->damage_rect.ToString(), b->damage_rect.ToString());
    EXPECT_EQ(a->transform_to_root_target, b->transform_to_root_target);
    EXPECT_EQ(a->has_transparent_background, b->has_transparent_background);
  }

  void Compare(const SharedQuadState* a, const SharedQuadState* b) {
    EXPECT_EQ(a->content_to_target_transform, b->content_to_target_transform);
    EXPECT_EQ(a->content_bounds, b->content_bounds);
    EXPECT_EQ(a->visible_content_rect, b->visible_content_rect);
    EXPECT_EQ(a->clip_rect, b->clip_rect);
    EXPECT_EQ(a->is_clipped, b->is_clipped);
    EXPECT_EQ(a->opacity, b->opacity);
    EXPECT_EQ(a->blend_mode, b->blend_mode);
    EXPECT_EQ(a->sorting_context_id, b->sorting_context_id);
  }

  void Compare(const DrawQuad* a, const DrawQuad* b) {
    ASSERT_NE(DrawQuad::INVALID, a->material);
    ASSERT_EQ(a->material, b->material);
    EXPECT_EQ(a->rect.ToString(), b->rect.ToString());
    EXPECT_EQ(a->opaque_rect.ToString(), b->opaque_rect.ToString());
    EXPECT_EQ(a->visible_rect.ToString(), b->visible_rect.ToString());
    EXPECT_EQ(a->needs_blending, b->needs_blending);

    Compare(a->shared_quad_state, b->shared_quad_state);

    switch (a->material) {
      case DrawQuad::CHECKERBOARD:
        Compare(CheckerboardDrawQuad::MaterialCast(a),
                CheckerboardDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::DEBUG_BORDER:
        Compare(DebugBorderDrawQuad::MaterialCast(a),
                DebugBorderDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::IO_SURFACE_CONTENT:
        Compare(IOSurfaceDrawQuad::MaterialCast(a),
                IOSurfaceDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::PICTURE_CONTENT:
        Compare(PictureDrawQuad::MaterialCast(a),
                PictureDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::RENDER_PASS:
        Compare(RenderPassDrawQuad::MaterialCast(a),
                RenderPassDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::TEXTURE_CONTENT:
        Compare(TextureDrawQuad::MaterialCast(a),
                TextureDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::TILED_CONTENT:
        Compare(TileDrawQuad::MaterialCast(a),
                TileDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::SOLID_COLOR:
        Compare(SolidColorDrawQuad::MaterialCast(a),
                SolidColorDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::STREAM_VIDEO_CONTENT:
        Compare(StreamVideoDrawQuad::MaterialCast(a),
                StreamVideoDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::SURFACE_CONTENT:
        Compare(SurfaceDrawQuad::MaterialCast(a),
                SurfaceDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::YUV_VIDEO_CONTENT:
        Compare(YUVVideoDrawQuad::MaterialCast(a),
                YUVVideoDrawQuad::MaterialCast(b));
        break;
      case DrawQuad::INVALID:
        break;
    }
  }

  void Compare(const CheckerboardDrawQuad* a, const CheckerboardDrawQuad* b) {
    EXPECT_EQ(a->color, b->color);
    EXPECT_EQ(a->scale, b->scale);
  }

  void Compare(const DebugBorderDrawQuad* a, const DebugBorderDrawQuad* b) {
    EXPECT_EQ(a->color, b->color);
    EXPECT_EQ(a->width, b->width);
  }

  void Compare(const IOSurfaceDrawQuad* a, const IOSurfaceDrawQuad* b) {
    EXPECT_EQ(a->io_surface_size.ToString(), b->io_surface_size.ToString());
    EXPECT_EQ(a->io_surface_resource_id, b->io_surface_resource_id);
    EXPECT_EQ(a->orientation, b->orientation);
  }

  void Compare(const RenderPassDrawQuad* a, const RenderPassDrawQuad* b) {
    EXPECT_EQ(a->render_pass_id, b->render_pass_id);
    EXPECT_EQ(a->mask_resource_id, b->mask_resource_id);
    EXPECT_EQ(a->mask_uv_scale.ToString(), b->mask_uv_scale.ToString());
    EXPECT_EQ(a->mask_texture_size.ToString(), b->mask_texture_size.ToString());
    EXPECT_EQ(a->filters.size(), b->filters.size());
    for (size_t i = 0; i < a->filters.size(); ++i) {
      if (a->filters.at(i).type() != cc::FilterOperation::REFERENCE) {
        EXPECT_EQ(a->filters.at(i), b->filters.at(i));
      } else {
        EXPECT_EQ(b->filters.at(i).type(), cc::FilterOperation::REFERENCE);
        EXPECT_EQ(a->filters.at(i).image_filter()->countInputs(),
                  b->filters.at(i).image_filter()->countInputs());
      }
    }
    EXPECT_EQ(a->filters_scale, b->filters_scale);
    EXPECT_EQ(a->background_filters, b->background_filters);
  }

  void Compare(const SolidColorDrawQuad* a, const SolidColorDrawQuad* b) {
    EXPECT_EQ(a->color, b->color);
    EXPECT_EQ(a->force_anti_aliasing_off, b->force_anti_aliasing_off);
  }

  void Compare(const StreamVideoDrawQuad* a, const StreamVideoDrawQuad* b) {
    EXPECT_EQ(a->resource_id, b->resource_id);
    EXPECT_EQ(a->matrix, b->matrix);
  }

  void Compare(const SurfaceDrawQuad* a, const SurfaceDrawQuad* b) {
    EXPECT_EQ(a->surface_id, b->surface_id);
  }

  void Compare(const TextureDrawQuad* a, const TextureDrawQuad* b) {
    EXPECT_EQ(a->resource_id, b->resource_id);
    EXPECT_EQ(a->premultiplied_alpha, b->premultiplied_alpha);
    EXPECT_EQ(a->uv_top_left, b->uv_top_left);
    EXPECT_EQ(a->uv_bottom_right, b->uv_bottom_right);
    EXPECT_EQ(a->background_color, b->background_color);
    EXPECT_EQ(a->vertex_opacity[0], b->vertex_opacity[0]);
    EXPECT_EQ(a->vertex_opacity[1], b->vertex_opacity[1]);
    EXPECT_EQ(a->vertex_opacity[2], b->vertex_opacity[2]);
    EXPECT_EQ(a->vertex_opacity[3], b->vertex_opacity[3]);
    EXPECT_EQ(a->flipped, b->flipped);
    EXPECT_EQ(a->nearest_neighbor, b->nearest_neighbor);
  }

  void Compare(const TileDrawQuad* a, const TileDrawQuad* b) {
    EXPECT_EQ(a->resource_id, b->resource_id);
    EXPECT_EQ(a->tex_coord_rect, b->tex_coord_rect);
    EXPECT_EQ(a->texture_size, b->texture_size);
    EXPECT_EQ(a->swizzle_contents, b->swizzle_contents);
    EXPECT_EQ(a->nearest_neighbor, b->nearest_neighbor);
  }

  void Compare(const YUVVideoDrawQuad* a, const YUVVideoDrawQuad* b) {
    EXPECT_EQ(a->tex_coord_rect, b->tex_coord_rect);
    EXPECT_EQ(a->ya_tex_size, b->ya_tex_size);
    EXPECT_EQ(a->uv_tex_size, b->uv_tex_size);
    EXPECT_EQ(a->y_plane_resource_id, b->y_plane_resource_id);
    EXPECT_EQ(a->u_plane_resource_id, b->u_plane_resource_id);
    EXPECT_EQ(a->v_plane_resource_id, b->v_plane_resource_id);
    EXPECT_EQ(a->a_plane_resource_id, b->a_plane_resource_id);
    EXPECT_EQ(a->color_space, b->color_space);
  }

  void Compare(const TransferableResource& a, const TransferableResource& b) {
    EXPECT_EQ(a.id, b.id);
    EXPECT_EQ(a.format, b.format);
    EXPECT_EQ(a.filter, b.filter);
    EXPECT_EQ(a.size.ToString(), b.size.ToString());
    for (size_t i = 0; i < arraysize(a.mailbox_holder.mailbox.name); ++i) {
      EXPECT_EQ(a.mailbox_holder.mailbox.name[i],
                b.mailbox_holder.mailbox.name[i]);
    }
    EXPECT_EQ(a.mailbox_holder.texture_target, b.mailbox_holder.texture_target);
    EXPECT_EQ(a.mailbox_holder.sync_point, b.mailbox_holder.sync_point);
    EXPECT_EQ(a.allow_overlay, b.allow_overlay);
  }
};

TEST_F(CCMessagesTest, AllQuads) {
  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);

  Transform arbitrary_matrix1;
  arbitrary_matrix1.Scale(3, 3);
  arbitrary_matrix1.Translate(-5, 20);
  arbitrary_matrix1.Rotate(15);
  Transform arbitrary_matrix2;
  arbitrary_matrix2.Scale(10, -1);
  arbitrary_matrix2.Translate(20, 3);
  arbitrary_matrix2.Rotate(24);
  gfx::Rect arbitrary_rect1(-5, 9, 3, 15);
  gfx::Rect arbitrary_rect1_inside_rect1(-4, 12, 2, 8);
  gfx::Rect arbitrary_rect2_inside_rect1(-5, 11, 1, 2);
  gfx::Rect arbitrary_rect2(40, 23, 11, 7);
  gfx::Rect arbitrary_rect1_inside_rect2(44, 23, 4, 2);
  gfx::Rect arbitrary_rect2_inside_rect2(41, 25, 3, 5);
  gfx::Rect arbitrary_rect3(7, -53, 22, 19);
  gfx::Rect arbitrary_rect1_inside_rect3(10, -40, 6, 3);
  gfx::Rect arbitrary_rect2_inside_rect3(12, -51, 5, 12);
  gfx::Size arbitrary_size1(15, 19);
  gfx::Size arbitrary_size2(3, 99);
  gfx::Size arbitrary_size3(75, 1281);
  gfx::RectF arbitrary_rectf1(4.2f, -922.1f, 15.6f, 29.5f);
  gfx::SizeF arbitrary_sizef1(15.2f, 104.6f);
  gfx::PointF arbitrary_pointf1(31.4f, 15.9f);
  gfx::PointF arbitrary_pointf2(26.5f, -35.8f);
  gfx::Vector2dF arbitrary_vector2df1(16.2f, -85.1f);
  gfx::Vector2dF arbitrary_vector2df2(-8.3f, 0.47f);
  float arbitrary_float1 = 0.7f;
  float arbitrary_float2 = 0.3f;
  float arbitrary_float3 = 0.9f;
  float arbitrary_float_array[4] = {3.5f, 6.2f, 9.3f, 12.3f};
  bool arbitrary_bool1 = true;
  bool arbitrary_bool2 = false;
  bool arbitrary_bool3 = true;
  bool arbitrary_bool4 = true;
  int arbitrary_context_id1 = 12;
  int arbitrary_context_id2 = 57;
  int arbitrary_context_id3 = -503;
  int arbitrary_int = 5;
  SkColor arbitrary_color = SkColorSetARGB(25, 36, 47, 58);
  SkXfermode::Mode arbitrary_blend_mode1 = SkXfermode::kScreen_Mode;
  SkXfermode::Mode arbitrary_blend_mode2 = SkXfermode::kLighten_Mode;
  SkXfermode::Mode arbitrary_blend_mode3 = SkXfermode::kOverlay_Mode;
  IOSurfaceDrawQuad::Orientation arbitrary_orientation =
      IOSurfaceDrawQuad::UNFLIPPED;
  ResourceProvider::ResourceId arbitrary_resourceid1 = 55;
  ResourceProvider::ResourceId arbitrary_resourceid2 = 47;
  ResourceProvider::ResourceId arbitrary_resourceid3 = 23;
  ResourceProvider::ResourceId arbitrary_resourceid4 = 16;
  SkScalar arbitrary_sigma = SkFloatToScalar(2.0f);
  YUVVideoDrawQuad::ColorSpace arbitrary_color_space =
      YUVVideoDrawQuad::REC_601;

  RenderPassId child_id(30, 5);
  RenderPassId root_id(10, 14);

  FilterOperations arbitrary_filters1;
  arbitrary_filters1.Append(FilterOperation::CreateGrayscaleFilter(
      arbitrary_float1));
  skia::RefPtr<SkImageFilter> arbitrary_filter = skia::AdoptRef(
      SkBlurImageFilter::Create(arbitrary_sigma, arbitrary_sigma));
  arbitrary_filters1.Append(
      cc::FilterOperation::CreateReferenceFilter(arbitrary_filter));

  FilterOperations arbitrary_filters2;
  arbitrary_filters2.Append(FilterOperation::CreateBrightnessFilter(
      arbitrary_float2));

  scoped_ptr<RenderPass> child_pass_in = RenderPass::Create();
  child_pass_in->SetAll(child_id, arbitrary_rect2, arbitrary_rect3,
                        arbitrary_matrix2, arbitrary_bool2);

  scoped_ptr<RenderPass> child_pass_cmp = RenderPass::Create();
  child_pass_cmp->SetAll(child_id, arbitrary_rect2, arbitrary_rect3,
                         arbitrary_matrix2, arbitrary_bool2);

  scoped_ptr<RenderPass> pass_in = RenderPass::Create();
  pass_in->SetAll(root_id, arbitrary_rect1, arbitrary_rect2, arbitrary_matrix1,
                  arbitrary_bool1);

  SharedQuadState* shared_state1_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state1_in->SetAll(arbitrary_matrix1, arbitrary_size1, arbitrary_rect1,
                           arbitrary_rect2, arbitrary_bool1, arbitrary_float1,
                           arbitrary_blend_mode1, arbitrary_context_id1);

  scoped_ptr<RenderPass> pass_cmp = RenderPass::Create();
  pass_cmp->SetAll(root_id, arbitrary_rect1, arbitrary_rect2, arbitrary_matrix1,
                   arbitrary_bool1);

  SharedQuadState* shared_state1_cmp =
      pass_cmp->CreateAndAppendSharedQuadState();
  shared_state1_cmp->CopyFrom(shared_state1_in);

  CheckerboardDrawQuad* checkerboard_in =
      pass_in->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
  checkerboard_in->SetAll(shared_state1_in, arbitrary_rect1,
                          arbitrary_rect2_inside_rect1,
                          arbitrary_rect1_inside_rect1, arbitrary_bool1,
                          arbitrary_color, arbitrary_float1);
  pass_cmp->CopyFromAndAppendDrawQuad(checkerboard_in,
                                      checkerboard_in->shared_quad_state);

  DebugBorderDrawQuad* debugborder_in =
      pass_in->CreateAndAppendDrawQuad<DebugBorderDrawQuad>();
  debugborder_in->SetAll(shared_state1_in,
                         arbitrary_rect3,
                         arbitrary_rect1_inside_rect3,
                         arbitrary_rect2_inside_rect3,
                         arbitrary_bool1,
                         arbitrary_color,
                         arbitrary_int);
  pass_cmp->CopyFromAndAppendDrawQuad(debugborder_in,
                                      debugborder_in->shared_quad_state);

  IOSurfaceDrawQuad* iosurface_in =
      pass_in->CreateAndAppendDrawQuad<IOSurfaceDrawQuad>();
  iosurface_in->SetAll(shared_state1_in,
                       arbitrary_rect2,
                       arbitrary_rect2_inside_rect2,
                       arbitrary_rect1_inside_rect2,
                       arbitrary_bool1,
                       arbitrary_size1,
                       arbitrary_resourceid3,
                       arbitrary_orientation);
  pass_cmp->CopyFromAndAppendDrawQuad(iosurface_in,
                                      iosurface_in->shared_quad_state);

  SharedQuadState* shared_state2_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state2_in->SetAll(arbitrary_matrix2, arbitrary_size2, arbitrary_rect2,
                           arbitrary_rect3, arbitrary_bool1, arbitrary_float2,
                           arbitrary_blend_mode2, arbitrary_context_id2);
  SharedQuadState* shared_state2_cmp =
      pass_cmp->CreateAndAppendSharedQuadState();
  shared_state2_cmp->CopyFrom(shared_state2_in);

  RenderPassDrawQuad* renderpass_in =
      pass_in->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
  renderpass_in->SetAll(
      shared_state2_in, arbitrary_rect1, arbitrary_rect2_inside_rect1,
      arbitrary_rect1_inside_rect1, arbitrary_bool1, child_id,
      arbitrary_resourceid2, arbitrary_vector2df1, arbitrary_size1,
      arbitrary_filters1, arbitrary_vector2df2, arbitrary_filters2);
  pass_cmp->CopyFromAndAppendRenderPassDrawQuad(
      renderpass_in,
      renderpass_in->shared_quad_state,
      renderpass_in->render_pass_id);

  SharedQuadState* shared_state3_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state3_in->SetAll(arbitrary_matrix1, arbitrary_size3, arbitrary_rect3,
                           arbitrary_rect1, arbitrary_bool1, arbitrary_float3,
                           arbitrary_blend_mode3, arbitrary_context_id3);
  SharedQuadState* shared_state3_cmp =
      pass_cmp->CreateAndAppendSharedQuadState();
  shared_state3_cmp->CopyFrom(shared_state3_in);

  SolidColorDrawQuad* solidcolor_in =
      pass_in->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
  solidcolor_in->SetAll(shared_state3_in,
                        arbitrary_rect3,
                        arbitrary_rect1_inside_rect3,
                        arbitrary_rect2_inside_rect3,
                        arbitrary_bool1,
                        arbitrary_color,
                        arbitrary_bool2);
  pass_cmp->CopyFromAndAppendDrawQuad(solidcolor_in,
                                      solidcolor_in->shared_quad_state);

  StreamVideoDrawQuad* streamvideo_in =
      pass_in->CreateAndAppendDrawQuad<StreamVideoDrawQuad>();
  streamvideo_in->SetAll(shared_state3_in, arbitrary_rect2,
                         arbitrary_rect2_inside_rect2,
                         arbitrary_rect1_inside_rect2, arbitrary_bool1,
                         arbitrary_resourceid2, arbitrary_matrix1);
  pass_cmp->CopyFromAndAppendDrawQuad(streamvideo_in,
                                      streamvideo_in->shared_quad_state);

  cc::SurfaceId arbitrary_surface_id(3);
  SurfaceDrawQuad* surface_in =
      pass_in->CreateAndAppendDrawQuad<SurfaceDrawQuad>();
  surface_in->SetAll(shared_state3_in,
                     arbitrary_rect2,
                     arbitrary_rect2_inside_rect2,
                     arbitrary_rect1_inside_rect2,
                     arbitrary_bool1,
                     arbitrary_surface_id);
  pass_cmp->CopyFromAndAppendDrawQuad(surface_in,
                                      surface_in->shared_quad_state);

  TextureDrawQuad* texture_in =
      pass_in->CreateAndAppendDrawQuad<TextureDrawQuad>();
  texture_in->SetAll(shared_state3_in,
                     arbitrary_rect2,
                     arbitrary_rect2_inside_rect2,
                     arbitrary_rect1_inside_rect2,
                     arbitrary_bool1,
                     arbitrary_resourceid1,
                     arbitrary_bool2,
                     arbitrary_pointf1,
                     arbitrary_pointf2,
                     arbitrary_color,
                     arbitrary_float_array,
                     arbitrary_bool3,
                     arbitrary_bool4);
  pass_cmp->CopyFromAndAppendDrawQuad(texture_in,
                                      texture_in->shared_quad_state);

  TileDrawQuad* tile_in = pass_in->CreateAndAppendDrawQuad<TileDrawQuad>();
  tile_in->SetAll(shared_state3_in,
                  arbitrary_rect2,
                  arbitrary_rect2_inside_rect2,
                  arbitrary_rect1_inside_rect2,
                  arbitrary_bool1,
                  arbitrary_resourceid3,
                  arbitrary_rectf1,
                  arbitrary_size1,
                  arbitrary_bool2,
                  arbitrary_bool3);
  pass_cmp->CopyFromAndAppendDrawQuad(tile_in, tile_in->shared_quad_state);

  YUVVideoDrawQuad* yuvvideo_in =
      pass_in->CreateAndAppendDrawQuad<YUVVideoDrawQuad>();
  yuvvideo_in->SetAll(shared_state3_in,
                      arbitrary_rect1,
                      arbitrary_rect2_inside_rect1,
                      arbitrary_rect1_inside_rect1,
                      arbitrary_bool1,
                      arbitrary_rectf1,
                      arbitrary_size1,
                      arbitrary_size2,
                      arbitrary_resourceid1,
                      arbitrary_resourceid2,
                      arbitrary_resourceid3,
                      arbitrary_resourceid4,
                      arbitrary_color_space);
  pass_cmp->CopyFromAndAppendDrawQuad(yuvvideo_in,
                                      yuvvideo_in->shared_quad_state);

  // Make sure the in and cmp RenderPasses match.
  Compare(child_pass_cmp.get(), child_pass_in.get());
  ASSERT_EQ(0u, child_pass_in->shared_quad_state_list.size());
  ASSERT_EQ(0u, child_pass_in->quad_list.size());
  Compare(pass_cmp.get(), pass_in.get());
  ASSERT_EQ(3u, pass_in->shared_quad_state_list.size());
  ASSERT_EQ(10u, pass_in->quad_list.size());
  for (cc::SharedQuadStateList::ConstIterator
           cmp_iterator = pass_cmp->shared_quad_state_list.begin(),
           in_iterator = pass_in->shared_quad_state_list.begin();
       in_iterator != pass_in->shared_quad_state_list.end();
       ++cmp_iterator, ++in_iterator) {
    Compare(*cmp_iterator, *in_iterator);
  }
  for (auto in_iter = pass_in->quad_list.cbegin(),
            cmp_iter = pass_cmp->quad_list.cbegin();
       in_iter != pass_in->quad_list.cend();
       ++in_iter, ++cmp_iter)
    Compare(*cmp_iter, *in_iter);

  for (size_t i = 1; i < pass_in->quad_list.size(); ++i) {
    bool same_shared_quad_state_cmp =
        pass_cmp->quad_list.ElementAt(i)->shared_quad_state ==
        pass_cmp->quad_list.ElementAt(i - 1)->shared_quad_state;
    bool same_shared_quad_state_in =
        pass_in->quad_list.ElementAt(i)->shared_quad_state ==
        pass_in->quad_list.ElementAt(i - 1)->shared_quad_state;
    EXPECT_EQ(same_shared_quad_state_cmp, same_shared_quad_state_in);
  }

  DelegatedFrameData frame_in;
  frame_in.render_pass_list.push_back(child_pass_in.Pass());
  frame_in.render_pass_list.push_back(pass_in.Pass());

  IPC::ParamTraits<DelegatedFrameData>::Write(&msg, frame_in);

  DelegatedFrameData frame_out;
  PickleIterator iter(msg);
  EXPECT_TRUE(IPC::ParamTraits<DelegatedFrameData>::Read(&msg,
      &iter, &frame_out));

  // Make sure the out and cmp RenderPasses match.
  scoped_ptr<RenderPass> child_pass_out =
      frame_out.render_pass_list.take(frame_out.render_pass_list.begin());
  Compare(child_pass_cmp.get(), child_pass_out.get());
  ASSERT_EQ(0u, child_pass_out->shared_quad_state_list.size());
  ASSERT_EQ(0u, child_pass_out->quad_list.size());
  scoped_ptr<RenderPass> pass_out =
      frame_out.render_pass_list.take(frame_out.render_pass_list.begin() + 1);
  Compare(pass_cmp.get(), pass_out.get());
  ASSERT_EQ(3u, pass_out->shared_quad_state_list.size());
  ASSERT_EQ(10u, pass_out->quad_list.size());
  for (cc::SharedQuadStateList::ConstIterator
           cmp_iterator = pass_cmp->shared_quad_state_list.begin(),
           out_iterator = pass_out->shared_quad_state_list.begin();
       out_iterator != pass_out->shared_quad_state_list.end();
       ++cmp_iterator, ++out_iterator) {
    Compare(*cmp_iterator, *out_iterator);
  }
  for (auto out_iter = pass_out->quad_list.cbegin(),
            cmp_iter = pass_cmp->quad_list.cbegin();
       out_iter != pass_out->quad_list.cend();
       ++out_iter, ++cmp_iter)
    Compare(*cmp_iter, *out_iter);

  for (size_t i = 1; i < pass_out->quad_list.size(); ++i) {
    bool same_shared_quad_state_cmp =
        pass_cmp->quad_list.ElementAt(i)->shared_quad_state ==
        pass_cmp->quad_list.ElementAt(i - 1)->shared_quad_state;
    bool same_shared_quad_state_out =
        pass_out->quad_list.ElementAt(i)->shared_quad_state ==
        pass_out->quad_list.ElementAt(i - 1)->shared_quad_state;
    EXPECT_EQ(same_shared_quad_state_cmp, same_shared_quad_state_out);
  }
}

TEST_F(CCMessagesTest, UnusedSharedQuadStates) {
  scoped_ptr<RenderPass> pass_in = RenderPass::Create();
  pass_in->SetAll(RenderPassId(1, 1),
                  gfx::Rect(100, 100),
                  gfx::Rect(),
                  gfx::Transform(),
                  false);

  // The first SharedQuadState is used.
  SharedQuadState* shared_state1_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state1_in->SetAll(gfx::Transform(),
                           gfx::Size(1, 1),
                           gfx::Rect(),
                           gfx::Rect(),
                           false,
                           1.f,
                           SkXfermode::kSrcOver_Mode,
                           0);

  CheckerboardDrawQuad* quad1 =
      pass_in->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
  quad1->SetAll(shared_state1_in, gfx::Rect(10, 10), gfx::Rect(10, 10),
                gfx::Rect(10, 10), false, SK_ColorRED, 1.f);

  // The second and third SharedQuadStates are not used.
  SharedQuadState* shared_state2_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state2_in->SetAll(gfx::Transform(),
                           gfx::Size(2, 2),
                           gfx::Rect(),
                           gfx::Rect(),
                           false,
                           1.f,
                           SkXfermode::kSrcOver_Mode,
                           0);

  SharedQuadState* shared_state3_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state3_in->SetAll(gfx::Transform(),
                           gfx::Size(3, 3),
                           gfx::Rect(),
                           gfx::Rect(),
                           false,
                           1.f,
                           SkXfermode::kSrcOver_Mode,
                           0);

  // The fourth SharedQuadState is used.
  SharedQuadState* shared_state4_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state4_in->SetAll(gfx::Transform(),
                           gfx::Size(4, 4),
                           gfx::Rect(),
                           gfx::Rect(),
                           false,
                           1.f,
                           SkXfermode::kSrcOver_Mode,
                           0);

  CheckerboardDrawQuad* quad2 =
      pass_in->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
  quad2->SetAll(shared_state4_in, gfx::Rect(10, 10), gfx::Rect(10, 10),
                gfx::Rect(10, 10), false, SK_ColorRED, 1.f);

  // The fifth is not used again.
  SharedQuadState* shared_state5_in = pass_in->CreateAndAppendSharedQuadState();
  shared_state5_in->SetAll(gfx::Transform(),
                           gfx::Size(5, 5),
                           gfx::Rect(),
                           gfx::Rect(),
                           false,
                           1.f,
                           SkXfermode::kSrcOver_Mode,
                           0);

  // 5 SharedQuadStates go in.
  ASSERT_EQ(5u, pass_in->shared_quad_state_list.size());
  ASSERT_EQ(2u, pass_in->quad_list.size());

  DelegatedFrameData frame_in;
  frame_in.render_pass_list.push_back(pass_in.Pass());

  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  IPC::ParamTraits<DelegatedFrameData>::Write(&msg, frame_in);

  DelegatedFrameData frame_out;
  PickleIterator iter(msg);
  EXPECT_TRUE(
      IPC::ParamTraits<DelegatedFrameData>::Read(&msg, &iter, &frame_out));

  scoped_ptr<RenderPass> pass_out =
      frame_out.render_pass_list.take(frame_out.render_pass_list.begin());

  // 2 SharedQuadStates come out. The first and fourth SharedQuadStates were
  // used by quads, and so serialized. Others were not.
  ASSERT_EQ(2u, pass_out->shared_quad_state_list.size());
  ASSERT_EQ(2u, pass_out->quad_list.size());

  EXPECT_EQ(
      gfx::Size(1, 1).ToString(),
      pass_out->shared_quad_state_list.ElementAt(0)->content_bounds.ToString());
  EXPECT_EQ(
      gfx::Size(4, 4).ToString(),
      pass_out->shared_quad_state_list.ElementAt(1)->content_bounds.ToString());
}

TEST_F(CCMessagesTest, Resources) {
  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  gfx::Size arbitrary_size(757, 1281);
  unsigned int arbitrary_uint1 = 71234838;
  unsigned int arbitrary_uint2 = 53589793;

  GLbyte arbitrary_mailbox1[GL_MAILBOX_SIZE_CHROMIUM] = {
      1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2,
      3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4,
      5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4};

  GLbyte arbitrary_mailbox2[GL_MAILBOX_SIZE_CHROMIUM] = {
      0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 2, 4, 6, 8, 0, 0, 9,
      8, 7, 6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 2, 4, 6, 8, 0, 0, 9, 8, 7,
      6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 2, 4, 6, 8, 0, 0, 9, 8, 7};

  TransferableResource arbitrary_resource1;
  arbitrary_resource1.id = 2178312;
  arbitrary_resource1.format = cc::RGBA_8888;
  arbitrary_resource1.filter = 53;
  arbitrary_resource1.size = gfx::Size(37189, 123123);
  arbitrary_resource1.mailbox_holder.mailbox.SetName(arbitrary_mailbox1);
  arbitrary_resource1.mailbox_holder.texture_target = GL_TEXTURE_2D;
  arbitrary_resource1.mailbox_holder.sync_point = arbitrary_uint1;
  arbitrary_resource1.allow_overlay = true;

  TransferableResource arbitrary_resource2;
  arbitrary_resource2.id = 789132;
  arbitrary_resource2.format = cc::RGBA_4444;
  arbitrary_resource2.filter = 47;
  arbitrary_resource2.size = gfx::Size(89123, 23789);
  arbitrary_resource2.mailbox_holder.mailbox.SetName(arbitrary_mailbox2);
  arbitrary_resource2.mailbox_holder.texture_target = GL_TEXTURE_EXTERNAL_OES;
  arbitrary_resource2.mailbox_holder.sync_point = arbitrary_uint2;
  arbitrary_resource2.allow_overlay = false;

  scoped_ptr<RenderPass> renderpass_in = RenderPass::Create();
  renderpass_in->SetNew(
      RenderPassId(1, 1), gfx::Rect(), gfx::Rect(), gfx::Transform());

  DelegatedFrameData frame_in;
  frame_in.resource_list.push_back(arbitrary_resource1);
  frame_in.resource_list.push_back(arbitrary_resource2);
  frame_in.render_pass_list.push_back(renderpass_in.Pass());

  IPC::ParamTraits<DelegatedFrameData>::Write(&msg, frame_in);

  DelegatedFrameData frame_out;
  PickleIterator iter(msg);
  EXPECT_TRUE(IPC::ParamTraits<DelegatedFrameData>::Read(&msg,
      &iter, &frame_out));

  ASSERT_EQ(2u, frame_out.resource_list.size());
  Compare(arbitrary_resource1, frame_out.resource_list[0]);
  Compare(arbitrary_resource2, frame_out.resource_list[1]);
}

TEST_F(CCMessagesTest, SoftwareFrameData) {
  cc::SoftwareFrameData frame_in;
  frame_in.id = 3;
  frame_in.size = gfx::Size(40, 20);
  frame_in.damage_rect = gfx::Rect(5, 18, 31, 44);
  frame_in.bitmap_id = cc::SharedBitmap::GenerateId();

  // Write the frame.
  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  IPC::ParamTraits<cc::SoftwareFrameData>::Write(&msg, frame_in);

  // Read the frame.
  cc::SoftwareFrameData frame_out;
  PickleIterator iter(msg);
  EXPECT_TRUE(
      IPC::ParamTraits<SoftwareFrameData>::Read(&msg, &iter, &frame_out));
  EXPECT_EQ(frame_in.id, frame_out.id);
  EXPECT_EQ(frame_in.size.ToString(), frame_out.size.ToString());
  EXPECT_EQ(frame_in.damage_rect.ToString(), frame_out.damage_rect.ToString());
  EXPECT_EQ(frame_in.bitmap_id, frame_out.bitmap_id);
}

TEST_F(CCMessagesTest, SoftwareFrameDataMaxInt) {
  SoftwareFrameData frame_in;
  frame_in.id = 3;
  frame_in.size = gfx::Size(40, 20);
  frame_in.damage_rect = gfx::Rect(5, 18, 31, 44);
  frame_in.bitmap_id = cc::SharedBitmap::GenerateId();

  // Write the SoftwareFrameData by hand, make sure it works.
  {
    IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
    IPC::WriteParam(&msg, frame_in.id);
    IPC::WriteParam(&msg, frame_in.size);
    IPC::WriteParam(&msg, frame_in.damage_rect);
    IPC::WriteParam(&msg, frame_in.bitmap_id);
    SoftwareFrameData frame_out;
    PickleIterator iter(msg);
    EXPECT_TRUE(
        IPC::ParamTraits<SoftwareFrameData>::Read(&msg, &iter, &frame_out));
  }

  // The size of the frame may overflow when multiplied together.
  int max = std::numeric_limits<int>::max();
  frame_in.size = gfx::Size(max, max);

  // If size_t is larger than int, then int*int*4 can always fit in size_t.
  bool expect_read = sizeof(size_t) >= sizeof(int) * 2;

  // Write the SoftwareFrameData with the MaxInt size, if it causes overflow it
  // should fail.
  {
    IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
    IPC::WriteParam(&msg, frame_in.id);
    IPC::WriteParam(&msg, frame_in.size);
    IPC::WriteParam(&msg, frame_in.damage_rect);
    IPC::WriteParam(&msg, frame_in.bitmap_id);
    SoftwareFrameData frame_out;
    PickleIterator iter(msg);
    EXPECT_EQ(
        expect_read,
        IPC::ParamTraits<SoftwareFrameData>::Read(&msg, &iter, &frame_out));
  }
}

}  // namespace
}  // namespace content


text:
package bankaccount

import (
	"errors"
	"net/http"

	stripe "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/form"
)

// Client is used to invoke /bank_accounts APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

// New creates a new bank account.
func New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().New(params)
}

// New creates a new bank account.
func (c Client) New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	if params == nil {
		return nil, errors.New("params should not be nil")
	}

	var path string
	if params.Customer != nil {
		path = stripe.FormatURLPath("/v1/customers/%s/sources", stripe.StringValue(params.Customer))
	} else if params.Account != nil {
		path = stripe.FormatURLPath("/v1/accounts/%s/external_accounts", stripe.StringValue(params.Account))
	} else {
		return nil, errors.New("Invalid bank account params: either Customer or Account need to be set")
	}

	body := &form.Values{}

	// Note that we call this special append method instead of the standard one
	// from the form package. We should not use form's because doing so will
	// include some parameters that are undesirable here.
	params.AppendToAsSourceOrExternalAccount(body)

	// Because bank account creation uses the custom append above, we have to
	// make an explicit call using a form and CallRaw instead of the standard
	// Call (which takes a set of parameters).
	ba := &stripe.BankAccount{}
	err := c.B.CallRaw(http.MethodPost, path, c.Key, body, &params.Params, ba)
	return ba, err
}

// Get returns the details of a bank account.
func Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Get(id, params)
}

// Get returns the details of a bank account.
func (c Client) Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	if params == nil {
		return nil, errors.New("params should not be nil")
	}

	var path string
	if params != nil && params.Customer != nil {
		path = stripe.FormatURLPath("/v1/customers/%s/sources/%s", stripe.StringValue(params.Customer), id)
	} else if params != nil && params.Account != nil {
		path = stripe.FormatURLPath("/v1/accounts/%s/external_accounts/%s", stripe.StringValue(params.Account), id)
	} else {
		return nil, errors.New("Invalid bank account params: either Customer or Account need to be set")
	}

	ba := &stripe.BankAccount{}
	err := c.B.Call(http.MethodGet, path, c.Key, params, ba)
	return ba, err
}

// Update updates a bank account.
func Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Update(id, params)
}

// Update updates a bank account.
func (c Client) Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	if params == nil {
		return nil, errors.New("params should not be nil")
	}

	var path string
	if params.Customer != nil {
		path = stripe.FormatURLPath("/v1/customers/%s/sources/%s", stripe.StringValue(params.Customer), id)
	} else if params.Account != nil {
		path = stripe.FormatURLPath("/v1/accounts/%s/external_accounts/%s", stripe.StringValue(params.Account), id)
	} else {
		return nil, errors.New("Invalid bank account params: either Customer or Account need to be set")
	}

	ba := &stripe.BankAccount{}
	err := c.B.Call(http.MethodPost, path, c.Key, params, ba)
	return ba, err
}

// Del removes a bank account.
func Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Del(id, params)
}

// Del removes a bank account.
func (c Client) Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	if params == nil {
		return nil, errors.New("params should not be nil")
	}

	var path string
	if params.Customer != nil {
		path = stripe.FormatURLPath("/v1/customers/%s/sources/%s", stripe.StringValue(params.Customer), id)
	} else if params.Account != nil {
		path = stripe.FormatURLPath("/v1/accounts/%s/external_accounts/%s", stripe.StringValue(params.Account), id)
	} else {
		return nil, errors.New("Invalid bank account params: either Customer or Account need to be set")
	}

	ba := &stripe.BankAccount{}
	err := c.B.Call(http.MethodDelete, path, c.Key, params, ba)
	return ba, err
}

// List returns a list of bank accounts.
func List(params *stripe.BankAccountListParams) *Iter {
	return getC().List(params)
}

// List returns a list of bank accounts.
func (c Client) List(listParams *stripe.BankAccountListParams) *Iter {
	var path string
	var outerErr error

	// There's no bank accounts list URL, so we use one sources or external
	// accounts. An override on BankAccountListParam's `AppendTo` will add the
	// filter `object=bank_account` to make sure that only bank accounts come
	// back with the response.
	if listParams == nil {
		outerErr = errors.New("params should not be nil")
	} else if listParams.Customer != nil {
		path = stripe.FormatURLPath("/v1/customers/%s/sources",
			stripe.StringValue(listParams.Customer))
	} else if listParams.Account != nil {
		path = stripe.FormatURLPath("/v1/accounts/%s/external_accounts",
			stripe.StringValue(listParams.Account))
	} else {
		outerErr = errors.New("Invalid bank account params: either Customer or Account need to be set")
	}

	return &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &stripe.BankAccountList{}

		if outerErr != nil {
			return nil, list.ListMeta, outerErr
		}

		err := c.B.CallRaw(http.MethodGet, path, c.Key, b, p, list)

		ret := make([]interface{}, len(list.Data))
		for i, v := range list.Data {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}

// Iter is an iterator for bank accounts.
type Iter struct {
	*stripe.Iter
}

// BankAccount returns the bank account which the iterator is currently pointing to.
func (i *Iter) BankAccount() *stripe.BankAccount {
	return i.Current().(*stripe.BankAccount)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}

redpajama_set_name: RedPajamaGithub


text:
import Vue from 'vue';

import { sanitize } from 'dompurify';

import UsersCache from './lib/utils/users_cache';
import UserPopover from './vue_shared/components/user_popover/user_popover.vue';

const removeTitle = el => {
  // Removing titles so its not showing tooltips also

  el.dataset.originalTitle = '';
  el.setAttribute('title', '');
};

const getPreloadedUserInfo = dataset => {
  const userId = dataset.user || dataset.userId;
  const { username, name, avatarUrl } = dataset;

  return {
    userId,
    username,
    name,
    avatarUrl,
  };
};

/**
 * Adds a UserPopover component to the body, hands over as much data as the target element has in data attributes.
 * loads based on data-user-id more data about a user from the API and sets it on the popover
 */
const populateUserInfo = user => {
  const { userId } = user;

  return Promise.all([UsersCache.retrieveById(userId), UsersCache.retrieveStatusById(userId)]).then(
    ([userData, status]) => {
      if (userData) {
        Object.assign(user, {
          avatarUrl: userData.avatar_url,
          username: userData.username,
          name: userData.name,
          location: userData.location,
          bio: userData.bio,
          bioHtml: sanitize(userData.bio_html),
          workInformation: userData.work_information,
          loaded: true,
        });
      }

      if (status) {
        Object.assign(user, {
          status,
        });
      }

      return user;
    },
  );
};

const initializedPopovers = new Map();

export default (elements = document.querySelectorAll('.js-user-link')) => {
  const userLinks = Array.from(elements);
  const UserPopoverComponent = Vue.extend(UserPopover);

  return userLinks
    .filter(({ dataset }) => dataset.user || dataset.userId)
    .map(el => {
      if (initializedPopovers.has(el)) {
        return initializedPopovers.get(el);
      }

      const user = {
        location: null,
        bio: null,
        workInformation: null,
        status: null,
        loaded: false,
      };
      const renderedPopover = new UserPopoverComponent({
        propsData: {
          target: el,
          user,
        },
      });

      initializedPopovers.set(el, renderedPopover);

      renderedPopover.$mount();

      el.addEventListener('mouseenter', ({ target }) => {
        removeTitle(target);
        const preloadedUserInfo = getPreloadedUserInfo(target.dataset);

        Object.assign(user, preloadedUserInfo);

        if (preloadedUserInfo.userId) {
          populateUserInfo(user);
        }
      });
      el.addEventListener('mouseleave', ({ target }) => {
        target.removeAttribute('aria-describedby');
      });

      return renderedPopover;
    });
};


text:
<?php
	include("includes/header.php");
	include("includes/left.php");
    include("conf/require-functions.php");

?>

This page does not exist

<?php
	include("includes/footer.php");
?>


text:
#!/usr/bin/env bash

# Copyright 2017 Garrett D'Amore <garrett@damore.org>
# Copyright 2017 Capitar IT Group BV <info@capitar.com>
#
# This software is supplied under the terms of the MIT License, a
# copy of which should be located in the distribution where this
# file was obtained (LICENSE.txt).  A copy of the license may also be
# found online at https://opensource.org/licenses/MIT.

if [ "${COVERAGE}" != ON ]
then
	echo "Code coverage not enabled."
	exit 0
fi

GCOV=${GCOV:-gcov}

# capture all coverage info
lcov --gcov-tool ${GCOV} --directory . --capture --output-file coverage.info || exit 1

# filter out system information (C++ templates & inlines)
lcov --remove coverage.info '/usr/*' --output-file coverage.info || exit 1

# filter out the *test* program data
lcov --remove coverage.info '*/tests/*' --output-file coverage.info || exit 1

# emit debug stats.
lcov --list coverage.info

rm coverage.info

echo 0


text:
#import <Foundation/Foundation.h>

@class GULCCComponentContainer;

NS_ASSUME_NONNULL_BEGIN

/// Provides a system to clean up cached instances returned from the component system.
NS_SWIFT_NAME(ComponentLifecycleMaintainer)
@protocol GULCCComponentLifecycleMaintainer
/// Clean up any resources as they are about to be deallocated.
- (void)containerWillBeEmptied:(GULCCComponentContainer *)container;
@end

typedef _Nullable id (^GULCCComponentCreationBlock)(GULCCComponentContainer *container,
                                                    BOOL *isCacheable)
    NS_SWIFT_NAME(ComponentCreationBlock);

@class GULCCDependency;

/// Describes the timing of instantiation. Note: new components should default to lazy unless there
/// is a strong reason to be eager.
typedef NS_ENUM(NSInteger, GULCCInstantiationTiming) {
  GULCCInstantiationTimingLazy,
  GULCCInstantiationTimingAlwaysEager
} NS_SWIFT_NAME(InstantiationTiming);

/// A component that can be used from other components.
NS_SWIFT_NAME(Component)
@interface GULCCComponent : NSObject

/// The protocol describing functionality provided from the Component.
@property(nonatomic, strong, readonly) Protocol *protocol;

/// The timing of instantiation.
@property(nonatomic, readonly) GULCCInstantiationTiming instantiationTiming;

/// An array of dependencies for the component.
@property(nonatomic, copy, readonly) NSArray<GULCCDependency *> *dependencies;

/// A block to instantiate an instance of the component with the appropriate dependencies.
@property(nonatomic, copy, readonly) GULCCComponentCreationBlock creationBlock;

// There's an issue with long NS_SWIFT_NAMES that causes compilation to fail, disable clang-format
// for the next two methods.
// clang-format off

/// Creates a component with no dependencies that will be lazily initialized.
+ (instancetype)componentWithProtocol:(Protocol *)protocol
                        creationBlock:(GULCCComponentCreationBlock)creationBlock
NS_SWIFT_NAME(init(_:creationBlock:));

/// Creates a component to be registered with the component container.
///
/// @param protocol - The protocol describing functionality provided by the component.
/// @param instantiationTiming - When the component should be initialized. Use .lazy unless there's
///                              a good reason to be instantiated earlier.
/// @param dependencies - Any dependencies the `implementingClass` has, optional or required.
/// @param creationBlock - A block to instantiate the component with a container and a flag to cache
///                        the instance created or not.
/// @return A component that can be registered with the component container.
+ (instancetype)componentWithProtocol:(Protocol *)protocol
                  instantiationTiming:(GULCCInstantiationTiming)instantiationTiming
                         dependencies:(NSArray<GULCCDependency *> *)dependencies
                        creationBlock:(GULCCComponentCreationBlock)creationBlock
NS_SWIFT_NAME(init(_:instantiationTiming:dependencies:creationBlock:));

// clang-format on

/// Unavailable.
- (instancetype)init NS_UNAVAILABLE;

@end

NS_ASSUME_NONNULL_END


text:
var EventEmitter  = require('events').EventEmitter;
var http = require('http');
var et = require('elementtree');
var XML = et.XML;
var ElementTree = et.ElementTree;
var Element = et.Element;
var util = require('./util');
var Bucket = require('./Bucket');

module.exports = Connection;
require('util').inherits(Connection, EventEmitter);

function Connection(options) {
	EventEmitter.call(this);

	this.host = options.host || 'oss.aliyuncs.com';
	this.access_id = options.access_id || '';
	this.access_key = options.access_key || '';
	this._debug = options.debug;
}

Connection.prototype.listBuckets = function(callback) {
	var self = this;

	var method = 'GET';
	var path = '/';
	var resource = path;

	var headers = {};
	headers['Host'] = this.host;
	headers['Date'] = new Date().toUTCString();
	headers['Authorization'] = 'OSS ' + this.access_id + ':' + util.signHeader(this.access_key, method, resource, headers);

	var req_options = { host: headers['Host'], method: method, path: path, headers: headers };

	var req = http.request(req_options, function(res) {
		res._oss_chunk = '';

		res.on('data', function(chunk) {
			this._oss_chunk += chunk;
		});

		res.on('end', function() {
			if(self._debug)
				console.log('\nConnection.listBuckets res:\n', this, '\n');

			var err = new Error('Unknown Error');
			var buckets = null;

			if (this.headers['content-type'] === 'application/xml') {
				var xml = XML(this._oss_chunk);
				if (xml.tag === 'ListAllMyBucketsResult') {
					var result = util.xml2object(xml);
					var owner = { id: result.Owner.ID, name: result.Owner.DisplayName };

					buckets = [];

					if (result.Buckets.Bucket instanceof Array) {
						for (var i in result.Buckets.Bucket) {
							buckets.push(new Bucket(self, result.Buckets.Bucket[i].Name, result.Buckets.Bucket[i].CreationDate, owner));
						}
					} else if (result.Buckets) {
						buckets.push(new Bucket(self, result.Buckets.Bucket.Name, result.Buckets.Bucket.CreationDate, owner));
					}

					err = null;
				} else if (xml.tag === 'Error') {
					var result = util.xml2object(xml);
					err = new Error(result.Message);
					err.name = 'OssError';
					err.code = result.Code;
					err.errno = result.RequestId;
					err.syscall = 'Connection.listBucekts';
				}
			}

			callback(err, buckets);
		});
	});

	req.on('error' , function(err) {
		callback(err, null);
	});

	req.end();

	if (self._debug)
		console.log('\nConnection.listBuckets req:\n', req, '\n');

	return self;
}

Connection.prototype.queryBucket = function(name, callback) {
	var self = this;

	var method = 'GET';
	var path = '/?acl';
	var resource = '/' + name + path;

	var headers = {};
	headers['Host'] = name + '.' + this.host;
	headers['Date'] = new Date().toUTCString();
	headers['Authorization'] = 'OSS ' + this.access_id + ':' + util.signHeader(this.access_key, method, resource, headers);

	var req_options = { host: headers['Host'], method: method, path: path, headers: headers };

	var req = http.request(req_options, function(res) {
		res._oss_chunk = '';

		res.on('data', function(chunk) {
			this._oss_chunk += chunk;
		});

		res.on('end', function() {
			if(self._debug)
				console.log('\nConnection.queryBucket res:\n', this, '\n');

			var err = new Error('Unknown Error');
			var bucket = null;

			if (this.headers['content-type'] === 'application/xml') {
				var xml = XML(this._oss_chunk);
				if (xml.tag === 'AccessControlPolicy') {
					var result = util.xml2object(xml);
					var owner = { id: result.Owner.ID, name: result.Owner.DisplayName };

					bucket = new Bucket(self, name, undefined, owner);
					err = null;
				} else if (xml.tag === 'Error') {
					var result = util.xml2object(xml);
					err = new Error(result.Message);
					err.name = 'OssError';
					err.code = result.Code;
					err.errno = result.RequestId;
					err.syscall = 'Connection.queryBucket';
				}
			}

			callback(err, bucket);
		});
	});

	req.on('error' , function(err) {
		callback(err, null);
	});

	req.end();

	if (self._debug)
		console.log('\nConnection.queryBucket req:\n', req, '\n');

	return self;
}

Connection.prototype.createBucket = function(name, acl, callback) {
	var self = this;

	var method = 'PUT';
	var path = '/';
	var resource = '/' + name + path;

	var headers = {};
	headers['Host'] = name + '.' + this.host;
	headers['Date'] = new Date().toUTCString();
	if (acl)
		headers['x-oss-acl'] = acl;
	headers['Authorization'] = 'OSS ' + this.access_id + ':' + util.signHeader(this.access_key, method, resource, headers);
	headers['Content-Length'] = '0';

	var req_options = { host : headers['Host'], method : method, path : path, headers : headers };

	var req = http.request(req_options, function(res) {
		res._oss_chunk = '';

		res.on('data', function(chunk) {
			this._oss_chunk += chunk;
		});

		res.on('end', function() {
			if(self._debug)
				console.log('\nConnection.createBucket res:\n', this, '\n');

			var err = new Error('Unknown Error');
			var bucket = null;

			if (this.statusCode === 200) {
				bucket = new Bucket(self, name, undefined, undefined);
				err = null;
			} else if (this.headers['content-type'] === 'application/xml') {
				var xml = XML(this._oss_chunk);
				if (xml.tag === 'Error') {
					var result = util.xml2object(xml);
					err = new Error(result.Message);
					err.name = 'OssError';
					err.code = result.Code;
					err.errno = result.RequestId;
					err.syscall = 'Connection.createBucket';
				}
			}

			callback(err, bucket);
		});
	});

	req.on('error' , function(err) {
		callback(err, null);
	});

	req.end();

	if (self._debug)
		console.log('\nConnection.createBucket req:\n', req, '\n');

	return self;
}

Connection.prototype.deleteBucket = function(name, force, callback) {
	var self = this;

	var method = 'DELETE';
	var path = '/';
	var resource = '/' + name + path;

	var headers = {};
	headers['Host'] = name + '.' + this.host;
	headers['Date'] = new Date().toUTCString();
	headers['Authorization'] = 'OSS ' + this.access_id + ':' + util.signHeader(this.access_key, method, resource, headers);
	headers['Content-Length'] = '0';

	var req_options = { host : headers['Host'], method : method, path : path, headers : headers };

	var req = http.request(req_options, function(res) {
		res._oss_chunk = '';

		res.on('data', function(chunk) {
			this._oss_chunk += chunk;
		});

		res.on('end', function() {
			if(self._debug)
				console.log('\nConnection.deleteBucket res:\n', this, '\n');

			var err = new Error('Unknown Error');

			if (this.statusCode === 204) {
				err = null;
			} else if (this.headers['content-type'] === 'application/xml') {
				var xml = XML(this._oss_chunk);
				if (xml.tag === 'Error') {
					var result = util.xml2object(xml);
					err = new Error(result.Message);
					err.name = 'OssError';
					err.code = result.Code;
					err.errno = result.RequestId;
					err.syscall = 'Connection.deleteBucket';
				}
			}

			callback(err);
		});
	});

	req.on('error' , function(err) {
		callback(err);
	});

	req.end();

	if (self._debug)
		console.log('\nConnection.deleteBucket req:\n', req, '\n');

	return self;
}


text:
import logging
import sys
from collections import namedtuple

import numpy as np
import pandas as pd
from scipy.stats import chisquare

from . import categorizer as cat
from . import draw
from .ipf.ipf import calculate_constraints
from .ipu.ipu import household_weights

logger = logging.getLogger("synthpop")
FitQuality = namedtuple(
    'FitQuality',
    ('people_chisq', 'people_p'))
BlockGroupID = namedtuple(
    'BlockGroupID', ('state', 'county', 'tract', 'block_group'))

def enable_logging():
    handler = logging.StreamHandler(stream=sys.stdout)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)

def synthesize(h_marg, p_marg, h_jd, p_jd, h_pums, p_pums,
               marginal_zero_sub=.01, jd_zero_sub=.001, hh_index_start=0):

    # this is the zero marginal problem
    h_marg = h_marg.replace(0, marginal_zero_sub)
    p_marg = p_marg.replace(0, marginal_zero_sub)

    # zero cell problem
    h_jd.frequency = h_jd.frequency.replace(0, jd_zero_sub)
    p_jd.frequency = p_jd.frequency.replace(0, jd_zero_sub)

    # ipf for households
    logger.info("Running ipf for households")
    h_constraint, _ = calculate_constraints(h_marg, h_jd.frequency)
    h_constraint.index = h_jd.cat_id

    logger.debug("Household constraint")
    logger.debug(h_constraint)

    # ipf for persons
    logger.info("Running ipf for persons")
    p_constraint, _ = calculate_constraints(p_marg, p_jd.frequency)
    p_constraint.index = p_jd.cat_id

    logger.debug("Person constraint")
    logger.debug(p_constraint)

    # make frequency tables that the ipu expects
    household_freq, person_freq = cat.frequency_tables(p_pums, h_pums,
                                                       p_jd.cat_id,
                                                       h_jd.cat_id)

    # do the ipu to match person marginals
    logger.info("Running ipu")
    import time
    t1 = time.time()
    best_weights, fit_quality, iterations = household_weights(household_freq,
                                                              person_freq,
                                                              h_constraint,
                                                              p_constraint)
    logger.info("Time to run ipu: %.3fs" % (time.time()-t1))

    logger.debug("IPU weights:")
    logger.debug(best_weights.describe())
    logger.debug("Fit quality:")
    logger.debug(fit_quality)
    logger.debug("Number of iterations:")
    logger.debug(iterations)

    num_households = int(h_marg.groupby(level=0).sum().mean())
    print "Drawing %d households" % num_households

    best_chisq = np.inf

    return draw.draw_households(
        num_households, h_pums, p_pums, household_freq, h_constraint,
        p_constraint, best_weights, hh_index_start=hh_index_start)

def synthesize_all(recipe, num_geogs=None, indexes=None,
                   marginal_zero_sub=.01, jd_zero_sub=.001):
    """
    Returns
    -------
    households, people : pandas.DataFrame
    fit_quality : dict of FitQuality
        Keys are geographic IDs, values are namedtuples with attributes
        ``.household_chisq``, ``household_p``, ``people_chisq``,
        and ``people_p``.

    """
    print "Synthesizing at geog level: '{}' (number of geographies is {})".\
        format(recipe.get_geography_name(), recipe.get_num_geographies())

    if indexes is None:
        indexes = recipe.get_available_geography_ids()

    hh_list = []
    people_list = []
    cnt = 0
    fit_quality = {}
    hh_index_start = 0

    # TODO will parallelization work here?
    for geog_id in indexes:
        print "Synthesizing geog id:\n", geog_id

        h_marg = recipe.get_household_marginal_for_geography(geog_id)
        logger.debug("Household marginal")
        logger.debug(h_marg)

        p_marg = recipe.get_person_marginal_for_geography(geog_id)
        logger.debug("Person marginal")
        logger.debug(p_marg)

        h_pums, h_jd = recipe.\
            get_household_joint_dist_for_geography(geog_id)
        logger.debug("Household joint distribution")
        logger.debug(h_jd)

        p_pums, p_jd = recipe.get_person_joint_dist_for_geography(geog_id)
        logger.debug("Person joint distribution")
        logger.debug(p_jd)

        households, people, people_chisq, people_p = \
            synthesize(
                h_marg, p_marg, h_jd, p_jd, h_pums, p_pums,
                marginal_zero_sub=marginal_zero_sub, jd_zero_sub=jd_zero_sub,
                hh_index_start=hh_index_start)

        hh_list.append(households)
        people_list.append(people)
        key = BlockGroupID(
            geog_id['state'], geog_id['county'], geog_id['tract'],
            geog_id['block group'])
        fit_quality[key] = FitQuality(people_chisq, people_p)

        cnt += 1
        if len(households) > 0:
            hh_index_start = households.index.values[-1] + 1

        if num_geogs is not None and cnt >= num_geogs:
            break

    # TODO might want to write this to disk as we go?
    return (
        pd.concat(hh_list), pd.concat(people_list, ignore_index=True),
        fit_quality)


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

namespace Gamelogic
{
	/**
		This class provides useful extension methods for collections, mostly IEnumerable<T>.
	*/
	public static class CollectionExtensions
	{
		/**
			Returns all elements of the collection wich are of FilterType.
		*/
		public static IEnumerable<FilterType> FilterByType<T, FilterType>(this IEnumerable<T> list)
			where T : class
			where FilterType : class, T
		{
			return list.Where(item => item as FilterType != null).Cast<FilterType>();
		}

		/**
			Removes all the elements in the list that does not satisfy the predicate.
		*/
		public static void RemoveAllBut<T>(this List<T> list, Predicate<T> match)
		{
			Predicate<T> nomatch = item => !match(item);

			list.RemoveAll(nomatch);
		}

		/**
			Returns whether this collection is empty.
		*/
		public static bool IsEmpty<T>(this ICollection<T> collection)
		{
			return collection.Count == 0;
		}

		/**
			Add all elements of other to the given collection.
		*/
		public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> other)
		{
			if (other == null)//nothing to add
			{
				return;
			}

			foreach (var obj in other)
			{
				collection.Add(obj);
			}
		}

		/**
			Returns a pretty string representation of the given list. The resulting string looks something like
			<code>{a, b, c}</code>.
		*/
		public static string ListToString<T>(this IEnumerable<T> list)
		{
			if (list == null)
			{
				return "null";
			}

			var s = "{";

			s += list.Aggregate(s, (res, x) => res + ", " + x.ToString());
			s += "}";

			return s;
		}

		/**
			Returns an enumerable of all elements of the given list	but the first,
			keeping them in order.
		*/
		public static IEnumerable<T> ButFirst<T>(this IEnumerable<T> list)
		{
			return list.Skip(1);
		}

		/**
			Return an Enumarable off all elements in the given
			list but the last, keeping them in order.
		*/
		public static IEnumerable<T> ButLast<T>(this IEnumerable<T> list)
		{
			var lastX = default(T);
			var first = true;

			foreach (var x in list)
			{
				if (first)
				{
					first = false;
				}
				else
				{
					yield return lastX;
				}

				lastX = x;
			}
		}

		/**
			Finds the maximum element in the element as scored by the given function.
		*/
		public static T MaxBy<T>(this IEnumerable<T> collection, Func<T, IComparable> score)
		{
			return collection.Aggregate((x, y) => score(x).CompareTo(score(y)) > 0 ? x : y);
		}

		/**
			Returns a list with elements in order, but the first element is moved to the end.
		*/
		//TODO consider changing left to something more universal
		public static IEnumerable<T> RotateLeft<T>(this IEnumerable<T> list)
		{
			var enumeratedList = list as IList<T> ?? list.ToList();
			return enumeratedList.ButFirst().Concat(enumeratedList.Take(1));
		}

		/**
			Returns a list with elements in order, but the last element is moved to the front.
		*/
		public static IEnumerable<T> RotateRight<T>(this IEnumerable<T> list)
		{
			var enumeratedList = list as IList<T> ?? list.ToList();
			yield return enumeratedList.Last();

			foreach (var item in enumeratedList.ButLast())
			{
				yield return item;
			}
		}

		/**
			Returns a random element from the list.
		*/
		public static T RandomItem<T>(this IEnumerable<T> list)
		{
			return list.SampleRandom(1).First();
		}

		/**
			Returns a random sample from the list.
		*/
		public static IEnumerable<T> SampleRandom<T>(this IEnumerable<T> list, int sampleCount)
		{
			/* Reservoir sampling. */
			var samples = new List<T>();

			//Must be 1, otherwise we have to use Range(0, i + 1)
			var i = 1;

			foreach (var item in list)
			{
				if (i <= sampleCount)
				{
					samples.Add(item);
				}
				else
				{
					// Randomly replace elements in the reservoir with a decreasing probability.
					var r = UnityEngine.Random.Range(0, i);

					if (r < sampleCount)
					{
						samples[r] = item;
					}
				}

				i++;
			}

			return samples;
		}

		/**
			Shuffles a list.
		*/
		public static void Shuffle<T>(this IList<T> list)
		{
		    var rng = new Random();
		    var n = list.Count;

			while (n > 1)
			{
		        n--;
		        var k = rng.Next(n + 1);
		        var value = list[k];
		        list[k] = list[n];
		        list[n] = value;
		    }
		}
	}
}


text:
var Index = require('../app/controllers/index')
var User = require('../app/controllers/user')
var Movie = require('../app/controllers/movie')
var Comment = require('../app/controllers/comment')
var Category = require('../app/controllers/category')

module.exports = function (app) {
  //pre handle user
  app.use(function (req, res, next) {
    var _user = req.session.user
    app.locals.user = _user
    next()
  })
//index page
app.get('/', Index.index)
app.get('/results', Index.search)

//User
app.post('/user/signin',User.signin)
app.get('/logout',User.logout)
app.get('/signin',User.showSignin)
app.get('/signup',User.showSignup)
app.post('/user/signup',User.signup)
app.get('/admin/user/list', User.signinRequired, User.adminRequired,User.list)
//Movie
app.get('/movie/:id', Movie.detail)
app.get('/admin/movie/new', User.signinRequired, User.adminRequired,Movie.new)
app.get('/admin/movie/update/:id', User.signinRequired, User.adminRequired,Movie.update)
app.post('/admin/movie', User.signinRequired, User.adminRequired, Movie.savePoster, Movie.save)
app.get('/admin/movie/list', User.signinRequired, User.adminRequired,Movie.list)
app.delete("/admin/movie/list", User.signinRequired, User.adminRequired,Movie.delete)
app.post("/user/comment", User.signinRequired,Comment.save)
app.get('/admin/category/new', User.signinRequired, User.adminRequired, Category.new)
app.post('/admin/category', User.signinRequired, User.adminRequired, Category.save)
app.get('/admin/category/list', User.signinRequired, User.adminRequired, Category.list)
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.core.script;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.*;
import org.junit.experimental.categories.Category;

import generic.jar.ResourceFile;
import generic.test.category.NightlyCategory;
import ghidra.app.services.ProgramManager;
import ghidra.framework.Application;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.Reference;
import ghidra.test.*;

@Category(NightlyCategory.class)
public class WindowsResourceReferenceScriptTest extends AbstractGhidraHeadedIntegrationTest {

	private TestEnv env;
	private File script;

	@Before
	public void setUp() throws Exception {
		env = new TestEnv();

		ResourceFile resourceFile =
			Application.getModuleFile("Decompiler", "ghidra_scripts/WindowsResourceReference.java");

		script = resourceFile.getFile(true);
	}

	private void openProgram(Program program) {
		ProgramManager pm = env.getTool().getService(ProgramManager.class);
		pm.openProgram(program.getDomainFile());
	}

	private void closeProgram() {
		ProgramManager pm = env.getTool().getService(ProgramManager.class);
		pm.closeProgram();
		waitForPostedSwingRunnables();
	}

	@After
	public void tearDown() throws Exception {
		env.dispose();
	}

	/*
	 * Checks against known result set of addresses for use in regression testing.
	 * Checks each address location of created reference and checks
	 * that the correct format of address has been created to the resource
	 */
	@Test
	public void testWinmineNormalCases() throws Exception {
		Reference[] refs; //Array of mnemonic references
		RefType type; 	 //Type of reference
		Instruction inst;
		Boolean isAddr;

		Program program = env.getProgram("Winmine__XP.exe.gzf");
		openProgram(program);

		ScriptTaskListener scriptId = env.runScript(script);
		waitForScriptCompletion(scriptId, 65000);
		program.flushEvents();
		waitForPostedSwingRunnables();

		Listing listing = program.getListing();

		//Fill array with addresses of reference results
		Address[] winmineTestAddrs = propagateWinMineTestAddrs(program);

		for (Address winmineTestAddr : winmineTestAddrs) {
			inst = listing.getInstructionAt(winmineTestAddr);
			refs = inst.getMnemonicReferences();
			//Check a reference exists on the Mnemonic
			assertNotNull(refs);
			type = refs[0].getReferenceType();
			isAddr = refs[0].getToAddress().isMemoryAddress();
			//Check the reference is a real memory address
			assertTrue(isAddr);
			//Check the reference type created is of type DATA
			assertTrue(type.equals(RefType.DATA));
		}
		closeProgram();
	}

	@Test
	public void testMIPNormalCases() throws Exception {
		Reference[] refs; //Array of mnemonic references
		RefType type;    //Type of reference
		Boolean isAddr;
		Instruction inst;

		Program program = env.getProgram("mip.exe.gzf");
		openProgram(program);

		ScriptTaskListener scriptID = env.runScript(script);
		waitForScriptCompletion(scriptID, 60000);
		program.flushEvents();
		waitForPostedSwingRunnables();

		Listing listing = program.getListing();

		Address[] mipTestAddrs = propagateMIPTestAddrs(program);
		for (Address mipTestAddr : mipTestAddrs) {
			inst = listing.getInstructionAt(mipTestAddr);
			refs = inst.getMnemonicReferences();
			//Check a reference exists on the mnemonic
			assertNotNull(refs);
			type = refs[0].getReferenceType();
			isAddr = refs[0].getToAddress().isMemoryAddress();
			//check the reference is a real memory address
			assertTrue(isAddr);
			//check the reference type created is of type DATA
			assertTrue(type.equals(RefType.DATA));
		}

		closeProgram();
	}

	private Address addr(long offset, Program program) {
		return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset);
	}

	/*
	 * Creates and returns the known result set to check against for use
	 * in regression testing
	 */
	protected Address[] propagateWinMineTestAddrs(Program pgm) {
		Address[] winmineTestAddrs = { addr(0x01001b99, pgm), addr(0x01001bc2, pgm),
			addr(0x01001b5e, pgm), addr(0x010022c2, pgm), addr(0x01002243, pgm),
			addr(0x01003d52, pgm), addr(0x010022ac, pgm), addr(0x01002334, pgm),
			addr(0x01001f3b, pgm), addr(0x0100398f, pgm), addr(0x01003ade, pgm),
			addr(0x01003aec, pgm), addr(0x01003ad0, pgm), addr(0x010039c5, pgm),
			addr(0x01003d45, pgm), addr(0x0100385b, pgm), addr(0x01003d36, pgm),
			addr(0x01003920, pgm), addr(0x0100390e, pgm) };

		return winmineTestAddrs;
	}

	protected Address[] propagateMIPTestAddrs(Program pgm) {
		Address[] mipTestAddrs =

			{ addr(0x1400172c7L, pgm), addr(0x14005282dL, pgm), addr(0x14005276cL, pgm),
				addr(0x1400523baL, pgm), addr(0x14004ca38L, pgm), addr(0x14003d855L, pgm),
				addr(0x14001a964L, pgm), addr(0x14001846fL, pgm), addr(0x140025c87L, pgm) };

		return mipTestAddrs;
	}

}


text:
using System.Web.Http;
using System.Web.Mvc;
using StructureMap;
using RegTesting.Mvc.DependencyResolution;

namespace RegTesting.Mvc.App_Start {

	/// <summary>
	/// StructuremapMvc
	/// </summary>
    public static class StructuremapMvc {
		/// <summary>
		/// Start of IoC
		/// </summary>
        public static void Start() {
			IContainer container = IoC.Initialize();
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
        }
    }
}


text:
package org.apache.geode.internal.cache.execute.util;

import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.execute.InternalFunction;
import org.apache.geode.management.internal.RestAgent;

/**
 * The FindRestEnabledServersFunction class is a gemfire function that gives details about REST
 * enabled gemfire servers.
 *
 * @since GemFire 8.1
 */
public class FindRestEnabledServersFunction implements InternalFunction {
  private static final long serialVersionUID = 7851518767859544678L;

  /**
   * This property defines internal function that will get executed on each node to fetch active
   * REST service endpoints (servers).
   */
  public static final String FIND_REST_ENABLED_SERVERS_FUNCTION_ID =
      FindRestEnabledServersFunction.class.getName();

  @Override
  public void execute(FunctionContext context) {
    try {
      InternalCache cache = (InternalCache) context.getCache();
      DistributionConfig config = cache.getInternalDistributedSystem().getConfig();

      String bindAddress = RestAgent.getBindAddressForHttpService(config);

      final String protocolType = config.getHttpServiceSSLEnabled() ? "https" : "http";

      if (cache.isRESTServiceRunning()) {
        context.getResultSender()
            .lastResult(protocolType + "://" + bindAddress + ":" + config.getHttpServicePort());

      } else {
        context.getResultSender().lastResult("");
      }
    } catch (CacheClosedException ex) {
      context.getResultSender().lastResult("");
    }
  }

  @Override
  public String getId() {
    return FIND_REST_ENABLED_SERVERS_FUNCTION_ID;
  }

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

  @Override
  public boolean optimizeForWrite() {
    return false;
  }

  @Override
  public boolean isHA() {
    return false;
  }
}


text:
<?php

namespace Core\Exception;

/**
 * Class InvalidRequestException
 * @package Core\Exception
 */
class InvalidRequestException extends \Exception {}


text:
<endpoint name="data/inputs/kafka">
	Kafka Messaging
	<breadcrumb>
		<parent hidecurrent="False">datainputstats</parent>
		<name>Kafka Messaging</name>
	</breadcrumb>
	<elements>
		<element name="sourceFields" type="fieldset">
			<view name="list" />
			<view name="edit" />
			<view name="create" />
			<elements>

				<element name="name" label="Stanza Name">
					<view name="list" />
					<view name="create" />

					<key name="exampleText">Name of this stanza</key>
				</element>

<element name="activation_key" label="Activation Key">
					<view name="list" />
					<view name="create" />
					<view name="edit" />
					<key name="exampleText">Visit <a href="http://www.baboonbones.com/#activation"
						target="_blank">http://www.baboonbones.com/#activation</a> to
						obtain a non-expiring key</key>
				</element>

				<element name="output_settings" type="fieldset">
					<key name="legend">Output Settings</key>
					<view name="edit" />
					<view name="create" />
					<view name="list" />
					<elements>

						<element name="output_type" type="select" label="Data Output">
							<onChange>

								<key name="_action">showonly</key>
								<key name="stdout">NONE</key>
								<group_set>
									<group name="hec_output_settings" />
								</group_set>
								<key name="hec">hec_output_settings</key>

							</onChange>
							<view name="list" />
							<view name="edit" />
							<view name="create" />

							<options>
								<opt value="stdout" label="STDOUT" />
								<opt value="hec" label="HTTP Event Collector" />
							</options>
						</element>

						<element name="hec_output_settings" type="fieldset">
							<key name="legend">HTTP Event Collector Output</key>
							<view name="edit" />
							<view name="create" />
							<elements>

								<element name="hec_port" type="textfield" label="HTTP(s) Port">

									<view name="edit" />
									<view name="create" />
									<key name="exampleText">HTTP(s) Port that you have setup in Splunk</key>
								</element>
								<element name="hec_token" type="textfield" label="Authorisation Token">

									<view name="edit" />
									<view name="create" />
									<key name="exampleText">Authorisation Token that you have setup in Splunk
									</key>
								</element>
								<element name="hec_poolsize" type="textfield"
									label="HTTP Client Pool Size">

									<view name="edit" />
									<view name="create" />
									<key name="exampleText">You can setup a pool of HTTP client
										connections.Defaults to 1</key>
								</element>
								<element name="hec_https" type="checkbox" label="Use HTTPs ?">

									<view name="edit" />
									<view name="create" />
									<key name="exampleText">Note : Plain HTTP performs better</key>
								</element>
								<element name="hec_batch_mode" type="checkbox" label="Use Batch Mode ?">

									<view name="edit" />
									<view name="create" />
									<key name="exampleText">Send events to SplunkD in batches vs individual
										events</key>
									<onChange>
										<key name="_action">showonly</key>
										<key name="0">NONE</key>
										<key name="1">ALL</key>
										<group_set>
											<group name="hec_batch_mode_settings" />
										</group_set>
									</onChange>
								</element>

								<element name="hec_batch_mode_settings" type="fieldset">
									<key name="legend">Batch Mode Settings</key>
									<view name="edit" />
									<view name="create" />
									<elements>

										<element name="hec_max_batch_size_bytes" type="textfield"
											label="Maximum batch size">

											<view name="edit" />
											<view name="create" />
											<key name="exampleText">Will flush a batch upload at this size,
												defaults to 1048576 (1MB)</key>
										</element>
										<element name="hec_max_batch_size_events" type="textfield"
											label="Maximum batch event count">

											<view name="edit" />
											<view name="create" />
											<key name="exampleText">Will flush a batch upload at this number of
												events, defaults to 100</key>
										</element>
										<element name="hec_max_inactive_time_before_batch_flush"
											type="textfield" label="Inactivity time before flushing batch buffer">

											<view name="edit" />
											<view name="create" />
											<key name="exampleText">Will flush a batch upload after this period of
												inactivity , defaults to 5000 (5 secs)</key>
										</element>

									</elements>
								</element>

							</elements>
						</element>

					</elements>
				</element>

				<element name="consumer_connection_settings" type="fieldset">
					<key name="legend">Consumer Connection Settings</key>
					<view name="edit" />
					<view name="create" />
					<view name="list" />
					<elements>
						<element name="topic_name" type="textfield" label="Kafka Topic Name">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Kafka Topic Name</key>
						</element>

						<element name="group_id" type="textfield" label="Kafka Group ID">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Kafka Group ID</key>
						</element>

						<element name="zookeeper_connect_host" type="textfield"
							label="Zookeeper Host">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Zookeeper Host.IP or resolvable hostname.</key>
						</element>
						<element name="zookeeper_connect_port" type="textfield"
							label="Zookeeper Port">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Zookeeper Port.Will default to 2181.</key>
						</element>
						<element name="zookeeper_connect_chroot" type="textfield"
							label="Zookeeper CHROOT path">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Zookeeper CHROOT path ie: foo/bar </key>
						</element>
						<element name="zookeeper_connect_rawstring" type="textfield"
							label="Zookeeper Raw Connection String">

							<view name="edit" />
							<view name="create" />
							<view name="list" />
							<key name="exampleText">Zookeeper raw connection string. This will override
								any host/port/chroot settings above.Using this format , multiple
								hosts can be provided in a comma delimited manner ie:
								hostname1:port1,hostname2:port2,hostname3:port3/chroot/path
							</key>
						</element>
						<element name="zookeeper_session_timeout_ms" type="textfield"
							label="Zookeeper Session Timeout">

							<view name="edit" />
							<view name="create" />

							<key name="exampleText">Session timeout value in milliseconds.Will default
								to 400.</key>
						</element>
						<element name="zookeeper_sync_time_ms" type="textfield"
							label="Zookeeper Sync Time">

							<view name="edit" />
							<view name="create" />

							<key name="exampleText">Sync time value in milliseconds.Will default to
								200.</key>
						</element>
						<element name="auto_commit_interval_ms" type="textfield"
							label="Autocommit Interval">

							<view name="edit" />
							<view name="create" />

							<key name="exampleText">Autocommit interval time value in milliseconds.Will
								default to 1000.</key>
						</element>
						<element name="additional_consumer_properties" type="textfield"
							label="Additional Consumer Connection Properties">

							<view name="edit" />
							<view name="create" />
							<key name="exampleText">Parameter string in format
								'key1=value1,key2=value2,key3=value3'. This gets passed to the
								implementation class to process.</key>
						</element>

					</elements>
				</element>

				<element name="message_handler" type="fieldset">
					<key name="legend">Message Processing</key>
					<view name="edit" />
					<view name="create" />
					<elements>

						<element name="message_handler_impl" type="textfield"
							label="Implementation class for a custom message handler">

							<view name="edit" />
							<view name="create" />
							<key name="exampleText">An implementation of the
								com.splunk.modinput.kafka.AbstractMessageHandler class.You would
								provide this if you required some custom handling/formatting of
								the messages you consume.Ensure that the necessary jars are in
								the $SPLUNK_HOME/etc/apps/kafka_ta/bin/lib directory.If ommitted
								then the default handler
								'com.splunk.modinput.kafka.DefaultMessageHandler' will be used.
							</key>
						</element>
						<element name="message_handler_params" type="textfield"
							label="Implementation parameter string for the custom message handler">

							<view name="edit" />
							<view name="create" />
							<key name="exampleText">Parameter string in format
								'key1=value1,key2=value2,key3=value3'. This gets passed to the
								implementation class to process.</key>
						</element>

					</elements>
				</element>

				<element name="additional_startup_settings" type="fieldset">
					<key name="legend">Additional Startup Settings</key>
					<view name="edit" />
					<view name="create" />
					<elements>

						<element name="additional_jvm_propertys" type="textfield"
							label="Additional JVM System Properties">

							<view name="edit" />
							<view name="create" />
							<key name="exampleText">Parameter string in format
								'key1=value1,key2=value2,key3=value3'</key>
						</element>

					</elements>
				</element>
			</elements>
		</element>

		<element name="sourcetypeFields" type="fieldset">
			<view name="list" />
			<view name="edit" />
			<view name="create" />
			<elements>
				<element name="spl-ctrl_sourcetypeSelect" type="select"
					label="Set sourcetype">
					<onChange>

						<key name="_action">showonly</key>
						<group_set>
							<group name="sourcetype" />
							<group name="spl-ctrl_from_list" />
						</group_set>
						<key name="sourcetype">sourcetype</key>
						<key name="spl-ctrl_from_list">spl-ctrl_from_list</key>
					</onChange>
					<options>

						<opt value="spl-ctrl_from_list" label="From list" />
						<opt value="sourcetype" label="Manual" />
					</options>
					<view name="edit" />
					<view name="create" />

					<key name="processValueEdit">[[ e for e in ['sourcetype'] if form_defaults.get(e)
						][0]]</key>
					<key name="processValueAdd">[[ e for e in ['sourcetype'] if form_defaults.get(e)
						][0]]</key>
				</element>
				<element name="sourcetype" type="textfield" label="Source type">
					<view name="list" />
					<view name="edit" />
					<view name="create" />
					<key name="exampleText">If this field is left blank, the default value of
						script will be used for the source type.</key>
					<key name="processValueList">_('script') if (value==None or value=='') else value
					</key>
					<key name="submitValueAdd">form_data.get('spl-ctrl_from_list') if
						form_data.get('spl-ctrl_sourcetypeSelect')=='spl-ctrl_from_list'
						else value if
						form_data.get('spl-ctrl_sourcetypeSelect')=='sourcetype' else None
					</key>
					<key name="submitValueEdit">form_data.get('spl-ctrl_from_list') if
						form_data.get('spl-ctrl_sourcetypeSelect')=='spl-ctrl_from_list'
						else value if
						form_data.get('spl-ctrl_sourcetypeSelect')=='sourcetype' else None
					</key>
					<key name="labelList">Source type</key>
				</element>
				<element name="spl-ctrl_from_list" type="select"
					label="Select source type from list">
					<view name="edit" />
					<view name="create" />
					<key name="exampleText">Splunk
						classifies all common data types automatically, but if you're
						looking for something specific, you can find more source types in
						the <![CDATA[Splunkbase apps browser]]>
						or online at <![CDATA[www.splunkbase.com]]>.
					</key>
					<key name="requiredIfVisible" />
					<key name="dynamicOptions" type="dict">
						<key name="keyName">title</key>
						<key name="keyValue">title</key>
						<key name="splunkSource">/saved/sourcetypes</key>
						<key name="splunkSourceParams" type="dict">
							<key name="count">-1</key>
							<key name="search">'pulldown_type=true'</key>
						</key>
						<key name="prefixOptions" type="list">
							<item type="list">
								<item></item>
								<item>Choose...</item>
							</item>
						</key>
					</key>
				</element>
			</elements>
			<key name="legend">Source type</key>
			<key name="helpText">Set sourcetype field for all events from this source.
			</key>
		</element>

		<element name="spl-ctrl_EnableAdvanced" type="checkbox" label="More settings"
			class="spl-mgr-advanced-switch">
			<view name="edit" />
			<view name="create" />
			<onChange>
				<key name="_action">showonly</key>
				<key name="0">NONE</key>
				<key name="1">ALL</key>
				<group_set>
					<group name="advanced" />
				</group_set>
			</onChange>
		</element>
		<element name="advanced" type="fieldset" class="spl-mgr-advanced-options">
			<view name="edit" />
			<view name="create" />
			<elements>
				<element name="hostFields" type="fieldset">
					<key name="legend">Host</key>
					<view name="list" />
					<view name="edit" />
					<view name="create" />
					<elements>
						<element name="host" type="textfield" label="Host field value">
							<view name="edit" />
							<view name="create" />
						</element>
					</elements>
				</element>
				<element name="indexField" type="fieldset">
					<key name="legend">Index</key>
					<key name="helpText">Set the destination index for this source.</key>
					<view name="list" />
					<view name="edit" />
					<view name="create" />
					<elements>
						<element name="index" type="select" label="Index">
							<view name="list" />
							<view name="edit" />
							<view name="create" />
							<key name="dynamicOptions" type="dict">
								<key name="keyName">title</key>
								<key name="keyValue">title</key>
								<key name="splunkSource">/data/indexes</key>
								<key name="splunkSourceParams" type="dict">
									<key name="search">'isInternal=false disabled=false'</key>
									<key name="count">-1</key>
								</key>
							</key>
						</element>
					</elements>
				</element>
			</elements>
		</element>

		<element name="eai:acl.app" label="App">
			<view name="list" />
			<key name="processValueList">entity['eai:acl']['app'] or ""</key>
		</element>

	</elements>
</endpoint>


text:
"""
set of tools for working with VIX futures

@author: Jev Kuznetsov
Licence: GPL v2
"""

import datetime as dt
from pandas import *
import os
import urllib2
#from csvDatabase import HistDataCsv

m_codes = dict(zip(range(1,13),['F','G','H','J','K','M','N','Q','U','V','X','Z'])) #month codes of the futures
monthToCode = dict(zip(range(1,len(m_codes)+1),m_codes))

def getCboeData(year,month):
    ''' download data from cboe '''
    fName = "CFE_{0}{1}_VX.csv".format(m_codes[month],str(year)[-2:])
    urlStr =  "http://cfe.cboe.com/Publish/ScheduledTask/MktData/datahouse/{0}".format(fName)

    try:
        lines = urllib2.urlopen(urlStr).readlines()
    except Exception, e:
        s = "Failed to download:\n{0}".format(e);
        print s

    # first column is date, second is future , skip these
    header = lines[0].strip().split(',')[2:]

    dates = []
    data = [[] for i in range(len(header))]

    for line in lines[1:]:
        fields = line.strip().split(',')
        dates.append(datetime.strptime( fields[0],'%m/%d/%Y'))
        for i,field in enumerate(fields[2:]):
            data[i].append(float(field))

    data = dict(zip(header,data))

    df = DataFrame(data=data, index=Index(dates))

    return df

class Future(object):
    ''' vix future class '''
    def __init__(self,year,month):
        self.year = year
        self.month = month
        self.expiration = self._calculateExpirationDate()
        self.cboeData = None # daily cboe data
        self.intradayDb = None # intraday database (csv)

    def _calculateExpirationDate(self):
        ''' calculate expiration date of the future, (not 100% reliable) '''
        t = dt.date(self.year,self.month,1)+datetools.relativedelta(months=1)
        offset = datetools.Week(weekday=4)
        if t.weekday()<>4:
            t_new = t+3*offset
        else:
            t_new = t+2*offset

        t_new = t_new-datetools.relativedelta(days=30)
        return t_new

    def getCboeData(self, dataDir=None, forceUpdate=False):
        ''' download interday CBOE data
        specify dataDir to save data to csv.
        data will not be downloaded if csv file is already present.
        This can be overridden with setting forceUpdate to True
        '''

        if dataDir is not None:
            fileFound = os.path.exists(self._csvFilename(dataDir))

            if forceUpdate or not fileFound:
                self.cboeData = getCboeData(self.year, self.month)
                self.to_csv(dataDir)
            else:
                self.cboeData = DataFrame.from_csv(self._csvFilename(dataDir))

        else:
            self.cboeData = getCboeData(self.year, self.month)

        return self.cboeData

    def updateIntradayDb(self,dbDir):
        #self.intradayDb =
        pass

    def to_csv(self,dataDir):
        ''' save to csv in given dir. Filename is automatically generated '''
        self.cboeData.to_csv(self._csvFilename(dataDir))

    @property
    def dates(self):
        ''' trading days derived from cboe data '''
        if self.cboeData is not None:
            dates = [d.date() for d in self.cboeData.index]
        else:
            dates = None

        return dates

    def _csvFilename(self,dataDir):
        fName =  "VIX_future_%i_%i.csv" % (self.year, self.month)
        return os.path.join(dataDir,fName)

    def __repr__(self):
        s = 'Vix future [%i-%i (%s)] exp: %s\n' % (self.year, self.month,monthToCode[self.month], self.expiration.strftime("%B, %d %Y (%A)"))
        s+= 'Cboe data: %i days'% len(self.cboeData) if self.cboeData is not None else  'No data downloaded yet'
        return s

if __name__ == '__main__':
    print 'testing vix futures'

    year = 2012
    month = 12

    f = Future(year,month)
    f.getCboeData()
    print f


text:
package com.ysj.tinySpring.context;

import java.util.List;

import com.ysj.tinySpring.beans.BeanPostProcessor;
import com.ysj.tinySpring.beans.factory.AbstractBeanFactory;

/**
 * ApplicationContext 的抽象实现
 *
 */
public abstract class AbstractApplicationContext implements ApplicationContext {

	protected AbstractBeanFactory beanFactory;

	public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	/**
	 * 用于实现 BeanFactory 的刷新,也就是告诉 BeanFactory 该使用哪个资源(Resource)加载bean的定义
	 * (BeanDefinition),并实例化,初始化bean
	 * @throws Exception
	 */
	public void refresh() throws Exception {
		// 加载出bean的定义并保存到beanFactory中
		loadBeanDefinitions(beanFactory);
		// 从 BeanFactory 中的bean的定义找实现 BeanPostProcessor接口的类(例如:AspectJAwareAdvisorAutoProxyCreator.java)
		// 注册到 AbstractBeanFactory 维护的 BeanPostProcessor 列表中去(用于在bean实例化后对其进行一些其他处理,
		// 可以看看getBean方法()中的initializeBean()的调用)。
		// 后面调用getBean方法通过AspectJAwareAdvisorAutoProxyCreator#postProcessAfterInitialization()方法中调用了
		// getBeansForType方法保证了 PointcutAdvisor 的实例化顺序优于普通 Bean。
		registerBeanPostProcessors(beanFactory);
		// 默认以单例的方式实例化所有 Bean
		onRefresh();
	}

	/**
	 * 由子类决定从哪种形式的Resource中加载出bean的定义,并保存到beanFactory中
	 * @param beanFactory
	 * @throws Exception
	 */
	protected abstract void loadBeanDefinitions(AbstractBeanFactory beanFactory) throws Exception;

	/**
	 * 可用于实例化AspectJAwareAdvisorAutoProxyCreator
	 * @param beanFactory
	 * @throws Exception
	 */
	protected void registerBeanPostProcessors(AbstractBeanFactory beanFactory) throws Exception {
		List beanPostProcessors = beanFactory.getBeansForType(BeanPostProcessor.class);
		for (Object beanPostProcessor : beanPostProcessors) {
			beanFactory.addBeanPostProcessor((BeanPostProcessor) beanPostProcessor);
		}
	}

	// 实现支持singleton(单例)类型的bean
	protected void onRefresh() throws Exception{
        beanFactory.preInstantiateSingletons();
    }

	// 从beanFactory中获取bean
	@Override
	public Object getBean(String name) throws Exception {
		return beanFactory.getBean(name);
	}

}


text:
/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} newColor
 * @return {number[][]}
 */
const floodFill = function (image, sr, sc, newColor) {
    if (!image || image.length === 0 || image[0].length === 0 || sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) {
        return image;
    }
    let visited = new Array(image.length);
    for (let i = 0; i < image.length; ++i) {
        visited[i] = new Array(image[0].length);
        visited[i].fill(false);
    }
    floodHelper(image, visited, sr, sc, image[sr][sc], newColor);
    return image;
};

function floodHelper(image, visited, r, c, oldColor, newColor) {
    if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || visited[r][c] || image[r][c] !== oldColor) {
        return;
    }
    image[r][c] = newColor;
    visited[r][c] = true;
    floodHelper(image, visited, r - 1, c, oldColor, newColor);
    floodHelper(image, visited, r + 1, c, oldColor, newColor);
    floodHelper(image, visited, r, c - 1, oldColor, newColor);
    floodHelper(image, visited, r, c + 1, oldColor, newColor);
}

module.exports = floodFill;


text:
Service for confirming mobile numbers

## Note: We are sunsetting Digitimate on Monday, July 9, 2018.

On July 9, 2018, we are sunsetting Digitimate. This is over 180 days from the announcement (on January 9), which we believe is ample advance notice for developers to find time to gracefully migrate off of Digitimate.

**Developers who are already using Digitimate:** We will help you migrate to another SMS confirmation service by letting you export the data associated with the developer email address you used with Digitimate.

You either can run Digitimate yourself (the code will stay open-source on July 9), which requires Node.js, RethinkDB, and a Twilio account, or you can use another SMS confirmation service, such as building your own that connects to an SMS service like Twilio.

**Developers who aren't already using Digitimate:** We recommend that you choose another service today so you don't have to migrate so soon.

**Data policy:** After July 9, the Digitimate service will no longer be online. We may continue to allow developers to export data associated with their developer email addresses for a couple of weeks afterwards. After that, we'll turn off Digitimate and terminate the Node.js servers, RethinkDB server, and disks used by those servers.

## About

See http://digitimate.com/ for more info.


text:
<?php

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Exception\ProcessFailedException;

/**
 * @author Sebastian Marek <proofek@gmail.com>
 */
class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * tests ProcessFailedException throws exception if the process was successful
     */
    public function testProcessFailedExceptionThrowsException()
    {
        $process = $this->getMock(
            'Symfony\Component\Process\Process',
            array('isSuccessful'),
            array('php')
        );
        $process->expects($this->once())
            ->method('isSuccessful')
            ->will($this->returnValue(true));

        $this->setExpectedException(
            '\InvalidArgumentException',
            'Expected a failed process, but the given process was successful.'
        );

        new ProcessFailedException($process);
    }

    /**
     * tests ProcessFailedException uses information from process output
     * to generate exception message
     */
    public function testProcessFailedExceptionPopulatesInformationFromProcessOutput()
    {
        $cmd = 'php';
        $exitCode = 1;
        $exitText = 'General error';
        $output = "Command output";
        $errorOutput = "FATAL: Unexpected error";

        $process = $this->getMock(
            'Symfony\Component\Process\Process',
            array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled'),
            array($cmd)
        );
        $process->expects($this->once())
            ->method('isSuccessful')
            ->will($this->returnValue(false));

        $process->expects($this->once())
            ->method('getOutput')
            ->will($this->returnValue($output));

        $process->expects($this->once())
            ->method('getErrorOutput')
            ->will($this->returnValue($errorOutput));

        $process->expects($this->once())
            ->method('getExitCode')
            ->will($this->returnValue($exitCode));

        $process->expects($this->once())
            ->method('getExitCodeText')
            ->will($this->returnValue($exitText));

        $process->expects($this->once())
            ->method('isOutputDisabled')
            ->will($this->returnValue(false));

        $exception = new ProcessFailedException($process);

        $this->assertEquals(
            "The command \"$cmd\" failed.\nExit Code: $exitCode($exitText)\n\nOutput:\n================\n{$output}\n\nError Output:\n================\n{$errorOutput}",
            $exception->getMessage()
        );
    }

    /**
     * Tests that ProcessFailedException does not extract information from
     * process output if it was previously disabled
     */
    public function testDisabledOutputInFailedExceptionDoesNotPopulateOutput()
    {
        $cmd = 'php';
        $exitCode = 1;
        $exitText = 'General error';

        $process = $this->getMock(
            'Symfony\Component\Process\Process',
            array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput'),
            array($cmd)
        );
        $process->expects($this->once())
            ->method('isSuccessful')
            ->will($this->returnValue(false));

        $process->expects($this->never())
            ->method('getOutput');

        $process->expects($this->never())
            ->method('getErrorOutput');

        $process->expects($this->once())
            ->method('getExitCode')
            ->will($this->returnValue($exitCode));

        $process->expects($this->once())
            ->method('getExitCodeText')
            ->will($this->returnValue($exitText));

        $process->expects($this->once())
            ->method('isOutputDisabled')
            ->will($this->returnValue(true));

        $exception = new ProcessFailedException($process);

        $this->assertEquals(
            "The command \"$cmd\" failed.\nExit Code: $exitCode($exitText)",
            $exception->getMessage()
        );
    }
}


text:
package buildinfo

import "github.com/rackspace/gophercloud"

func getURL(c *gophercloud.ServiceClient) string {
	return c.ServiceURL("build_info")
}


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?ؠ an illegal char #x620
 in PITarget ?>
]>
<animal/>


text:
@interface WUEmoticonsKeyboardKeyCell : UICollectionViewCell
@property (nonatomic,weak,readonly) UIButton *keyButton;
@property (nonatomic,strong) WUEmoticonsKeyboardKeyItem *keyItem;
@end


text:
using Chloe.Sharding.Queries;
using System.Threading;

namespace Chloe.Sharding.Enumerables
{
    class SingleTablePagingQueryEnumerable : FeatureEnumerable<PagingResult>
    {
        ShardingQueryPlan _queryPlan;

        public SingleTablePagingQueryEnumerable(ShardingQueryPlan queryPlan)
        {
            this._queryPlan = queryPlan;
        }

        public override IFeatureEnumerator<PagingResult> GetFeatureEnumerator(CancellationToken cancellationToken = default)
        {
            return new Enumerator(this, cancellationToken);
        }

        class Enumerator : FeatureEnumerator<PagingResult>
        {
            SingleTablePagingQueryEnumerable _enumerable;
            CancellationToken _cancellationToken;
            public Enumerator(SingleTablePagingQueryEnumerable enumerable, CancellationToken cancellationToken)
            {
                this._enumerable = enumerable;
                this._cancellationToken = cancellationToken;
            }

            protected override async Task<IFeatureEnumerator<PagingResult>> CreateEnumerator(bool @async)
            {
                ShardingQueryPlan queryPlan = this._enumerable._queryPlan;
                var countQuery = ShardingHelpers.GetCountQuery(queryPlan);

                List<QueryResult<long>> routeTableCounts = @async ? await countQuery.ToListAsync() : countQuery.ToList();
                long totals = routeTableCounts.Select(a => a.Result).Sum();

                SingleTableQueryEnumerable queryEnumerable = new SingleTableQueryEnumerable(queryPlan);
                List<object> dataList = @async ? await queryEnumerable.ToListAsync() : queryEnumerable.ToList();

                return new ScalarFeatureEnumerator<PagingResult>(new PagingResult() { Totals = totals, DataList = dataList });
            }
        }
    }

}