text:
using blink::test::RunPendingTasks;
using testing::_;
using testing::AnyNumber;

namespace blink {
namespace {

class AnimationMockChromeClient : public RenderingTestChromeClient {
 public:
  AnimationMockChromeClient() : has_scheduled_animation_(false) {}

  // ChromeClient
  MOCK_METHOD2(AttachRootGraphicsLayer,
               void(GraphicsLayer*, LocalFrame* localRoot));
  MOCK_METHOD3(MockSetToolTip, void(LocalFrame*, const String&, TextDirection));
  void SetToolTip(LocalFrame& frame,
                  const String& tooltip_text,
                  TextDirection dir) override {
    MockSetToolTip(&frame, tooltip_text, dir);
  }

  void ScheduleAnimation(const LocalFrameView*,
                         base::TimeDelta = base::TimeDelta()) override {
    has_scheduled_animation_ = true;
  }
  bool has_scheduled_animation_;
};

class LocalFrameViewTest : public RenderingTest {
 protected:
  LocalFrameViewTest()
      : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
        chrome_client_(MakeGarbageCollected<AnimationMockChromeClient>()) {
    EXPECT_CALL(GetAnimationMockChromeClient(), AttachRootGraphicsLayer(_, _))
        .Times(AnyNumber());
  }

  ~LocalFrameViewTest() override {
    testing::Mock::VerifyAndClearExpectations(&GetAnimationMockChromeClient());
  }

  RenderingTestChromeClient& GetChromeClient() const override {
    return *chrome_client_;
  }

  void SetUp() override {
    EnableCompositing();
    RenderingTest::SetUp();
  }

  AnimationMockChromeClient& GetAnimationMockChromeClient() const {
    return *chrome_client_;
  }

 private:
  Persistent<AnimationMockChromeClient> chrome_client_;
};

TEST_F(LocalFrameViewTest, SetPaintInvalidationDuringUpdateAllLifecyclePhases) {
  SetBodyInnerHTML("
A
");
  GetDocument().getElementById("a")->setAttribute(html_names::kStyleAttr,
                                                  "color: green");
  GetAnimationMockChromeClient().has_scheduled_animation_ = false;
  UpdateAllLifecyclePhasesForTest();
  EXPECT_FALSE(GetAnimationMockChromeClient().has_scheduled_animation_);
}

TEST_F(LocalFrameViewTest, SetPaintInvalidationOutOfUpdateAllLifecyclePhases) {
  SetBodyInnerHTML("
A
");
  GetAnimationMockChromeClient().has_scheduled_animation_ = false;
  GetDocument()
      .getElementById("a")
      ->GetLayoutObject()
      ->SetShouldDoFullPaintInvalidation();
  EXPECT_TRUE(GetAnimationMockChromeClient().has_scheduled_animation_);
  GetAnimationMockChromeClient().has_scheduled_animation_ = false;
  GetDocument()
      .getElementById("a")
      ->GetLayoutObject()
      ->SetShouldDoFullPaintInvalidation();
  EXPECT_TRUE(GetAnimationMockChromeClient().has_scheduled_animation_);
  GetAnimationMockChromeClient().has_scheduled_animation_ = false;
  UpdateAllLifecyclePhasesForTest();
  EXPECT_FALSE(GetAnimationMockChromeClient().has_scheduled_animation_);
}

// If we don't hide the tooltip on scroll, it can negatively impact scrolling
// performance. See crbug.com/586852 for details.
TEST_F(LocalFrameViewTest, HideTooltipWhenScrollPositionChanges) {
  SetBodyInnerHTML("

");

  EXPECT_CALL(GetAnimationMockChromeClient(),
              MockSetToolTip(GetDocument().GetFrame(), String(), _));
  GetDocument().View()->LayoutViewport()->SetScrollOffset(
      ScrollOffset(1, 1), mojom::blink::ScrollType::kUser);

  // Programmatic scrolling should not dismiss the tooltip, so setToolTip
  // should not be called for this invocation.
  EXPECT_CALL(GetAnimationMockChromeClient(),
              MockSetToolTip(GetDocument().GetFrame(), String(), _))
      .Times(0);
  GetDocument().View()->LayoutViewport()->SetScrollOffset(
      ScrollOffset(2, 2), mojom::blink::ScrollType::kProgrammatic);
}

// NoOverflowInIncrementVisuallyNonEmptyPixelCount tests fail if the number of
// pixels is calculated in 32-bit integer, because 65536 * 65536 would become 0
// if it was calculated in 32-bit and thus it would be considered as empty.
TEST_F(LocalFrameViewTest, NoOverflowInIncrementVisuallyNonEmptyPixelCount) {
  EXPECT_FALSE(GetDocument().View()->IsVisuallyNonEmpty());
  GetDocument().View()->IncrementVisuallyNonEmptyPixelCount(
      IntSize(65536, 65536));
  EXPECT_TRUE(GetDocument().View()->IsVisuallyNonEmpty());
}

// This test addresses http://crbug.com/696173, in which a call to
// LocalFrameView::UpdateLayersAndCompositingAfterScrollIfNeeded during layout
// caused a crash as the code was incorrectly assuming that the ancestor
// overflow layer would always be valid.
TEST_F(LocalFrameViewTest,
       ViewportConstrainedObjectsHandledCorrectlyDuringLayout) {
  SetBodyInnerHTML(R"HTML(

  )HTML");

  LayoutBoxModelObject* sticky = ToLayoutBoxModelObject(
      GetDocument().getElementById("sticky")->GetLayoutObject());

  // Deliberately invalidate the ancestor overflow layer. This approximates
  // http://crbug.com/696173, in which the ancestor overflow layer can be null
  // during layout.
  sticky->Layer()->UpdateAncestorOverflowLayer(nullptr);

  // This call should not crash.
  GetDocument().View()->LayoutViewport()->SetScrollOffset(
      ScrollOffset(0, 100), mojom::blink::ScrollType::kProgrammatic);
}

TEST_F(LocalFrameViewTest, UpdateLifecyclePhasesForPrintingDetachedFrame) {
  SetBodyInnerHTML("");
  SetChildFrameHTML("A");

  ChildDocument().SetPrinting(Document::kPrinting);
  ChildDocument().View()->UpdateLifecyclePhasesForPrinting();

  // The following checks that the detached frame has been walked for PrePaint.
  EXPECT_EQ(DocumentLifecycle::kPrePaintClean,
            GetDocument().Lifecycle().GetState());
  EXPECT_EQ(DocumentLifecycle::kPrePaintClean,
            ChildDocument().Lifecycle().GetState());
  auto* child_layout_view = ChildDocument().GetLayoutView();
  EXPECT_TRUE(child_layout_view->FirstFragment().PaintProperties());
}

TEST_F(LocalFrameViewTest, CanHaveScrollbarsIfScrollingAttrEqualsNoChanged) {
  SetBodyInnerHTML("");
  EXPECT_FALSE(ChildDocument().View()->CanHaveScrollbars());

  ChildDocument().WillChangeFrameOwnerProperties(
      0, 0, mojom::blink::ScrollbarMode::kAlwaysOn, false);
  EXPECT_TRUE(ChildDocument().View()->CanHaveScrollbars());
}

TEST_F(LocalFrameViewTest,
       MainThreadScrollingForBackgroundFixedAttachmentWithCompositing) {
  GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled(
      true);

  SetBodyInnerHTML(R"HTML(

  )HTML");

  auto* frame_view = GetDocument().View();
  EXPECT_EQ(0u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_FALSE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  Element* body = GetDocument().body();
  Element* html = GetDocument().documentElement();
  Element* div = GetDocument().getElementById("div");

  // Only body has fixed background. No main thread scrolling.
  body->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_FALSE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  // Both body and div have fixed background. Requires main thread scrolling.
  div->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(2u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  // Only div has fixed background. Requires main thread scrolling.
  body->removeAttribute(html_names::kClassAttr);
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  // Only html has fixed background. No main thread scrolling.
  div->removeAttribute(html_names::kClassAttr);
  html->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_FALSE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  // Both html and body have fixed background. Requires main thread scrolling.
  body->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(2u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());
}

TEST_F(LocalFrameViewTest,
       MainThreadScrollingForBackgroundFixedAttachmentWithoutCompositing) {
  SetBodyInnerHTML(R"HTML(

  )HTML");

  auto* frame_view = GetDocument().View();
  EXPECT_EQ(0u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_FALSE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  Element* body = GetDocument().body();
  Element* html = GetDocument().documentElement();
  Element* div = GetDocument().getElementById("div");

  // When not prefer compositing, we use main thread scrolling when there is
  // any object with fixed-attachment background.
  body->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  div->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(2u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  body->removeAttribute(html_names::kClassAttr);
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  div->removeAttribute(html_names::kClassAttr);
  html->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(1u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());

  body->setAttribute(html_names::kClassAttr, "fixed-background");
  UpdateAllLifecyclePhasesForTest();
  EXPECT_EQ(2u, frame_view->BackgroundAttachmentFixedObjects().size());
  EXPECT_TRUE(
      frame_view->RequiresMainThreadScrollingForBackgroundAttachmentFixed());
}

// Ensure the fragment navigation "scroll into view and focus" behavior doesn't
// activate synchronously while rendering is blocked waiting on a stylesheet.
// See https://crbug.com/851338.
TEST_F(SimTest, FragmentNavChangesFocusWhileRenderingBlocked) {
  // Style-sheets are parser-blocking, not render-blocking when
  // BlockHTMLParserOnStyleSheets is enabled.
  ScopedBlockHTMLParserOnStyleSheetsForTest scope(false);

  SimRequest main_resource("https://example.com/test.html", "text/html");
  SimSubresourceRequest css_resource("https://example.com/sheet.css",
                                     "text/css");
  LoadURL("https://example.com/test.html");

  main_resource.Complete(R"HTML(
      <!DOCTYPE html>
      <link rel="stylesheet" type="text/css" href="sheet.css">
      Link to bottom of the page

      <input id="bottom">Bottom of the page</input>
    )HTML");

  ScrollableArea* viewport = GetDocument().View()->LayoutViewport();
  ASSERT_EQ(ScrollOffset(), viewport->GetScrollOffset());

  // We're still waiting on the stylesheet to load so the load event shouldn't
  // yet dispatch and rendering is deferred.
  ASSERT_FALSE(GetDocument().HaveRenderBlockingResourcesLoaded());
  EXPECT_FALSE(GetDocument().IsLoadCompleted());

  // Click on the anchor element. This will cause a synchronous same-document
  //  navigation.
  auto* anchor =
      To<HTMLAnchorElement>(GetDocument().getElementById("anchorlink"));
  anchor->click();

  // Even though the navigation is synchronous, the active element shouldn't be
  // changed.
  EXPECT_EQ(GetDocument().body(), GetDocument().ActiveElement())
      << "Active element changed while rendering is blocked";
  EXPECT_EQ(ScrollOffset(), viewport->GetScrollOffset())
      << "Scroll offset changed while rendering is blocked";

  // Force a layout.
  anchor->style()->setProperty(GetDocument().GetExecutionContext(), "display",
                               "block", String(), ASSERT_NO_EXCEPTION);
  GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);

  EXPECT_EQ(GetDocument().body(), GetDocument().ActiveElement())
      << "Active element changed due to layout while rendering is blocked";
  EXPECT_EQ(ScrollOffset(), viewport->GetScrollOffset())
      << "Scroll offset changed due to layout while rendering is blocked";

  // Complete the CSS stylesheet load so the document can finish loading. The
  // fragment should be activated at that point.
  css_resource.Complete("");
  RunPendingTasks();
  Compositor().BeginFrame();
  ASSERT_TRUE(GetDocument().IsLoadCompleted());
  EXPECT_EQ(GetDocument().getElementById("bottom"),
            GetDocument().ActiveElement())
      << "Active element wasn't changed after load completed.";
  EXPECT_NE(ScrollOffset(), viewport->GetScrollOffset())
      << "Scroll offset wasn't changed after load completed.";
}

TEST_F(SimTest, ForcedLayoutWithIncompleteSVGChildFrame) {
  SimRequest main_resource("https://example.com/test.html", "text/html");
  SimRequest svg_resource("https://example.com/file.svg", "image/svg+xml");

  LoadURL("https://example.com/test.html");

  main_resource.Complete(R"HTML(
      <!DOCTYPE html>
      <object data="file.svg"></object>
    )HTML");

  // Write the SVG document so that there is something to layout, but don't let
  // the resource finish loading.
  svg_resource.Write(R"SVG(
      <svg xmlns="http://www.w3.org/2000/svg"></svg>
    )SVG");

  // Mark the top-level document for layout and then force layout. This will
  // cause the layout tree in the <object> object to be built.
  GetDocument().View()->SetNeedsLayout();
  GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kTest);

  svg_resource.Finish();
}

}  // namespace
}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
<mat-card class="breadcrumb-card">
  <button class="scroll-button" [class.hidden]="!showScrollLeftButton" (click)="scroll(-100)">
    <mat-icon> more_horiz </mat-icon>
  </button>

  <div class="breadcrumbs" #breadcrumbs (scroll)="updateScrollButtonVisibility$.next()">
    <button
      *ngFor="let node of parents; let last = last"
      (mouseover)="mouseOverNode.emit(node)"
      (mouseleave)="mouseLeaveNode.emit(node)"
      mat-button
      color="primary"
      (click)="handleSelect.emit(node)"
      [class.selected]="last"
    >
      {{ node.original.component?.name || node.original.element }}
    </button>
  </div>

  <button class="scroll-button" [class.hidden]="!showScrollRightButton" (click)="scroll(100)">
    <mat-icon> more_horiz </mat-icon>
  </button>
</mat-card>


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="MdlScorm" table="mdl_scorm">
    <indexes>
      <index name="mdl_scor_cou_ix" columns="course"/>
    </indexes>
    <id name="id" type="bigint" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="course" type="bigint" column="course" nullable="false"/>
    <field name="name" type="string" column="name" length="255" nullable="false"/>
    <field name="scormtype" type="string" column="scormtype" length="50" nullable="false"/>
    <field name="reference" type="string" column="reference" length="255" nullable="false"/>
    <field name="intro" type="text" column="intro" nullable="false"/>
    <field name="introformat" type="smallint" column="introformat" nullable="false"/>
    <field name="version" type="string" column="version" length="9" nullable="false"/>
    <field name="maxgrade" type="float" column="maxgrade" precision="10" scale="0" nullable="false"/>
    <field name="grademethod" type="boolean" column="grademethod" nullable="false"/>
    <field name="whatgrade" type="bigint" column="whatgrade" nullable="false"/>
    <field name="maxattempt" type="bigint" column="maxattempt" nullable="false"/>
    <field name="forcecompleted" type="boolean" column="forcecompleted" nullable="false"/>
    <field name="forcenewattempt" type="boolean" column="forcenewattempt" nullable="false"/>
    <field name="lastattemptlock" type="boolean" column="lastattemptlock" nullable="false"/>
    <field name="displayattemptstatus" type="boolean" column="displayattemptstatus" nullable="false"/>
    <field name="displaycoursestructure" type="boolean" column="displaycoursestructure" nullable="false"/>
    <field name="updatefreq" type="boolean" column="updatefreq" nullable="false"/>
    <field name="sha1hash" type="string" column="sha1hash" length="40" nullable="true"/>
    <field name="md5hash" type="string" column="md5hash" length="32" nullable="false"/>
    <field name="revision" type="bigint" column="revision" nullable="false"/>
    <field name="launch" type="bigint" column="launch" nullable="false"/>
    <field name="skipview" type="boolean" column="skipview" nullable="false"/>
    <field name="hidebrowse" type="boolean" column="hidebrowse" nullable="false"/>
    <field name="hidetoc" type="boolean" column="hidetoc" nullable="false"/>
    <field name="hidenav" type="boolean" column="hidenav" nullable="false"/>
    <field name="auto" type="boolean" column="auto" nullable="false"/>
    <field name="popup" type="boolean" column="popup" nullable="false"/>
    <field name="options" type="string" column="options" length="255" nullable="false"/>
    <field name="width" type="bigint" column="width" nullable="false"/>
    <field name="height" type="bigint" column="height" nullable="false"/>
    <field name="timeopen" type="bigint" column="timeopen" nullable="false"/>
    <field name="timeclose" type="bigint" column="timeclose" nullable="false"/>
    <field name="timemodified" type="bigint" column="timemodified" nullable="false"/>
  </entity>
</doctrine-mapping>


text:
package org.apache.sysml.test.gpu;

import org.apache.sysml.test.utils.TestUtils;
import org.junit.Test;

/**
 * Unit tests for Unary ops on GPU
 */
public class UnaryOpTests extends UnaryOpTestsBase {

	private final static String TEST_NAME = "UnaryOpTests";

	@Override
	public void setUp() {
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_DIR, TEST_NAME);
		getAndLoadTestConfiguration(TEST_NAME);
	}

	@Test
	public void testSin() throws Exception {
		testSimpleUnaryOpMatrixOutput("sin", "gpu_sin");
	}

	@Test
	public void testCos() throws Exception {
		testSimpleUnaryOpMatrixOutput("cos", "gpu_cos");
	}

	@Test
	public void testTan() throws Exception {
		testSimpleUnaryOpMatrixOutput("tan", "gpu_tan");
	}

	@Test
	public void testAsin() throws Exception {
		testSimpleUnaryOpMatrixOutput("asin", "gpu_asin");
	}

	@Test
	public void testAcos() throws Exception {
		testSimpleUnaryOpMatrixOutput("acos", "gpu_acos");
	}

	@Test
	public void testAtan() throws Exception {
		testSimpleUnaryOpMatrixOutput("atan", "gpu_atan");
	}

	@Test
	public void testExp() throws Exception {
		testSimpleUnaryOpMatrixOutput("exp", "gpu_exp");
	}

	@Test
	public void testLog() throws Exception {
		testSimpleUnaryOpMatrixOutput("log", "gpu_log");
	}

	@Test
	public void testSqrt() throws Exception {
		testSimpleUnaryOpMatrixOutput("sqrt", "gpu_sqrt");
	}

	@Test
	public void testAbs() throws Exception {
		testSimpleUnaryOpMatrixOutput("abs", "gpu_abs");
	}

	@Test
	public void testRound() throws Exception {
		testSimpleUnaryOpMatrixOutput("round", "gpu_round");
	}

	@Test
	public void testFloor() throws Exception {
		testSimpleUnaryOpMatrixOutput("sqrt", "gpu_floor");
	}

	@Test
	public void testCeil() throws Exception {
		testSimpleUnaryOpMatrixOutput("ceil", "gpu_ceil");
	}

	@Test
	public void testSign() throws Exception {
		testSimpleUnaryOpMatrixOutput("sign", "gpu_sign");
	}

	@Test
	public void testSelp() throws Exception {
		testUnaryOpMatrixOutput("out = max(in1, 0)", "gpu_selp", "in1", "out");
	}
}


text:
var validateApiKey = require('../validateApiKey');

// validate api key header prior to api method execution
module.exports = {
    // api methods can be defined with an array of middleware functions
    get: [ validateApiKey, function (req, res, next) {
        res.status(200).send();
    }]
}


text:
[Home](../README.md)

# Ad-Hoc finding of Page Objects
The `Browser` and `PageObject` classes provide entry points to the "ad-hoc finding" API.
This allows you to apply a more script style approach to your tests.

**Doing so might be useful in the following circumstances:**

- You don't have an unique identification property for initializing a `PageObject` field and need to take a programmatic approach
- You want to rapidly prototype your tests scenarios
- You want to execute some bordercases upon elements and don't like to declare those as fields in your page objects
- Getting to a specific page object is not possible by using `@IdentifyUsing`, `@FindBy` or `@FindBys`

## Examples
```java
// find an element by its ID 'fooId' as a GenericElement
GenericElement element = getBrowser()
    .find("#fooId");

// find many elements by their shared CSS class 'foo' as a list of GenericElement
List<GenericElement> elements = getBrowser()
    .findMany(".foo");

// find a TextField by it's ID - Identification first
TextField textField = getBrowser()
    .findBy(id("textField"))
    .as(TextField.class);

// find a TextField by it's ID - class first
TextField textField = getBrowser()
    .find(TextField.class)
    .by(id("textField"));

// find all all elements with the CSS class 'foo' within an element with ID 'group' as TextFields
List<TextField> textFields = getBrowser()
    .find("#group")
    .findBy(css(".foo"))
    .asMany(TextField.class);
```

# Linked Documentation

- [Conditions](conditions.md)
- [Identifications](identifications.md)
- [Generic Elements](page-object-generic.md)


text:
<!doctype html>

    <title>My first document title</title>

My second heading

My second subheading

My second document text is brilliant.   Second is better than first.


text:
    <title>SendGrid Incoming Parse</title>

You have successfuly launched the server!

      Check out the documentation on how to use this software to utilize the SendGrid Inbound Parse webhook.


text:
'use strict';

var config   = require('../config/config');
var mongoose = require('mongoose');

process.env.NODE_ENV = 'test';

beforeEach(function (done) {

  function clearDB() {
    for (var i in mongoose.connection.collections) {
      mongoose.connection.collections[i].remove();
    }
    return done();
  }

  function reconnect() {
    mongoose.connect(config.db, function (err) {
      if (err) {
        throw err;
      }
      return clearDB();
    });
  }

  function checkState() {
    switch (mongoose.connection.readyState) {
      case 0:
        reconnect();
        break;
      case 1:
        clearDB();
        break;
      default:
        process.nextTick(checkState);
    }
  }

  checkState();
});

afterEach(function (done) {
  mongoose.disconnect();
  return done();
});


text:
//
//  JMWebResourceInterceptorSettings+Internal.h
//  JoyMapsKit
//
//  Created by laijiandong on 12/25/14.
//  Copyright (c) 2014 laijiandong. All rights reserved.
//

#import "JMWebResourceInterceptorSettings.h"

/**
 *  Web资源拦截器规则配置类的内部方法。
 */
@interface JMWebResourceInterceptorSettings (Internal)

// 创建默认拦截设置
+ (instancetype)defaultInterceptorSettings;

@end


text:
Rails.application.config.to_prepare do
  ########## changes for spree to works with camaleon  ##########
  Spree::UserSessionsController.class_eval do
    private
    def redirect_back_or_default(default)
      redirect_to(cookies[:return_to] || session["spree_user_return_to"] || default)
      session["spree_user_return_to"] = nil
      cookies[:return_to] = nil
    end
  end

  Deface::Override.new(
      virtual_path: 'spree/layouts/admin',
      name: 'cama_admin_iframe_hide_sidebar',
      insert_bottom: '[data-hook="admin_footer_scripts"]',
      text: '<script>
               jQuery(function(){
                  if(window.location != window.parent.location){ $("#wrapper").addClass("sidebar-minimized"); $("#main-part").css({"margin-left": 0, "padding-left": "35px"}); $("#main-sidebar").hide(); }
               })
            </script>'
  )

  Deface::Override.new(
      virtual_path: 'spree/admin/products/_form',
      name: 'cama_custom_fields',
      insert_bottom: '[data-hook="admin_product_form_additional_fields"]',
      partial: '/plugins/camaleon_spree/admin/render_custom_fields_product'
  )
  Deface::Override.new(
      virtual_path: 'spree/admin/products/new',
      name: 'cama_custom_fields_on_create',
      insert_bottom: '[data-hook="new_product_attrs"]',
      partial: '/plugins/camaleon_spree/admin/render_custom_fields_product'
  )

  # spree product add custom fields support
  Spree::Product.class_eval do
    include CamaleonCms::Metas
    include CamaleonCms::CustomFieldsRead
    include CamaleonCms::CustomFieldsConcern
    def get_field_groups(args = {}) # needs to fix for multisite&multistore support
      CamaleonCms::CustomFieldGroup.where(object_class: self.class.name)
    end

  end

  Spree::Admin::ProductsController.class_eval do
    create.after :save_custom_fields
    update.after :save_custom_fields

    private
    def save_custom_fields
      @object.set_field_values(params[:field_options])
    end
  end

  # redirect to cama dashboard
  # Spree::Admin::RootController.class_eval do
  #   def index
  #     redirect_to Rails.application.routes.url_helpers.cama_admin_dashboard_path
  #   end
  # end
end


text:
#ifndef _BAS_CONFIG_H_
#define _BAS_CONFIG_H_

/** @defgroup BAS Battery Service
  * @brief Battery service
  * @{
  */

/** @defgroup BAS_CONFIG Battery Service Config
  * @brief Battery service configuration file
  * @{
  */

/*============================================================================*
 *                         Micros
 *============================================================================*/
/** @defgroup BAS_Common_Exported_Macros BAS Common Exported Macros
  * @{
  */

/** @details
    Set BAS_BATTERY_LEVEL_NOTIFY_SUPPORT to 1 to support Battery level notification feature,
    otherwise set it to 0.
*/
#define BAS_BATTERY_LEVEL_NOTIFY_SUPPORT    1

/** @} End of BAS_Common_Exported_Macros */

/** @} End of BAS_CONFIG */

/** @} End of BAS */

#endif


text:
'use strict';

import { objectPropertyTypes } from '../Meta';
import { helpers } from 'utils';
import { Handlebars } from 'lib';

const factory = {
    getCellViewByDataType(type) {
        let result;

        switch (type) {
            case objectPropertyTypes.STRING:
                result = factory.getTextCellView();
                break;
            case objectPropertyTypes.INSTANCE:
                result = factory.getReferenceCellView();
                break;
            case objectPropertyTypes.ACCOUNT:
                result = factory.getUserCellView();
                break;
            case objectPropertyTypes.ENUM:
                result = factory.getEnumCellView();
                break;
            case objectPropertyTypes.INTEGER:
            case objectPropertyTypes.DOUBLE:
            case objectPropertyTypes.DECIMAL:
                result = factory.getNumberCellView();
                break;
            case objectPropertyTypes.DURATION:
                result = factory.getDurationCellView();
                break;
            case objectPropertyTypes.BOOLEAN:
                result = factory.getBooleanCellView();
                break;
            case objectPropertyTypes.DATETIME:
                result = factory.getDateTimeCellView();
                break;
            case objectPropertyTypes.DOCUMENT:
                result = factory.getDocumentCellView();
                break;
            default:
                helpers.throwNotSupportedError(`Data type${type}is not supported`);
                break;
        }

        return result;
    },

    getTextCellView() {
        return factory.__getSimpleView('{{highlightFragment value highlightedFragment}}');
    },

    getReferenceCellView() {
        return factory.__getSimpleView('{{#if value}}{{#if value.name}}{{highlightFragment value.name highlightedFragment}}{{/if}}{{/if}}');
    },

    getUserCellView() {
        return factory.__getAccountView();
    },

    getEnumCellView() {
        return factory.__getEnumView();
    },

    getNumberCellView() {
        return factory.__getSimpleView('{{value}}');
    },

    getDurationCellView() {
        return factory.__getSimpleView('{{renderShortDuration value}}');
    },

    getBooleanCellView() {
        const templateHelpers = {
            showIcon() {
                return _.isBoolean(this.value);
            }
        };

        return factory.__getSimpleView(
            '{{#if showIcon}}' +
                '{{#if value}}<svg class="svg-grid-icons svg-icons_flag-yes"><use xlink:href="#icon-checked"></use></svg>{{/if}}' +
                '{{#unless value}}<svg class="svg-grid-icons svg-icons_flag-none"><use xlink:href="#icon-remove"></use></svg>{{/unless}}' +
            '{{/if}}', templateHelpers);
    },

    getDateTimeCellView() {
        return factory.__getSimpleView('{{#if value}}{{renderFullDate value}}{{/if}}');
    },

    getDocumentCellView() {
        return factory.__getDocumentView();
    },

    __getSimpleView(template, templateHelpers) {
        return Marionette.ItemView.extend({
            template: Handlebars.compile(template),
            modelEvents: {
                'change:highlightedFragment': '__handleHighlightedFragmentChange'
            },
            __handleHighlightedFragmentChange() {
                this.render();
            },
            className: 'grid-cell',
            templateHelpers
        });
    },

    __getAccountView() {
        return Marionette.ItemView.extend({
            template: Handlebars.compile('{{text}}'),
            templateHelpers() {
                const value = this.model.get('value');
                let text = '';
                if (value && value.length > 0) {
                    text = _.chain(value)
                        .map(item => ({
                            id: item.id,
                            text: item.text || item.name || item.columns && item.columns[0]
                        }))
                        .sortBy(member => member.text)
                        .reduce((memo, member) => {
                            if (memo) {
                                return `${memo}, ${member.text}`;
                            }
                            return member.text;
                        }, null)
                        .value();
                } else if (value && value.name) {
                    text = value.name;
                }

                return {
                    text
                };
            },
            modelEvents: {
                'change:highlightedFragment': '__handleHighlightedFragmentChange'
            },
            __handleHighlightedFragmentChange() {
                this.render();
            },
            className: 'grid-cell'
        });
    },

    __getDocumentView() {
        return Marionette.ItemView.extend({
            template: Handlebars.compile('{{#each documents}}{{text}}{{#unless @last}}, {{/unless}}{{/each}}'),

            templateHelpers() {
                const value = this.model.get('value');
                let documents = [];
                if (value && value.length > 0) {
                    documents = _.chain(value)
                        .map(item => ({
                            id: item.id,
                            text: item.text || item.name || item.columns && item.columns[0],
                            url: item.url || item.columns && item.columns[1]
                        }))
                        .sortBy(document => document.text)
                        .value();
                }

                return {
                    documents
                };
            },
            modelEvents: {
                'change:highlightedFragment': '__handleHighlightedFragmentChange'
            },
            __handleHighlightedFragmentChange() {
                this.render();
            },
            className: 'grid-cell'
        });
    },

    __getEnumView() {
        return Marionette.ItemView.extend({
            template: Handlebars.compile('{{#if value}}{{valueExplained}}{{/if}}'),
            modelEvents: {
                'change:highlightedFragment': '__handleHighlightedFragmentChange'
            },
            __handleHighlightedFragmentChange() {
                this.render();
            },
            templateHelpers() {
                const value = this.model.get('value');
                return {
                    value,
                    valueExplained: value.valueExplained
                };
            },
            className: 'grid-cell'
        });
    }
};
export default factory;


text:
package org.edgexfoundry.scheduling;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.edgexfoundry.domain.meta.Addressable;
import org.edgexfoundry.domain.meta.ScheduleEvent;
import org.edgexfoundry.support.logging.client.EdgeXLogger;
import org.edgexfoundry.support.logging.client.EdgeXLoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ScheduleEventHTTPExecutor {

	private static final EdgeXLogger logger = EdgeXLoggerFactory.getEdgeXLogger(ScheduleEventHTTPExecutor.class);

	@Value("${service.timeout}")
	private int timeout;

	@Async
	public void execute(final ScheduleEvent event) {
		int returnCode;
		String body = event.getParameters();
		if(body == null) body = "";
		final String url = getURL(event.getAddressable());

		String method = event.getAddressable().getMethod().toString();

		try {
			if (url == null) {
				logger.info("no address for schedule event " + event.getName());
			} else {
				URL obj = new URL(url);
				HttpURLConnection con = (HttpURLConnection) obj.openConnection();
				con.setRequestMethod(method);
				con.setDoOutput(true);
				con.setConnectTimeout(timeout);
				con.setRequestProperty("Content-Type", "application/json");
				con.setRequestProperty("Content-Length", "" + body.length());
				OutputStream os = null;
				try {
					os = con.getOutputStream();
					os.write(body.getBytes());
					returnCode = con.getResponseCode();
				} finally {
					os.close();
				}
				logger.debug("executed event " + event.getId() + " '" + event.getName() + "' response code " + returnCode + " url '" + url + "' body '" + body + "'");
			}
		} catch (Exception e) {
			logger.error("exception executing event " + event.getId() + " '" + event.getName() + "' url '" + url + "' body '" + body + "' exception " + e.getMessage());
			e.printStackTrace();
		}
	}

	private String getURL(Addressable addressable) {
		if (addressable != null) {
			StringBuilder builder = new StringBuilder(addressable.getProtocol().toString());
			builder.append("://");
			builder.append(addressable.getAddress());
			builder.append(":");
			builder.append(addressable.getPort());
			builder.append(addressable.getPath());
			return builder.toString();
		}
		return null;
	}
}


text:
import React from 'react';
import { mount } from 'enzyme';
import SideNavLink from '../SideNavLink';

describe('SideNavLink', () => {
  let mockProps;

  beforeEach(() => {
    mockProps = {
      className: 'custom-classname',
      children: 'link',
      icon:
icon
,
      isActive: false,
    };
  });

  it('should render', () => {
    const inactive = mount(<SideNavLink {...mockProps} />);
    expect(inactive).toMatchSnapshot();
    const active = mount(<SideNavLink {...mockProps} isActive />);
    expect(active).toMatchSnapshot();
  });
});


text:
module ParsecError
{-# DEPRECATED "This module has moved to Text.ParserCombinators.Parsec.Error" #-}
(module Text.ParserCombinators.Parsec.Error) where
import Text.ParserCombinators.Parsec.Error


text:
using ContextType = extensions::ExtensionBrowserTest::ContextType;

// Tests for extension-controlled prefs, where an extension in lacros sets a
// pref where the underlying feature lives in ash.
class ExtensionPreferenceApiLacrosBrowserTest
    : public extensions::ExtensionApiTest,
      public testing::WithParamInterface<ContextType> {
 public:
  ExtensionPreferenceApiLacrosBrowserTest(
      const ExtensionPreferenceApiLacrosBrowserTest&) = delete;
  ExtensionPreferenceApiLacrosBrowserTest& operator=(
      const ExtensionPreferenceApiLacrosBrowserTest&) = delete;

 protected:
  ExtensionPreferenceApiLacrosBrowserTest() : ExtensionApiTest(GetParam()) {}
  ~ExtensionPreferenceApiLacrosBrowserTest() override = default;

  void CheckPreferencesSet() {
    PrefService* prefs = profile_->GetPrefs();
    // From the lacros perspective, the pref should look extension controlled.
    const PrefService::Preference* pref =
        prefs->FindPreference(prefs::kLacrosAccessibilityAutoclickEnabled);
    ASSERT_TRUE(pref);
    EXPECT_TRUE(pref->IsExtensionControlled());
    EXPECT_TRUE(prefs->GetBoolean(prefs::kLacrosAccessibilityAutoclickEnabled));
  }

  void CheckPreferencesCleared() {
    PrefService* prefs = profile_->GetPrefs();
    const PrefService::Preference* pref =
        prefs->FindPreference(prefs::kLacrosAccessibilityAutoclickEnabled);
    ASSERT_TRUE(pref);
    EXPECT_FALSE(pref->IsExtensionControlled());
    EXPECT_FALSE(
        prefs->GetBoolean(prefs::kLacrosAccessibilityAutoclickEnabled));
  }

  void SetUpOnMainThread() override {
    extensions::ExtensionApiTest::SetUpOnMainThread();

    // The browser might get closed later (and therefore be destroyed), so we
    // save the profile.
    profile_ = browser()->profile();

    // Closing the last browser window also releases a module reference. Make
    // sure it's not the last one, so the message loop doesn't quit
    // unexpectedly.
    keep_alive_ = std::make_unique<ScopedKeepAlive>(
        KeepAliveOrigin::BROWSER, KeepAliveRestartOption::DISABLED);
  }

  void TearDownOnMainThread() override {
    // BrowserProcess::Shutdown() needs to be called in a message loop, so we
    // post a task to release the keep alive, then run the message loop.
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::BindOnce(&std::unique_ptr<ScopedKeepAlive>::reset,
                                  base::Unretained(&keep_alive_), nullptr));
    content::RunAllTasksUntilIdle();

    extensions::ExtensionApiTest::TearDownOnMainThread();
  }

  bool IsServiceAvailable() {
    if (chromeos::LacrosService::Get()->GetInterfaceVersion(
            crosapi::mojom::Prefs::Uuid_) <
        static_cast<int>(crosapi::mojom::Prefs::MethodMinVersions::
                             kGetExtensionPrefWithControlMinVersion)) {
      LOG(WARNING) << "Unsupported ash version.";
      return false;
    }
    return true;
  }

  bool DoesAshSupportObservers() {
    // Versions of ash without this capability cannot create observers for prefs
    // writing to the ash standalone browser prefstore.
    constexpr char kExtensionControlledPrefObserversCapability[] =
        "crbug/1334964";
    return chromeos::BrowserParamsProxy::Get()->AshCapabilities().has_value() &&
           base::Contains(
               chromeos::BrowserParamsProxy::Get()->AshCapabilities().value(),
               kExtensionControlledPrefObserversCapability);
  }

  raw_ptr<Profile> profile_ = nullptr;
  std::unique_ptr<ScopedKeepAlive> keep_alive_;
};

INSTANTIATE_TEST_SUITE_P(EventPage,
                         ExtensionPreferenceApiLacrosBrowserTest,
                         ::testing::Values(ContextType::kPersistentBackground));

IN_PROC_BROWSER_TEST_P(ExtensionPreferenceApiLacrosBrowserTest, Lacros) {
  if (!IsServiceAvailable()) {
    return;
  }
  absl::optional<::base::Value> out_value;
  crosapi::mojom::PrefsAsyncWaiter async_waiter(
      chromeos::LacrosService::Get()->GetRemote<crosapi::mojom::Prefs>().get());

  // At start, the value in ash should not be set.
  async_waiter.GetPref(crosapi::mojom::PrefPath::kAccessibilityAutoclickEnabled,
                       &out_value);
  EXPECT_FALSE(out_value.value().GetBool());

  base::FilePath extension_path =
      test_data_dir_.AppendASCII("preference/lacros");
  {
    extensions::ResultCatcher catcher;
    ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
    EXPECT_TRUE(LoadExtension(extension_path)) << message_;
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    // Run the tests.
    listener.Reply("run test");
    EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  }
  CheckPreferencesSet();

  // In ash, the value should now be set.
  async_waiter.GetPref(crosapi::mojom::PrefPath::kAccessibilityAutoclickEnabled,
                       &out_value);
  EXPECT_TRUE(out_value.value().GetBool());

  // The settings should not be reset when the extension is reloaded.
  {
    ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
    ReloadExtension(last_loaded_extension_id());
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    listener.Reply("");
  }
  CheckPreferencesSet();

  // Uninstalling and installing the extension (without running the test that
  // calls the extension API) should clear the settings.
  extensions::TestExtensionRegistryObserver observer(
      extensions::ExtensionRegistry::Get(profile_), last_loaded_extension_id());
  UninstallExtension(last_loaded_extension_id());
  observer.WaitForExtensionUninstalled();
  CheckPreferencesCleared();

  if (DoesAshSupportObservers()) {
    // When the extension in uninstalled, the pref in lacros should be the
    // default value (false). This only works if Ash correctly implements
    // extension-controlled pref observers.
    async_waiter.GetPref(
        crosapi::mojom::PrefPath::kAccessibilityAutoclickEnabled, &out_value);
    EXPECT_FALSE(out_value.value().GetBool());
  }

  {
    ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
    EXPECT_TRUE(LoadExtension(extension_path));
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    listener.Reply("");
  }
  CheckPreferencesCleared();
}

IN_PROC_BROWSER_TEST_P(ExtensionPreferenceApiLacrosBrowserTest, OnChange) {
  if (!IsServiceAvailable()) {
    return;
  }
  if (!DoesAshSupportObservers()) {
    LOG(WARNING) << "Ash does not support observers, skipping the test.";
    return;
  }
  EXPECT_TRUE(RunExtensionTest("preference/onchange_lacros", {},
                               {.allow_in_incognito = false}))
      << message_;
}

// The extension controlled pref observers are only instantiated when a listener
// is actually attached. The purpose of running this test is to ensure that they
// are instantiated as we use the prefs api to create the observer. See also
// crbug/1334985.
IN_PROC_BROWSER_TEST_P(ExtensionPreferenceApiLacrosBrowserTest,
                       CreateObservers) {
  EXPECT_TRUE(
      RunExtensionTest("preference/onchange", {}, {.allow_in_incognito = true}))
      << message_;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="DEFAULT_WRAPPED" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleJvm" value="1.8" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/pullloadview" />
            <option value="$PROJECT_DIR$/simple" />
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>


text:
Android WatchViewStub Sample
===================================

This sample has been deprecated.


text:
layout: post
title: Déployer un environnement jetable avec un conteneur LXC
---

![head]({{ site.baseurl }}/images/head.png){:class="img-responsive"}

 Il m'arrive souvent, par manque de temps, de lancer des tests sur ma machine. Ces tests finissent par rendre mon système instable au fil du temps.

De plus, les CTF et autres challenges sont souvent particuliers, il est donc parfois intérèssant d'avoir un environnement jetable qui puisse être remonté rapidement.

Bien entendus une VM aurait fait l'affaire mais elle inclut un plus grand overhead.

### Installation de LXC

Sur Debian, voici ce que j'ai installé :

``` bash
sudo apt-get install lxc lxctl lxc-templates bridge-utils
```

### Déploiement de notre conteneur

> Ici mon conteneur se nomme **debian**

On commence par lister les templates disponibles :

```bash
ls /usr/share/lxc/templates
lxc-alpine     lxc-centos    lxc-fedora        lxc-oracle      lxc-sshd
lxc-altlinux   lxc-cirros    lxc-gentoo        lxc-plamo       lxc-ubuntu
lxc-archlinux  lxc-debian    lxc-openmandriva  lxc-slackware   lxc-ubuntu-cloud
lxc-busybox    lxc-download  lxc-opensuse      lxc-sparclinux
```

Dans mon cas, je pars sur un debian :

```bash
lxc-create -n deb -t debian
```

**-n** représente le nom du conteneur

**-t** représente le template choisis

L'initialisation peu prendre un peut de temps, patientez et prenez un café.

On va maintenant lancer notre conteneur :

```bash
sudo lxc-start -n debian
lxc-start: tools/lxc_start.c: main: 366 The container failed to start.
lxc-start: tools/lxc_start.c: main: 368 To get more details, run the container in foreground mode.
lxc-start: tools/lxc_start.c: main: 370 Additional information can be obtained by setting the --logfile and --logpriority options.
```

Oups ! une erreur s'est produite. Cette erreur provient du fait que l'interface réseau spécifié par notre fichier de configuration est mauvaise.

Mon fix consiste a me brancher sur le bridge par défaut créé par virt-manager :

```bash
sudo vi /var/lib/lxc/debian/config
# Modifier la ligne suivante :
lxc.network.link = br0
# avec cette ligne :
lxc.network.link = virbr0
```

Puis relancer le conteneur.

##### Autres possibilités:

Décommentez la ligne suivent dans `/etc/sysctl.conf`:

```
# Décommentez la prochaine ligne pour activer le "packet forwarding" pour IPv4
net.ipv4.ip_forward=1
```

Insérez les lignes suivantes dans `/etc/network/interfaces` :

```
auto lxc-bridge-nat
iface lxc-bridge-nat inet static
        bridge_ports none
        bridge_fd 0
        bridge_maxwait 0
        address 192.168.100.1
        netmask 255.255.255.0
        up iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
```

Enfin on modifie le fichier de configuration en conséquence :

```bash
sudo vi /var/lib/lxc/debian/config
# Modifier la ligne suivante :
lxc.network.link = br0
# avec cette ligne :
lxc.network.link = lxc-bridge-nat
```

On vient ici de créer un bridge puis un NAT, ce dernier va nous permettre d'accéder a internet depuis le conteneur.

### On se lance !

Voici un workflow classique sur LXC :

```bash
# On liste les conteneurs
sudo lxc-ls
# On lance notre LXC
sudo lxc-start -n debian
# On attache un prompt au LXC
sudo lxc-attach -n debian
# Une fois finis, on coupe le conteneur
sudo lxc-stop -n debian
# Si on le souhaite on le supprime
sudo lxc-destroy debian
```

## Limitation des ressources allouées au conteneur

On va éditer notre fichier de configuration (**/var/lib/lxc/debian/config**) et on y ajoute ces lignes en fin de fichier :

```bash
lxc.cgroup.memory.limit_in_bytes = 250M
lxc.cgroup.cpuset.cpus = 0
```

Ici on assigne le CPU numéro 0 au conteneur et enfin on limite la ram alloué a 250 Mb.

On vérifie :

```bash
# nombre de cpu du conteneur
root@debian:/> cat /proc/cpuinfo | grep "processor" | wc -l
1
# Ram alloué
root@debian:/> free -h
              total        used        free      shared  buff/cache   available
Mem:           250M        5.9M        236M        171M        8.1M        236M
Swap:          8.0G          0B        8.0G
```

Comme on le voit, ici on a bien la limitation souhaitée.

## Exemple de configuration type :

```
# Networking
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = virbr0
lxc.network.hwaddr = 00:FF:AA:00:00:01
lxc.network.ipv4 = 192.168.122.110/24
lxc.network.ipv4.gateway = 192.168.122.1

#RootFS
lxc.rootfs = /var/lib/lxc/debi/rootfs
lxc.rootfs.backend = dir

# Limitation of the host ressource usage
lxc.cgroup.memory.limit_in_bytes = 250M
lxc.cgroup.cpuset.cpus = 0

# Common configuration
lxc.include = /usr/share/lxc/config/debian.common.conf

# Container specific configuration
lxc.tty = 4
lxc.utsname = debi
lxc.arch = amd64
```

## Edit du 17/10/2019
Il semble que sur les derniéres versions de Ubuntu la signature GPG des templates fonctionne mal.
Il existe néanmoins une solution vraiment pratique car elle télécharge directement une image suivant vos besoins :

~~~bash
jugu@WORKSTATION:~$ sudo lxc-create -n zetta_pgsql -t download
Setting up the GPG keyring
Downloading the image index

---
DIST	RELEASE	ARCH	VARIANT	BUILD
---
debian	bullseye	s390x	default	20191017_05:24
debian	buster	amd64	default	20191017_05:24
debian	buster	arm64	default	20191017_06:13
debian	buster	armel	default	20191017_05:40
debian	buster	armhf	default	20191017_05:24
debian	buster	i386	default	20191017_05:24
funtoo	1.3	i386	default	20191017_16:45
gentoo	current	amd64	default	20191017_16:07
gentoo	current	armhf	default	20191017_16:07
gentoo	current	i386	default	20191017_16:07

---

Distribution:
debian
Release:
buster
Architecture:
amd64

Downloading the image index
Downloading the rootfs
Downloading the metadata
The image cache is now ready
Unpacking the rootfs

---
You just created a Debian buster amd64 (20191017_05:24) container.

To enable SSH, run: apt install openssh-server
No default root or user password are set by LXC.
~~~
L'option `download` permet de choisir depuis une liste d'images ce qui offre un grand choix de distribution/architectures.

> Note: Cela me donne envie de tester un conteneur Kali !

## Conclusion

On à vue ici qu'il etait possible de créer un conteneur rapidement et que cette technique est parfois plus adapté qu'une machine virtuelle dans le cadre de CTF.

Pour ma part, cette technique fait désormais partie de ma boite à outils spécifiques aux CTF.


text:
from abc import ABCMeta, abstractmethod

from Src.Core.Entity.ProcessInfo import ProcessInfo

class BioDataImporterBase(metaclass=ABCMeta):
    """
    Abstract class responsible for importing biological data
    """
    @abstractmethod
    def execute(self) -> ProcessInfo:
        """
        Execute the import data process for specific biological data.
        This method must be implemented.
        :return: information about the importation
        """
        pass


text:
package dev.ahamed.mva.sample.view.expansion;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import dev.ahamed.mva.sample.R;
import dev.ahamed.mva.sample.data.model.FaqItem;
import mva2.adapter.ItemBinder;
import mva2.adapter.ItemViewHolder;

public class ExpandableItemBinder extends ItemBinder<FaqItem, ExpandableItemBinder.ViewHolder> {

  @Override public ViewHolder createViewHolder(ViewGroup parent) {
    return new ViewHolder(inflate(parent, R.layout.item_faq));
  }

  @Override public void bindViewHolder(ViewHolder holder, FaqItem item) {
    holder.toggle.setImageResource(
        holder.isItemExpanded() ? R.drawable.ic_expand_less : R.drawable.ic_expand_more);
    holder.question.setText(item.getQuestion());
    holder.answer.setVisibility(holder.isItemExpanded() ? View.VISIBLE : View.GONE);
    if (holder.isItemExpanded()) {
      holder.answer.setText(item.getAnswer());
    }
  }

  @Override public boolean canBindData(Object item) {
    return item instanceof FaqItem;
  }

  static class ViewHolder extends ItemViewHolder<FaqItem> {

    TextView question;
    TextView answer;
    ImageView toggle;

    public ViewHolder(View itemView) {
      super(itemView);
      question = itemView.findViewById(R.id.tv_question);
      answer = itemView.findViewById(R.id.tv_answer);
      toggle = itemView.findViewById(R.id.iv_toggle);
      toggle.setOnClickListener(v -> toggleItemExpansion());
    }
  }
}


text:
UnixPanel::UnixPanel(UnixWindow* panel)
    : MainPanel((QWidget*) panel),
      unixPanel(panel)
{
    this->adjustSize();
}

void UnixPanel::pushButtonMinimize()
{
    unixPanel->minimize();
}

void UnixPanel::pushButtonMaximize()
{
    unixPanel->maximize();
}

void UnixPanel::pushButtonClose()
{
    unixPanel->closeWindow();
}


text:
package alluxio.client.keyvalue;

import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.client.AbstractOutStream;
import alluxio.util.io.ByteIOUtils;

import com.google.common.base.Preconditions;

import java.io.IOException;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * Writer that implements {@link KeyValuePartitionWriter} using the Alluxio file stream interface to
 * generate a single-block key-value file.
 *

 * A partition file consists of:
 *

 *
A payload buffer which is an array of (key,value) pairs;

 *
A index which is a hash table maps each key to the offset in bytes into the payload
 *   buffer;

 *
A 4-bytes pointer in the end indicating the offset of the index.

 *

 *
 */
@NotThreadSafe
final class BaseKeyValuePartitionWriter implements KeyValuePartitionWriter {
  /** Handle to write to the underlying file. */
  private final AbstractOutStream mFileOutStream;
  /** Number of key-value pairs added. */
  private int mKeyCount = 0;
  /** Key-value index. */
  private Index mIndex;
  /** Key-value payload. */
  private PayloadWriter mPayloadWriter;
  /** Whether this writer is closed. */
  private boolean mClosed;
  /** Whether this writer is canceled. */
  private boolean mCanceled;
  /** Maximum size of this partition in bytes. */
  private long mMaxSizeBytes;

  /**
   * Constructs a {@link BaseKeyValuePartitionWriter} given an output stream.
   *
   * @param fileOutStream output stream to store the key-value file
   */
  BaseKeyValuePartitionWriter(AbstractOutStream fileOutStream) {
    mFileOutStream = Preconditions.checkNotNull(fileOutStream, "fileOutStream");
    // TODO(binfan): write a header in the file

    mPayloadWriter = new BasePayloadWriter(mFileOutStream);
    mIndex = LinearProbingIndex.createEmptyIndex();
    mClosed = false;
    mCanceled = false;
    mMaxSizeBytes = Configuration.getBytes(PropertyKey.KEY_VALUE_PARTITION_SIZE_BYTES_MAX);
  }

  @Override
  public void close() throws IOException {
    if (mClosed) {
      return;
    }
    if (mCanceled) {
      mFileOutStream.cancel();
    } else {
      build();
      mFileOutStream.close();
    }
    mClosed = true;
  }

  @Override
  public void cancel() throws IOException {
    mCanceled = true;
    close();
  }

  @Override
  public void put(byte[] key, byte[] value) throws IOException {
    Preconditions.checkNotNull(key, "key");
    Preconditions.checkNotNull(value, "value");
    Preconditions.checkArgument(key.length > 0, "Cannot put an empty key");
    Preconditions.checkArgument(value.length > 0, "Cannot put an empty value");
    Preconditions.checkState(!mClosed);
    mIndex.put(key, value, mPayloadWriter);
    mKeyCount++;
  }

  @Override
  public boolean canPut(byte[] key, byte[] value) {
    // See BasePayloadWriter.insert()
    // TODO(binfan): also take into account the potential index size change
    return byteCount() + key.length + value.length
        + Constants.BYTES_IN_INTEGER * 2 <= mMaxSizeBytes;
  }

  /**
   * @return number of keys
   */
  @Override
  public int keyCount() {
    return mKeyCount;
  }

  /**
   * @return number of bytes estimated
   */
  public long byteCount() {
    Preconditions.checkState(!mClosed);
    // last pointer to index
    return mFileOutStream.getBytesWritten() + mIndex.byteCount() + Integer.SIZE / Byte.SIZE;
  }

  private void build() throws IOException {
    Preconditions.checkState(!mClosed);
    mFileOutStream.flush();
    int indexOffset = mFileOutStream.getBytesWritten();
    mFileOutStream.write(mIndex.getBytes());
    ByteIOUtils.writeInt(mFileOutStream, indexOffset);
  }
}


text:
extern "C" {
#endif

// Release the memory used for a GumboAttribute, including the attribute itself
void gumbo_destroy_attribute(GumboAttribute* attribute);

#ifdef __cplusplus
}
#endif

#endif // GUMBO_ATTRIBUTE_H_


text:
declare module '@node/electron' {
  var ipcRenderer: any;
  var remote: any;
  export { ipcRenderer, remote };
}


text:
**Contributors:** [alpipego](https://profiles.wordpress.org/alpipego)
**Tags:** dynamic images, dynamic, image, png, jpg, gif, photo, media library, on-the-fly, resize
**Stable tag:** 3.2.6
**License:** MIT
**Requires at least:** 4.7.0
**Requires PHP:** 5.6
**Tested up to:** 5.6

Dynamically resize your WordPress images on the fly. Upload them once and don't worry about missing or new image sizes.

## Description ##
Instead of creating image sizes on upload, this plugin only creates them when requested.

Normally after activating a new theme or plugin that adds new image sizes, you will have to use a tool like [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) to create the newly registered image sizes. Depending on the size of the media library and the "power" of your server, this might take a while or even take several tries to process all your images; and in the end, you don't even know if you'll need all of the resized images.

This plugin takes care of the resizing dynamically and creates the requested size the moment it is first requested—and only when it is requested.

### Support ###
For users: Please use the support forums on [wordpress.org](https://wordpress.org/support/plugin/resizefly)

For developers: Head over to the [Github repository](https://github.com/alpipego/resizefly/)

For everything else, find me on [twitter](https://twitter.com/alpipego) or on slack

## Installation ##
1. Upload the plugin to your plugins directory (usually `wp-content/plugins`)
2. Make sure you have Pretty Permalinks enabled
3. Activate the plugin

The plugin handles the images from here on. The resized images are saved in a subfolder inside your uploads directory.

### Prerequisites ###

You'll need at least PHP 5.5, WordPress 4.7 and either GD or Imagick on your server.

### Uninstalling ###

If you want to uninstall the plugin for good, make sure to regenerate your image thumbnails/sizes afterward using [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) or similar.

## Frequently Asked Questions ##

### Why does this not work when using NGINX? ###
Often your NGINX is configured in a way to serve the image as a static resource and in case of failure throw a 404 Not Found error.

To work around this, make sure the request is sent to WordPress when the image cannot be found.

Add a directive like:

    location ~* (/[^/]+/)?uploads/(.+\.(png|gif|jpe?g)) {
        try_files $uri $uri/ /index.php?q=$uri&$args;
        expires max;
        log_not_found off;
        access_log off;
    }

If you have one long location directive listing all the static file formats (css, js, zip, etc.), you can also just drop the `try_files $uri $uri/ /index.php?q=$uri&$args;` in there.

### Why is there a `resizefly-duplicate` directory in my uploads folder? ###
The plugin stores an optimized duplicate of each image in this folder. The reason for this is, that image resizing puts a strain on your server and uses comparably a lot of resources. To minimize this ResizeFly creates an optimized copy from which the smaller image sizes will be created.

## Changelog ##

### 3.2.6 ###

* fix issue with trying to add number to string
* revert methods to get image id to prevent db strain

see https://github.com/alpipego/resizefly/releases for full changelog


text:
package org.nbandroid.netbeans.gradle.v2.sdk.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;

/**
 * @author ArSi
 */
@ActionID(id = "org.nbandroid.netbeans.gradle.v2.sdk.ui.SdksCustomizerAction", category = "Tools")
@ActionRegistration(iconInMenu = false, displayName = "#CTL_PlatformManager")
@ActionReference(position = 310, name = "SdksCustomizerAction", path = "Menu/Tools")
@NbBundle.Messages("CTL_PlatformManager=&Android SDKs")
public final class SdksCustomizerAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        SdksCustomizer.showCustomizer();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DiceButton">
        <attr name="rollModel" format="string" />
        <attr name="isCustom" format="boolean" />
    </declare-styleable>
</resources>


text:
JENKINS_API = r"api/python/"
LOAD_TIMEOUT = 30
LOAD_ATTEMPTS = 5


text:
using System;
using System.Linq;
using Ornament.Uow;

namespace Ornament.Stores
{
    /// <summary>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TId"></typeparam>
    public interface IStore<T, TId> : IDisposable
        where T : class
        where TId : IEquatable<TId>
    {
        /// <summary>
        /// get unit of work instance.
        /// </summary>
        IUnitOfWork Uow { get; }

        T Get(TId id);

        void Delete(TId id);

    }
}


text:
layout: post
title: State-Of-The-Art Unsupervised Part-Of-Speech Tagging in 300 lines of Clojure  (from
  Scratch)
categories:
- computer science
tags: []
status: publish
latex: true
type: post
published: true
excerpt: A complete unsupervised part-of-speech model in 30 lines of Clojure
meta:
  _edit_last: '1'
  superawesome: 'false'
  jabber_published: '1284428358'
  _wp_old_slug: ''
---
Recently, Yoong-Keok Lee, Regina Barzilay, and myself, published a paper on doing unsupervised part-of-speech tagging. I.e., how do we learn syntactic categories of words from raw text. This model is actually pretty simple relevant to other published papers and actually yields the best results on several languages. The C++ code for this project is available and can finish in under a few minutes for a large corpus.

Although the model is pretty simple, you might not be able to tell from the C++ code, despite Yoong being a top-notch coder. The problem is the language just doesn't facilitate expressiveness the way my favorite language, Clojure, does. In fact the entire code for the model, without dependencies beyond the language and the standard library, clojure contrib, can be written in about 300 lines of code, complete with comments. This includes a lot of standard probabilistic computation utilities necessary for doing something like Gibbs Sampling, which is how inference is done here.

Without further ado, the code is on gisthub and github (in case I make changes).

{% gist 578348 %}


text:
import test from 'ava';
import { isMutable, modify } from '@collectable/core';
import { HashSetStructure, fromArray, has, size, subtract } from '../../src';

const mainValues = ['A', 'B', 'C', 'D', 'E'];
const otherValues = ['D', 'E', 'F', 'G'];
const expectedValues = ['A', 'B', 'C'];

let main: HashSetStructure<string>, result: HashSetStructure<string>;
let other: Iterable<string>;

test.before(() => {
  other = new Set(otherValues).values();
  main = modify(fromArray(mainValues));
  result = subtract(other, main);
});

test('the input set is returned', t => {
  t.is(result, main);
});

test('the input set is still mutable', t => {
  t.true(isMutable(result));
});

test('the input set no longer includes any items that were emitted by the input iterable', t => {
  t.true(has('A', result));
  t.true(has('B', result));
  t.true(has('C', result));
});

test('the input set retains items that were not emitted by the input iterable', t => {
  t.false(has('D', result));
  t.false(has('E', result));
});

test('the size of the input set is decreased by the number of items that were common to both inputs', t => {
  t.is(size(result), expectedValues.length);
});


text:
describe("Thumbs.Class", function () {

    var Animal = Thumbs.Class.extend({});

    beforeEach(function () {
    });

    afterEach(function () {
    });

    it("should inherit the extend method", function () {
        var spy = sinon.spy();
        var Dog = Animal.extend({
            bark: spy
        });
        var Poodle = Dog.extend({});
        expect(Poodle.prototype.bark).toBeAFunction();
        var dog = new Poodle();
        dog.bark();
        expect(spy).toHaveBeenCalledOnce();
    });

    it("should inherit the _super method", function () {
        var Dog = Animal.extend({
            bark: function () {
                return 'woof';
            }
        });

        var Poodle = Dog.extend({
            bark: function () {
                return this._super('bark', arguments) + ' ruff';
            }
        });

        var dog = new Poodle();
        expect(dog.bark()).toBe('woof ruff');
    });

    it("should inherit Thumbs.Events", function () {
        var Dog = Animal.extend({
            bark: function () {
                this.trigger('bark', true);
            }
        });

        var spy = sinon.spy();
        var dog = new Dog();
        dog.on('bark', spy);
        dog.bark();
        expect(spy).toHaveBeenCalledOnce();
    });

    it("should receive a unique id", function () {
        var animal = new Animal();
        expect(animal.cid).toBeDefined();
    });
});


text:
package no.tornado.brap.common;

import java.io.Serializable;

/**
 * The response to an InvocationRequest is created by the
 * ProxyServlet after invocation.
 *
 */
public class InvocationResponse implements Serializable {
    private static final long serialVersionUID = 6091102541452095141L;

    /**
     * Will hold any exception thrown by either the remote service method itself,
     * or by the ProxyServlet if it encounters an error while invoking
     * or preparing to invoke the method.
     */
    private Throwable exception;

    /**
     * The result of the method invocation if no exceptions are thrown.
     */
    private Serializable result;

    /**
     * List of modifications that occured on the server while executing the remote operation.
     * The ServiceProxy will apply the changes to the local argument objects after method invocation returns.
     */
    private ModificationList[] modifications;

    public Throwable getException() {
        return exception;
    }

    public void setException(Throwable exception) {
        this.exception = exception;
    }

    public Serializable getResult() {
        return result;
    }

    public void setResult(Serializable result) {
        this.result = result;
    }

    public ModificationList[] getModifications() {
        return modifications;
    }

    public void setModifications(ModificationList[] modifications) {
        this.modifications = modifications;
    }
}


text:
import * as childProcess from 'child_process';
import * as crypto from 'crypto';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import * as util from 'util';

const execFilePromise = util.promisify(childProcess.execFile);
const execPromise = util.promisify(childProcess.exec);

import {MountPoint} from './server';
import {BenchmarkSpec, GitDependency, NpmPackageJson, PackageDependencyMap, PackageVersion} from './types';
import {fileKind, runNpm, throwUnreachable} from './util';

interface GitDependencyWithTempDir extends GitDependency {
  tempDir: string;
  sha: string;
}

/**
 * Parse an array of strings of the form <package>@<version>.
 */
export function parsePackageVersions(flags: string[]): PackageVersion[] {
  const versions: PackageVersion[] = [];
  for (const flag of flags) {
    const match = flag.match(/^(?:(.+)=)?(.+)@(.+)$/);
    if (match === null) {
      throw new Error(`Invalid package format ${flag}`);
    }
    const [, label, dep, version] = match;
    versions.push({
      label: label || `${dep}@${version}`,
      dependencyOverrides: {
        [dep]: version,
      },
    });
  }
  return versions;
}

export interface ServerPlan {
  /** The benchmarks this server will handle. */
  specs: BenchmarkSpec[];
  /** NPM installations needed for this server. */
  npmInstalls: NpmInstall[];
  /** URL to disk path mappings. */
  mountPoints: MountPoint[];
}

export interface NpmInstall {
  installDir: string;
  packageJson: NpmPackageJson;
}

export async function makeServerPlans(
    benchmarkRoot: string, npmInstallRoot: string, specs: BenchmarkSpec[]):
    Promise<{plans: ServerPlan[], gitInstalls: GitDependencyWithTempDir[]}> {
  const depSwaps = new Map<string, {
    installDir: string,
    packageJsonPath: string,
    specs: BenchmarkSpec[],
    dependencies: PackageDependencyMap,
  }>();
  const defaultSpecs = [];
  const gitInstalls = new Map<string, GitDependencyWithTempDir>();
  for (const spec of specs) {
    if (spec.url.kind === 'remote') {
      // No server needed for remote URLs.
      continue;
    }
    if (spec.url.version === undefined) {
      defaultSpecs.push(spec);
      continue;
    }

    const diskPath = path.join(benchmarkRoot, spec.url.urlPath);
    const kind = await fileKind(diskPath);
    if (kind === undefined) {
      throw new Error(`No such file or directory ${diskPath}`);
    }
    const originalPackageJsonPath = await findPackageJsonPath(
        kind === 'file' ? path.dirname(diskPath) : diskPath);
    if (originalPackageJsonPath === undefined) {
      throw new Error(`Could not find a package.json for ${diskPath}`);
    }
    const originalPackageJson =
        await fsExtra.readJson(originalPackageJsonPath) as NpmPackageJson;

    const updatedDeps: PackageDependencyMap = {
      ...originalPackageJson.dependencies,
    };
    for (const pkg of Object.keys(spec.url.version.dependencyOverrides)) {
      const version = spec.url.version.dependencyOverrides[pkg];
      if (typeof version === 'string') {
        // NPM dependency syntax that can be handled directly by NPM without any
        // help from us. This includes NPM packages, file paths, git repos (but
        // not monorepos!), etc. (see
        // https://docs.npmjs.com/configuring-npm/package-json.html#dependencies)
        updatedDeps[pkg] = version;
      } else {
        switch (version.kind) {
          case 'git':
            // NPM doesn't support directly installing from a sub-directory of a
            // git repo, like in monorepos, so we handle those cases ourselves.

            // Immediately resolve the git reference (branch, tag, etc.) to a
            // SHA and use that going forward, so that we never fall behind the
            // origin repo when re-using temp directories.
            const sha = looksLikeGitSha(version.ref) ?
                version.ref :
                await remoteResolveGitRefToSha(version.repo, version.ref);
            if (sha === undefined) {
              throw new Error(`Git repo ${
                  version.repo} could not resolve ref "${version.ref}"`);
            }

            // This hash uniquely identifies a `git clone` directory for some
            // dependency at a particular SHA, with a particular setup routine.
            const gitInstallHash = hashStrings(
                // Include the tachometer version in case any changes or bugs
                // would affect how we do this installation.
                tachometerVersion,
                version.repo,
                sha,
                JSON.stringify(version.setupCommands));
            const tempDir = path.join(npmInstallRoot, gitInstallHash);
            const tempPackageDir =
                version.subdir ? path.join(tempDir, version.subdir) : tempDir;
            updatedDeps[pkg] = tempPackageDir;
            // We're using a Map here because we want to de-duplicate git
            // installations that have the exact same parameters, since they can
            // be re-used across multiple benchmarks.
            gitInstalls.set(gitInstallHash, {...version, tempDir, sha});
            break;
          default:
            throwUnreachable(
                version.kind,
                'Unknown dependency version kind: ' + version.kind);
        }
      }
    }

    // This hash uniquely identifes the `npm install` location for some
    // `package.json` where some of its dependencies have been swapped.
    const depSwapHash = hashStrings(
        // Include the tachometer version in case any changes or bugs
        // would affect how we do this installation.
        tachometerVersion,
        originalPackageJsonPath,
        // Sort deps by package name for more temp-directory cache hits since
        // the order declared in the dependencies object doesn't matter.
        JSON.stringify(
            Object.entries(updatedDeps)
                .sort(([pkgA], [pkgB]) => pkgA.localeCompare(pkgB))));

    let swap = depSwaps.get(depSwapHash);
    if (swap === undefined) {
      swap = {
        specs: [],
        installDir: path.join(npmInstallRoot, depSwapHash),
        dependencies: updatedDeps,
        packageJsonPath: originalPackageJsonPath,
      };
      depSwaps.set(depSwapHash, swap);
    }
    swap.specs.push(spec);
  }

  const plans = [];

  if (defaultSpecs.length > 0) {
    plans.push({
      specs: defaultSpecs,
      npmInstalls: [],
      mountPoints: [
        {
          urlPath: `/`,
          diskPath: benchmarkRoot,
        },
      ],
    });
  }

  for (const {specs, installDir, dependencies, packageJsonPath} of depSwaps
           .values()) {
    plans.push({
      specs,
      npmInstalls: [{
        installDir,
        packageJson: {
          private: true,
          dependencies,
        }
      }],
      mountPoints: [
        {
          urlPath: path.posix.join(
              '/',
              path.relative(benchmarkRoot, path.dirname(packageJsonPath))
                  .replace(path.win32.sep, '/'),
              'node_modules'),
          diskPath: path.join(installDir, 'node_modules'),
        },
        {
          urlPath: `/`,
          diskPath: benchmarkRoot,
        },
      ],
    });
  }

  return {plans, gitInstalls: [...gitInstalls.values()]};
}

// TODO(aomarks) Some consolidation with install.ts may be possible.
async function findPackageJsonPath(startDir: string):
    Promise<string|undefined> {
  let cur = path.resolve(startDir);
  while (true) {
    const possibleLocation = path.join(cur, 'package.json');
    if (await fsExtra.pathExists(possibleLocation)) {
      return possibleLocation;
    }
    const parentDir = path.resolve(cur, '..');
    if (parentDir === cur) {
      return undefined;
    }
    cur = parentDir;
  }
}

export function hashStrings(...strings: string[]) {
  return crypto.createHash('sha256')
      .update(JSON.stringify(strings))
      .digest('hex');
}

export const tachometerVersion =
    require(path.join(__dirname, '..', 'package.json')).version;

/**
 * Name of special file used to indicate that an NPM or git install directory
 * completed successfully.
 */
const installSuccessFile = '__TACHOMETER_INSTALL_SUCCESS__';

/**
 * Write the given package.json to the given directory and run "npm install" in
 * it. If the directory already exists, don't do anything except log.
 */
export async function prepareVersionDirectory(
    {installDir, packageJson}: NpmInstall,
    forceCleanInstall: boolean): Promise<void> {
  if (forceCleanInstall) {
    await fsExtra.remove(installDir);
  } else if (await fsExtra.pathExists(installDir)) {
    if (await fsExtra.pathExists(path.join(installDir, installSuccessFile))) {
      console.log(`\nRe-using NPM install dir:\n ${installDir}\n`);
      return;
    } else {
      console.log(`\nCleaning up failed npm install:\n  ${installDir}\n`);
      await fsExtra.remove(installDir);
    }
  }

  console.log(`\nRunning npm install in temp dir:\n  ${installDir}\n`);
  await fsExtra.ensureDir(installDir);
  await fsExtra.writeFile(
      path.join(installDir, 'package.json'),
      JSON.stringify(packageJson, null, 2));
  await runNpm(['install'], {cwd: installDir});
  await fsExtra.writeFile(path.join(installDir, installSuccessFile), '');
}

/**
 * Check out the given commit from the given git repo, and run setup commands.
 * If the directory already exists, don't do anything except log.
 */
export async function installGitDependency(
    gitInstall: GitDependencyWithTempDir,
    forceCleanInstall: boolean): Promise<void> {
  if (forceCleanInstall) {
    await fsExtra.remove(gitInstall.tempDir);
  } else if (await fsExtra.pathExists(gitInstall.tempDir)) {
    if (await fsExtra.pathExists(
            path.join(gitInstall.tempDir, installSuccessFile))) {
      console.log(
          `\nRe-using git checkout:\n` +
          `  ${gitInstall.repo}#${gitInstall.ref}\n` +
          `  ${gitInstall.tempDir}\n`);
      return;
    } else {
      console.log(
          `\nCleaning up failed git checkout:\n  ${gitInstall.tempDir}\n`);
      await fsExtra.remove(gitInstall.tempDir);
    }
  }

  console.log(
      `\nFetching git commit to temp dir:\n` +
      `  ${gitInstall.repo}#${gitInstall.ref}\n` +
      `  ${gitInstall.tempDir}\n`);
  // This approach only requires us to hit the remote repo once (as opposed to
  // using `git clone`, which doesn't support fetching only one commit).
  await fsExtra.ensureDir(gitInstall.tempDir);
  const cwdOpts = {cwd: gitInstall.tempDir};
  await execFilePromise('git', ['init'], cwdOpts);
  await execFilePromise(
      'git', ['remote', 'add', 'origin', gitInstall.repo], cwdOpts);
  await execFilePromise(
      'git', ['fetch', 'origin', '--depth=1', gitInstall.sha], cwdOpts);
  await execFilePromise('git', ['checkout', gitInstall.sha], cwdOpts);

  for (const setupCommand of gitInstall.setupCommands || []) {
    console.log(`\nRunning setup command:\n  ${setupCommand}\n`);
    await execPromise(setupCommand, cwdOpts);
  }
  await fsExtra.writeFile(
      path.join(gitInstall.tempDir, installSuccessFile), '');
}

/**
 * Return whether the given string looks like a 40-characters of hexadecimal,
 * i.e. a valid full length git commit SHA-1 hash.
 */
function looksLikeGitSha(ref: string): boolean {
  return ref.match(/^[a-fA-F0-9]{40}$/) !== null;
}

/**
 * Use the `git ls-remote` command to remotely query the given git repo, and
 * resolve the given ref (e.g. a branch or tag) to a commit SHA. Returns
 * `undefined` if the ref does not resolve to anything in the repo. Throws if
 * the repo is invalid or errors.
 */
async function remoteResolveGitRefToSha(
    repo: string, ref: string): Promise<string|undefined> {
  const {stdout} =
      await execFilePromise('git', ['ls-remote', repo, '--symref', ref]);
  if (stdout.trim() === '') {
    return undefined;
  }
  const parts = stdout.trim().split(/\W/);
  if (parts.length > 0 && looksLikeGitSha(parts[0])) {
    return parts[0];
  }
  throw new Error(`Could not parse output of \`git ls-remote ${repo} --symref ${
      ref}\`:\n${stdout}`);
}


text:
import React from 'react';
import Input, { InputProps } from '@uiw/react-input';
import './style/index.less';

export interface FileInputProps<T> extends InputProps<T> {}

export default React.forwardRef<HTMLInputElement, InputProps<{}>>(
  (props, ref) => {
    const { className, prefixCls = 'w-fileinput', ...other } = props;
    const cls = [prefixCls, className].filter(Boolean).join(' ').trim();
    return (
      <Input
        ref={ref}
        data-label="Browse"
        className={cls}
        {...other}
        type="file"
      />
    );
  },
);


text:
package org.javalite.db_migrator.maven;

import org.apache.maven.plugin.MojoExecutionException;
import org.javalite.db_migrator.Migration;
import org.javalite.db_migrator.MigrationManager;

import java.util.List;

import static org.javalite.db_migrator.DbUtils.closeConnection;

/**
 * Validate current schema against available migrations.
 * <p/>
 *
 * @goal validate
 */
public class ValidateMojo extends AbstractDbMigrationMojo {
    public void executeMojo() throws MojoExecutionException {
        getLog().info("Validating " + getUrl() + " using migrations from " + getMigrationsPath());
        try {
            openConnection();
            MigrationManager manager = new MigrationManager(getMigrationsPath());
            List<Migration> pendingMigrations = manager.getPendingMigrations();

            getLog().info("Database: " + getUrl());
            getLog().info("Up-to-date: " + pendingMigrations.isEmpty());
            if (!pendingMigrations.isEmpty()) {
                getLog().info("Pending Migrations: ");
                for (Migration migration : pendingMigrations) {
                    getLog().info(migration.getName());
                }
            }else{
                getLog().info("No pending migrations found");
            }
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to validate " + getUrl(), e);
        }finally {
            closeConnection();
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Cryptog. Bryol. -Lichénol. 14(4): 337 (1993)

#### Original name
Pannaria austro-orcadensis Øvstedal

### Remarks
null


text:
package io.github.mcaliman.patterns.state;

/**
 * @author Massimo Caliman
 */
public class DarftState implements State {

    @Override
    public void execute() {
        System.out.println("Contenuto salvato in stato bozza");
    }

}


text:
The program `melrōse` is a Read–Eval–Print Loop (REPL) that produces or consumes MIDI.
By entering statements using the language, `melrōse` will send out MIDI messages to any connected DAW.

Although it is possible to program directly using the command line interface of `melrōse`, it is much more convenient to use the Visual Studio Code editor with the Melrose Plugin which uses the [HTTP API](http.md) of the same running program.

### program flags

You can start the program `melrōse` without any flags.
You can use the following flags to change its behavior.

    -http <address>
        address on which to listen for HTTP requests (default ":8118")
    -tunnel <subdomain>
        offers a public subdomain.loca.lt address to server HTTP request
    -v
        verbose logging

### CLI control

Commands to control the program itself are prefix with a colon `:`.
With `:h` you get the list of known commands.

### CLI line editing

The following line editing commands are supported on platforms and terminals
that `melrōse` supports:

Keystroke    | Action
---------    | ------
Tab          | Next completion
Shift-Tab    | (after Tab) Previous completion
Ctrl-A, Home | Move cursor to beginning of line
Ctrl-E, End  | Move cursor to end of line
Ctrl-B, Left | Move cursor one character left
Ctrl-F, Right| Move cursor one character right
Ctrl-Left, Alt-B    | Move cursor to previous word
Ctrl-Right, Alt-F   | Move cursor to next word
Ctrl-D, Del  | (if line is *not* empty) Delete character under cursor
Ctrl-D       | (if line *is* empty) End of File - usually quits application
Ctrl-C       | Reset input (create new empty prompt)
Ctrl-L       | Clear screen (line is unmodified)
Ctrl-T       | Transpose previous character with current character
Ctrl-H, BackSpace | Delete character before cursor
Ctrl-W, Alt-BackSpace | Delete word leading up to cursor
Alt-D        | Delete word following cursor
Ctrl-K       | Delete from cursor to end of line
Ctrl-U       | Delete from start of line to cursor
Ctrl-P, Up   | Previous match from history
Ctrl-N, Down | Next match from history
Ctrl-R       | Reverse Search history (Ctrl-S forward, Ctrl-G cancel)
Ctrl-Y       | Paste from Yank buffer (Alt-Y to paste next yank instead)


text:
package com.yeming.paopao.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yeming.paopao.R;
import com.yeming.paopao.app.YmApplication;
import com.yeming.paopao.aty.EditUserInfoActivity;
import com.yeming.paopao.aty.EditUserSignActivity;
import com.yeming.paopao.aty.OtherUserInfoActivity;
import com.yeming.paopao.bean.Comment;
import com.yeming.paopao.bean.Paopao;
import com.yeming.paopao.bean.User;
import com.yeming.paopao.utils.ImageLoadOptions;
import com.yeming.paopao.views.third.CircleImageView;

import java.util.List;

/**
 * author   YeMing(yeming_1001@163.com)
 * Date:    2015-01-28 21:27
 * version: V1.0
 * Description:  评论列表适配器
 */
public class CommentLisrAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater mInflater;
    private List<Comment> list ;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    public CommentLisrAdapter(Context context,List<Comment> list,ImageLoader imageLoader){
        this.context = context ;
        mInflater = LayoutInflater.from(context) ;
        this.list = list ;
        this.imageLoader = imageLoader ;
        this.options = ImageLoadOptions.getOptionsById(R.drawable.user_icon_default_main) ;
    }

    public CommentLisrAdapter(Context context){
        this.context = context ;
        mInflater = LayoutInflater.from(context) ;
    }

    @Override
    public int getCount() {
        return this.list.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        final ViewHolder viewHolder;
        if(view == null){
            viewHolder = new ViewHolder();
            view = mInflater.inflate(R.layout.paopao_comment_item,null) ;
            viewHolder.userName = (TextView)view.findViewById(R.id.comment_item_user_name);
            viewHolder.userIcon = (CircleImageView)view.findViewById(R.id.comment_item_user_icon);
            viewHolder.comment = (TextView)view.findViewById(R.id.comment_item_content_text);
            viewHolder.time = (TextView)view.findViewById(R.id.comment_item_content_time);
            view.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder)view.getTag();
        }
        Comment comment = list.get(i) ;
        final User user = comment.getUser() ;
        String avatarUrl = user.getAvatarUrl() ;
        imageLoader.displayImage(avatarUrl,viewHolder.userIcon,options);
        viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String objId = user.getObjectId() ;
                if(YmApplication.getCurrentUser().getObjectId().equals(objId)){
                    Intent intent = new Intent() ;
                    intent.setClass(context, EditUserInfoActivity.class) ;
                    context.startActivity(intent);
                }else {
                    //  点击跳转到用户
                    Intent intent = new Intent();
                    intent.putExtra("user", user);
                    intent.setClass(context, OtherUserInfoActivity.class);
                    context.startActivity(intent);
                }
            }
        });
        viewHolder.userName.setTypeface(YmApplication.chineseTypeface);
        viewHolder.comment.setTypeface(YmApplication.chineseTypeface);
        viewHolder.time.setTypeface(YmApplication.chineseTypeface);

        viewHolder.userName.setText(user.getNickname());
        viewHolder.time.setText(comment.getCreatedAt());
        viewHolder.comment.setText(comment.getContent());

        return view;
    }

    public List<Comment> getList() {
        return list;
    }

    public void setList(List<Comment> list) {
        this.list = list;
    }

    public static class ViewHolder{
        public CircleImageView userIcon;
        public TextView userName;
        public TextView comment;
        public TextView time ;
    }
}


text:
package com.qa.framework.bean;

import com.library.common.StringHelper;

import java.util.Arrays;

/**
 * Created by apple on 15/11/20.
 */
public class Pair {
    private String key;
    private String value;
    private boolean sort;
    private boolean patternMatch = true;

    /**
     * Instantiates a new Pair.
     *
     * @param key   the key
     * @param value the value
     */
    public Pair(String key, String value) {
        this.key = key;
        this.value = value;
    }

    /**
     * Instantiates a new Pair.
     */
    public Pair() {
    }

    /**
     * Gets pattern match.
     *
     * @return the pattern match
     */
    public Boolean getPatternMatch() {
        return patternMatch;
    }

    /**
     * Sets pattern match.
     *
     * @param patter the patter
     */
    public void setPatternMatch(String patter) {
        this.patternMatch = StringHelper.changeString2boolean(patter);
    }

    /**
     * Sets pattern match.
     *
     * @param patter the patter
     */
    public void setPatternMatch(boolean patter) {
        this.patternMatch = patter;
    }

    /**
     * Gets key.
     *
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets key.
     *
     * @param key the key
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * Gets value.
     *
     * @return the value
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets value.
     *
     * @param value the value
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Sets sort.
     *
     * @param sortStr the sort str
     */
    public void setSort(String sortStr) {
        sort = StringHelper.changeString2boolean(sortStr);
    }

    /**
     * Is sort boolean.
     *
     * @return the boolean
     */
    public boolean isSort() {
        return sort;
    }

    /**
     * Sets sort.
     *
     * @param sort the sort
     */
    public void setSort(boolean sort) {
        this.sort = sort;
    }

    /**
     * Sets map statement.
     *
     * @param mapStatement the map statement
     */
    public void setMapStatement(String mapStatement) {
        if (mapStatement != null && !"".equalsIgnoreCase(mapStatement)) {
            if (!mapStatement.contains(":")) {
                throw new IllegalArgumentException("请重新设值,参照格式key:value");
            }
            String[] statements = mapStatement.split(":");
            if (statements.length == 1) {
                setKey(statements[0].trim());
                setValue("");
            } else if (statements.length == 2) {
                setKey(statements[0].trim());
                setValue(statements[1].trim());
            } else {
                setKey(statements[0].trim());
                String[] newStatementsValue = Arrays.copyOfRange(statements, 1, statements.length);
                setValue(StringHelper.join(newStatementsValue, ":"));
            }
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof Pair) {
            Pair pair = (Pair) obj;
            if (this.getValue().equalsIgnoreCase(pair.getValue()) && this.getKey().equalsIgnoreCase(pair.getKey())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return key + ":=" + value;
    }

}


text:
ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.smtp_settings = {
  :address => "smtp.<%= domain %>",
  :domain => "<%= domain %>",
  :authentication => :plain,
  :user_name => "<%= username %>=<%= domain %>",
  :password => "<%= password %>"
}


text:
package algorithms;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

import agents.Car;
import comperator.*;

public class ShortestChargeFirst extends Algorithm {

	public ShortestChargeFirst() {
		this(new ArrayList<Car>());
	}

	public ShortestChargeFirst(ArrayList<Car> cars) {
		super("Shortest Charge First");
		super._source = cars;
	}

	/**
	 * Executes the algorithm
	 */
	@Override
	public void execute() {
		super._scheduledCars = new ConcurrentLinkedQueue<Car>();
		super._source.sort(new SortByShortestCharge());

		for (Car car : super._source) {
			super._scheduledCars.add(car);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Need Ocelot rune</title>
		<link>http://bvs.wikidot.com/forum/t-121979/need-ocelot-rune</link>
		<description>Posts in the discussion thread "Need Ocelot rune" - Need an ocelot rune and possibly some other monster drops in exchange for groupies</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 04:51:38 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-121979#post-362144</guid>
				<title>Need Wolf rune</title>
				<link>http://bvs.wikidot.com/forum/t-121979/need-ocelot-rune#post-362144</link>
				<description></description>
				<pubDate>Wed, 21 Jan 2009 02:33:41 +0000</pubDate>
				<wikidot:authorName>Theseus Theseus</wikidot:authorName>				<wikidot:authorUserId>265395</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Updated:
 I have,

necklace of first hocage
 stealth suits
 sham rock
 Groupies
 Carpace armor

If anyone is interested please PM Theseus in game. Willing to trade any of those for wolf rune or some other kaiju drops i do not already have.

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
import React from 'react';

import DateChooser from '../containers/DateChooser';
import Currency from './Currency';
import Button from '../containers/Button';

// CurrencyConverter
// - DateChooser
// - Currency (From)
//  - Amount
//  - CurrencyChooser
// - Currency (To)
//  - Amount (Disabled)
//  - CurrencyChooser

export default class CurrencyConverter extends React.Component {
  render() {
    return(

FX-u-like

        <DateChooser />
        <Currency direction="from" />
        <Currency direction="to" />
        <Button title="Convert!" />

    )
  }
}