text:
namespace ui {
namespace {

// Constants used by TimeoutGestureHandler.
enum TimeoutEvent {
  SHOW_PRESS = 0,
  LONG_PRESS,
  TAP,
  TIMEOUT_EVENT_COUNT
};

}  // namespace

// Note: These constants were taken directly from the default (unscaled)
// versions found in Android's ViewConfiguration.
GestureDetector::Config::Config()
    : longpress_timeout(base::TimeDelta::FromMilliseconds(500)),
      showpress_timeout(base::TimeDelta::FromMilliseconds(180)),
      double_tap_timeout(base::TimeDelta::FromMilliseconds(300)),
      scaled_touch_slop(8),
      scaled_double_tap_slop(100),
      scaled_minimum_fling_velocity(50),
      scaled_maximum_fling_velocity(8000) {}

GestureDetector::Config::~Config() {}

bool GestureDetector::SimpleGestureListener::OnDown(const MotionEvent& e) {
  return false;
}

void GestureDetector::SimpleGestureListener::OnShowPress(const MotionEvent& e) {
}

bool GestureDetector::SimpleGestureListener::OnSingleTapUp(
    const MotionEvent& e) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnLongPress(const MotionEvent& e) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnScroll(const MotionEvent& e1,
                                                      const MotionEvent& e2,
                                                      float distance_x,
                                                      float distance_y) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnFling(const MotionEvent& e1,
                                                     const MotionEvent& e2,
                                                     float velocity_x,
                                                     float velocity_y) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnSingleTapConfirmed(
    const MotionEvent& e) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnDoubleTap(const MotionEvent& e) {
  return false;
}

bool GestureDetector::SimpleGestureListener::OnDoubleTapEvent(
    const MotionEvent& e) {
  return false;
}

class GestureDetector::TimeoutGestureHandler {
 public:
  TimeoutGestureHandler(const Config& config, GestureDetector* gesture_detector)
      : gesture_detector_(gesture_detector) {
    DCHECK(config.showpress_timeout <= config.longpress_timeout);

    timeout_callbacks_[SHOW_PRESS] = &GestureDetector::OnShowPressTimeout;
    timeout_delays_[SHOW_PRESS] = config.showpress_timeout;

    timeout_callbacks_[LONG_PRESS] = &GestureDetector::OnLongPressTimeout;
    timeout_delays_[LONG_PRESS] =
        config.longpress_timeout + config.showpress_timeout;

    timeout_callbacks_[TAP] = &GestureDetector::OnTapTimeout;
    timeout_delays_[TAP] = config.double_tap_timeout;
  }

  ~TimeoutGestureHandler() {
    Stop();
  }

  void StartTimeout(TimeoutEvent event) {
    timeout_timers_[event].Start(FROM_HERE,
                                 timeout_delays_[event],
                                 gesture_detector_,
                                 timeout_callbacks_[event]);
  }

  void StopTimeout(TimeoutEvent event) { timeout_timers_[event].Stop(); }

  void Stop() {
    for (size_t i = SHOW_PRESS; i < TIMEOUT_EVENT_COUNT; ++i)
      timeout_timers_[i].Stop();
  }

  bool HasTimeout(TimeoutEvent event) const {
    return timeout_timers_[event].IsRunning();
  }

 private:
  typedef void (GestureDetector::*ReceiverMethod)();

  GestureDetector* const gesture_detector_;
  base::OneShotTimer<GestureDetector> timeout_timers_[TIMEOUT_EVENT_COUNT];
  ReceiverMethod timeout_callbacks_[TIMEOUT_EVENT_COUNT];
  base::TimeDelta timeout_delays_[TIMEOUT_EVENT_COUNT];
};

GestureDetector::GestureDetector(
    const Config& config,
    GestureListener* listener,
    DoubleTapListener* optional_double_tap_listener)
    : timeout_handler_(new TimeoutGestureHandler(config, this)),
      listener_(listener),
      double_tap_listener_(optional_double_tap_listener),
      touch_slop_square_(0),
      double_tap_touch_slop_square_(0),
      double_tap_slop_square_(0),
      min_fling_velocity_(1),
      max_fling_velocity_(1),
      still_down_(false),
      defer_confirm_single_tap_(false),
      in_longpress_(false),
      always_in_tap_region_(false),
      always_in_bigger_tap_region_(false),
      is_double_tapping_(false),
      last_focus_x_(0),
      last_focus_y_(0),
      down_focus_x_(0),
      down_focus_y_(0),
      is_longpress_enabled_(true) {
  DCHECK(listener_);
  Init(config);
}

GestureDetector::~GestureDetector() {}

bool GestureDetector::OnTouchEvent(const MotionEvent& ev) {
  const MotionEvent::Action action = ev.GetAction();

  velocity_tracker_.AddMovement(ev);

  const bool pointer_up = action == MotionEvent::ACTION_POINTER_UP;
  const int skip_index = pointer_up ? ev.GetActionIndex() : -1;

  // Determine focal point.
  float sum_x = 0, sum_y = 0;
  const int count = static_cast<int>(ev.GetPointerCount());
  for (int i = 0; i < count; i++) {
    if (skip_index == i)
      continue;
    sum_x += ev.GetX(i);
    sum_y += ev.GetY(i);
  }
  const int div = pointer_up ? count - 1 : count;
  const float focus_x = sum_x / div;
  const float focus_y = sum_y / div;

  bool handled = false;

  switch (action) {
    case MotionEvent::ACTION_POINTER_DOWN:
      down_focus_x_ = last_focus_x_ = focus_x;
      down_focus_y_ = last_focus_y_ = focus_y;
      // Cancel long press and taps.
      CancelTaps();
      break;

    case MotionEvent::ACTION_POINTER_UP:
      down_focus_x_ = last_focus_x_ = focus_x;
      down_focus_y_ = last_focus_y_ = focus_y;

      // Check the dot product of current velocities.
      // If the pointer that left was opposing another velocity vector, clear.
      velocity_tracker_.ComputeCurrentVelocity(1000, max_fling_velocity_);
      {
        const int up_index = ev.GetActionIndex();
        const int id1 = ev.GetPointerId(up_index);
        const float x1 = velocity_tracker_.GetXVelocity(id1);
        const float y1 = velocity_tracker_.GetYVelocity(id1);
        for (int i = 0; i < count; i++) {
          if (i == up_index)
            continue;

          const int id2 = ev.GetPointerId(i);
          const float x = x1 * velocity_tracker_.GetXVelocity(id2);
          const float y = y1 * velocity_tracker_.GetYVelocity(id2);

          const float dot = x + y;
          if (dot < 0) {
            velocity_tracker_.Clear();
            break;
          }
        }
      }
      break;

    case MotionEvent::ACTION_DOWN:
      if (double_tap_listener_) {
        bool had_tap_message = timeout_handler_->HasTimeout(TAP);
        if (had_tap_message)
          timeout_handler_->StopTimeout(TAP);
        if (current_down_event_ && previous_up_event_ && had_tap_message &&
            IsConsideredDoubleTap(
                *current_down_event_, *previous_up_event_, ev)) {
          // This is a second tap.
          is_double_tapping_ = true;
          // Give a callback with the first tap of the double-tap.
          handled |= double_tap_listener_->OnDoubleTap(*current_down_event_);
          // Give a callback with down event of the double-tap.
          handled |= double_tap_listener_->OnDoubleTapEvent(ev);
        } else {
          // This is a first tap.
          DCHECK(double_tap_timeout_ > base::TimeDelta());
          timeout_handler_->StartTimeout(TAP);
        }
      }

      down_focus_x_ = last_focus_x_ = focus_x;
      down_focus_y_ = last_focus_y_ = focus_y;
      current_down_event_ = ev.Clone();

      always_in_tap_region_ = true;
      always_in_bigger_tap_region_ = true;
      still_down_ = true;
      in_longpress_ = false;
      defer_confirm_single_tap_ = false;

      // Always start the SHOW_PRESS timer before the LONG_PRESS timer to ensure
      // proper timeout ordering.
      timeout_handler_->StartTimeout(SHOW_PRESS);
      if (is_longpress_enabled_)
        timeout_handler_->StartTimeout(LONG_PRESS);
      handled |= listener_->OnDown(ev);
      break;

    case MotionEvent::ACTION_MOVE:
      if (in_longpress_)
        break;

      {
        const float scroll_x = last_focus_x_ - focus_x;
        const float scroll_y = last_focus_y_ - focus_y;
        if (is_double_tapping_) {
          // Give the move events of the double-tap.
          DCHECK(double_tap_listener_);
          handled |= double_tap_listener_->OnDoubleTapEvent(ev);
        } else if (always_in_tap_region_) {
          const int delta_x = static_cast<int>(focus_x - down_focus_x_);
          const int delta_y = static_cast<int>(focus_y - down_focus_y_);
          int distance = (delta_x * delta_x) + (delta_y * delta_y);
          if (distance > touch_slop_square_) {
            handled = listener_->OnScroll(
                *current_down_event_, ev, scroll_x, scroll_y);
            last_focus_x_ = focus_x;
            last_focus_y_ = focus_y;
            always_in_tap_region_ = false;
            timeout_handler_->Stop();
          }
          if (distance > double_tap_touch_slop_square_)
            always_in_bigger_tap_region_ = false;
        } else if ((std::abs(scroll_x) >= 1) || (std::abs(scroll_y) >= 1)) {
          handled =
              listener_->OnScroll(*current_down_event_, ev, scroll_x, scroll_y);
          last_focus_x_ = focus_x;
          last_focus_y_ = focus_y;
        }
      }
      break;

    case MotionEvent::ACTION_UP:
      still_down_ = false;
      {
        if (is_double_tapping_) {
          // Finally, give the up event of the double-tap.
          DCHECK(double_tap_listener_);
          handled |= double_tap_listener_->OnDoubleTapEvent(ev);
        } else if (in_longpress_) {
          timeout_handler_->StopTimeout(TAP);
          in_longpress_ = false;
        } else if (always_in_tap_region_) {
          handled = listener_->OnSingleTapUp(ev);
          if (defer_confirm_single_tap_ && double_tap_listener_ != NULL) {
            double_tap_listener_->OnSingleTapConfirmed(ev);
          }
        } else {

          // A fling must travel the minimum tap distance.
          const int pointer_id = ev.GetPointerId(0);
          velocity_tracker_.ComputeCurrentVelocity(1000, max_fling_velocity_);
          const float velocity_y = velocity_tracker_.GetYVelocity(pointer_id);
          const float velocity_x = velocity_tracker_.GetXVelocity(pointer_id);

          if ((std::abs(velocity_y) > min_fling_velocity_) ||
              (std::abs(velocity_x) > min_fling_velocity_)) {
            handled = listener_->OnFling(
                *current_down_event_, ev, velocity_x, velocity_y);
          }
        }

        previous_up_event_ = ev.Clone();

        velocity_tracker_.Clear();
        is_double_tapping_ = false;
        defer_confirm_single_tap_ = false;
        timeout_handler_->StopTimeout(SHOW_PRESS);
        timeout_handler_->StopTimeout(LONG_PRESS);
      }
      break;

    case MotionEvent::ACTION_CANCEL:
      Cancel();
      break;
  }

  return handled;
}

void GestureDetector::Init(const Config& config) {
  DCHECK(listener_);

  const int touch_slop = config.scaled_touch_slop;
  const int double_tap_touch_slop = touch_slop;
  const int double_tap_slop = config.scaled_double_tap_slop;
  min_fling_velocity_ = config.scaled_minimum_fling_velocity;
  max_fling_velocity_ = config.scaled_maximum_fling_velocity;
  touch_slop_square_ = touch_slop * touch_slop;
  double_tap_touch_slop_square_ = double_tap_touch_slop * double_tap_touch_slop;
  double_tap_slop_square_ = double_tap_slop * double_tap_slop;
  double_tap_timeout_ = config.double_tap_timeout;
}

void GestureDetector::OnShowPressTimeout() {
  listener_->OnShowPress(*current_down_event_);
}

void GestureDetector::OnLongPressTimeout() {
  timeout_handler_->StopTimeout(TAP);
  defer_confirm_single_tap_ = false;
  in_longpress_ = listener_->OnLongPress(*current_down_event_);
}

void GestureDetector::OnTapTimeout() {
  if (!double_tap_listener_)
    return;
  if (!still_down_)
    double_tap_listener_->OnSingleTapConfirmed(*current_down_event_);
  else
    defer_confirm_single_tap_ = true;
}

void GestureDetector::Cancel() {
  timeout_handler_->Stop();
  velocity_tracker_.Clear();
  is_double_tapping_ = false;
  still_down_ = false;
  always_in_tap_region_ = false;
  always_in_bigger_tap_region_ = false;
  defer_confirm_single_tap_ = false;
  in_longpress_ = false;
}

void GestureDetector::CancelTaps() {
  timeout_handler_->Stop();
  is_double_tapping_ = false;
  always_in_tap_region_ = false;
  always_in_bigger_tap_region_ = false;
  defer_confirm_single_tap_ = false;
  in_longpress_ = false;
}

bool GestureDetector::IsConsideredDoubleTap(
    const MotionEvent& first_down,
    const MotionEvent& first_up,
    const MotionEvent& second_down) const {
  if (!always_in_bigger_tap_region_)
    return false;

  if (second_down.GetEventTime() - first_up.GetEventTime() >
      double_tap_timeout_)
    return false;

  int delta_x = static_cast<int>(first_down.GetX() - second_down.GetX());
  int delta_y = static_cast<int>(first_down.GetY() - second_down.GetY());
  return (delta_x * delta_x + delta_y * delta_y < double_tap_slop_square_);
}

}  // namespace ui


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Simyskin practicum</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">
        <link href="https://fonts.googleapis.com/css?family=Muli:300i,400" rel="stylesheet">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/base.min.css">
        <link rel="stylesheet" href="css/header.min.css">
        <link rel="stylesheet" href="css/main-hero.min.css">
        <link rel="stylesheet" href="css/what-is-it.min.css">
        <link rel="stylesheet" href="css/video.min.css">
        <link rel="stylesheet" href="css/targeted-solutions.min.css">
        <link rel="stylesheet" href="css/ingredients.min.css">
        <link rel="stylesheet" href="css/before-after.min.css">
        <link rel="stylesheet" href="css/testimonials.min.css">
        <link rel="stylesheet" href="css/where-to-buy.min.css">
        <link rel="stylesheet" href="css/shipping-container.min.css">
        <link rel="stylesheet" href="css/contact.min.css">
        <link rel="stylesheet" href="css/request-sample.min.css">
        <link rel="stylesheet" href="css/footer.min.css">

                    Targeted Skin Solutions for every phase of your life.

BUY NOW

Lorem Ipsum dolor sit amet Cum so.

Aenean vulputate eleifend tellus. leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.

BUY NOW

                    Made in france

                    All Natural

                    Nanotechnology

                    Systems Biology

What is it?

It is an advanced Anti-Aging Serum created o maintain a youthful eye contour.

Why do you need it?

Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut

SimyskinTM Anti-Aging Eye Serum

Targeted Skin Solutions

PHASE IM - 18-25 YEARS

Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem.Blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas tempusmet.

BUY NOW

PHASE IM - 18-25 YEARS

Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem.Blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas tempusmet.

BUY NOW

PHASE IM - 18-25 YEARS

Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem.Blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas tempusmet.

BUY NOW

What does it do?

quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem.

Blandit vel, luctus pulvinar, hendrerit id, lorem.
Maecenas tempusmet.

Blandit vel, luctus pulvinar, hendrerit id, lorem.

Maecenas tempus, tellus eget con ntum rh oncus, sem quam semper libero, sit amet.

Blandit vel, luctus pulvinar, hendrerit id, lorem.

How does it do it?

                    SYSTEMS BIOLOGY COMPLEX

Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem.

Blandit vel, luctus pulvinar, hendrerit id, lorem.

vntum rh oncus, sem quam semper libero, sit amet.

                    NANOTECHNOLOGY

Blandit vel, luctus pulvinar, hen drerit id, lorem. Maecenas tempus, tellus eget conntum rh oncus, sem quam semper libero, sit amet.

All Natural Ingredients

VITAMIN B12

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem hendrerit id, lorem.

FOLIC ACID

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem. hendrerit id, lorem.

HYALURONIC ACID

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem. hendrerit id, lorem. hendrerit

UBIQUINONE

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem hendrerit id, lorem.

PALMITOYL TETRAPEPTIDE-7

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem. hendrerit id, lorem.

SORGHUM BICOLOR STALK JUICE

                            Nam quam nunc, blandit vel, luctus pulvinar, hen drerit id, lorem hendrerit id, lorem.

Visible results lorem ipsum dolor

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut.

Return Guarantee

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.

BEFORE

AFTER

This is what experts have to say about SimyskinTM

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi.

Nicole Campbell

                    Integer tincidunt Cras of Lo.

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate.

Jenny Malone

                    Integer tincidunt Cras of Lo.

SimyskinTM is also available at

We ship worldwide!

WITHIN THE US

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.     Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.

INTERNATIONAL SHIPPING

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tinm semper nisi. Aenean vulputate eleifend tellus.

Aenean massa cum sociis natoque penatibus et magnis dis parturient?

Lae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.

CONTACT US

Try SimyskinTM TODAY!

ORDER A FREE SAMPLE

© Copyright Simyskin

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

                        common.lock

                        common.unlock

                        tenant.change


text:
var assert = require("assert");
var TestRunner = require("../src/test_runner");
var _ = require("lodash");
var settings = require("../src/settings");
var WorkerAllocator = require("../src/worker_allocator");

settings.framework = "magellan-fake";
settings.testFramework = require("../test_support/magellan-selftest-plugin/index");
settings.testFramework.initialize({});

var DEFAULT_BAIL_TIME = settings.bailTime;
var MAX_WORKERS = 1;

var baseOptions = {
  debug: false,
  maxWorkers: MAX_WORKERS,
  maxTestAttempts: 1,
  browsers: ["phantomjs"],
  listeners: [],
  bailFast: false,
  bailOnThreshold: false,
  serial: false,

  allocator: undefined,
  sauceSettings: undefined
};

describe("test runner", function () {

  beforeEach(function () {
    settings.bailTime = DEFAULT_BAIL_TIME;
  });

  describe("single worker", function () {
    this.timeout(6000);

    it("runs zero tests", function (done) {
      var options = _.extend({}, baseOptions, {
        onSuccess: done
      });

      var runner = new TestRunner([], options);
      runner.start();
    });

    it("runs one test @testtag", function (done) {
      this.timeout(6000);

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, baseOptions, {
        allocator: workerAllocator,
        onSuccess: done
      });

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(["fake_test1"], options);
        runner.start();
      });
    });

    it("fails one test @testtag", function (done) {
      this.timeout(6000);

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, baseOptions, {
        allocator: workerAllocator,
        onFailure: function () {
          done();
        }
      });

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(["fail_test1"], options);
        runner.start();
      });
    });

  });

  describe("multi-worker", function () {
    this.timeout(6000);

    var MAX_WORKERS = 8;
    var multiWorkerBaseOptions = _.extend({}, baseOptions, {
      maxWorkers: MAX_WORKERS
    });

    it("runs zero tests @testtag @multi", function (done) {
      var options = _.extend({}, multiWorkerBaseOptions, {
        onSuccess: done
      });

      var runner = new TestRunner([], options);
      runner.start();
    });

    it("runs one test", function (done) {
      this.timeout(6000);

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, multiWorkerBaseOptions, {
        allocator: workerAllocator,
        onSuccess: done
      });

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(["fake_test1"], options);
        runner.start();
      });
    });

    it("runs many tests", function (done) {
      this.timeout(25000);

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, multiWorkerBaseOptions, {
        allocator: workerAllocator,
        onSuccess: done
      });

      var tests = [];
      for (var i = 0; i < 14; i++) {
        tests.push("fake_test" + i);
      }

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(tests, options);
        runner.start();
      });
    });

    it.only("detects a zombie process @zombie", function (done) {
      this.timeout(25000);
      settings.bailTime = 2500;

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, multiWorkerBaseOptions, {
        bailFast: true,
        allocator: workerAllocator,
        onSuccess: function () {
          done();
        },
        onFailure: function () {
          done();
        }
      });

      var tests = ["zombie"];

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(tests, options);
        runner.start();
      });
    });

    it("runs many tests and fails two", function (done) {
      this.timeout(25000);

      var workerAllocator = new WorkerAllocator(MAX_WORKERS);

      var options = _.extend({}, multiWorkerBaseOptions, {
        allocator: workerAllocator,
        onFailure: function () {
          done();
        }
      });

      var tests = [];
      for (var i = 0; i < 14; i++) {
        if (i == 7 || i == 11) {
          tests.push("fail_test" + i);
        } else {
          tests.push("fake_test" + i);
        }
      }

      workerAllocator.initialize(function (err) {
        var runner = new TestRunner(tests, options);
        runner.start();
      });
    });

  });
});


text:
require 'test_helper'

module Byebug
  #
  # Tests Byebug's command line history.
  #
  class HistoryTestCase < TestCase
    def program
      strip_line_numbers <<-EOC
        1:  module Byebug
        2:    byebug
        3:
        4:    a = 2
        5:    a + 3
        6:  end
      EOC
    end

    def test_history_displays_latest_records_from_readline_history
      enter 'show', 'history'
      debug_code(program)

      check_output_includes(/\d+  show$/, /\d+  history$/)
    end

    def test_history_n_displays_whole_history_if_n_is_bigger_than_history_size
      enter 'show', 'history 3'
      debug_code(program)

      check_output_includes(/\d+  show$/, /\d+  history 3$/)
    end

    def test_history_n_displays_lastest_n_records_from_readline_history
      enter 'show width', 'show autolist', 'history 2'
      debug_code(program)

      check_output_includes(/\d+  show autolist$/, /\d+  history 2$/)
    end

    def test_history_does_not_save_empty_commands
      enter 'show', 'show width', '', 'history 3'
      debug_code(program)

      check_output_includes(/\d+  show$/, /\d+  show width$/, /\d+  history 3$/)
    end

    def test_history_does_not_save_duplicated_consecutive_commands
      enter 'show', 'show width', 'show width', 'history 3'
      debug_code(program)

      check_output_includes(/\d+  show$/, /\d+  show width$/, /\d+  history 3$/)
    end

    def test_cmds_from_previous_repls_are_remembered_if_autosave_enabled
      with_setting :autosave, true do
        enter 'next', 'history 2'
        debug_code(program)

        check_output_includes(/\d+  next$/, /\d+  history 2$/)
      end
    end

    def test_cmds_from_previous_repls_are_not_remembered_if_autosave_disabled
      with_setting :autosave, false do
        enter 'set noautosave', 'next', 'history 2'
        debug_code(program)

        check_output_includes(/\d+  history 2$/)
        check_output_doesnt_include(/\d+  next$/)
      end
    end
  end
end


text:
package com.taobao.weex.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;

/**
 * modify the scrollFactor
 */
public class WXSmoothScroller extends Scroller {

  private double mScrollFactor = 1;

  public WXSmoothScroller(Context context) {
    super(context);
  }

  public WXSmoothScroller(Context context, Interpolator interpolator) {
    super(context, interpolator);
  }

  @SuppressLint("NewApi")
  public WXSmoothScroller(Context context, Interpolator interpolator, boolean flywheel) {
    super(context, interpolator, flywheel);
  }

  /**
   * Set the factor by which the duration will change
   */
  public void setScrollDurationFactor(double scrollFactor) {
    mScrollFactor = scrollFactor;
  }

  @Override
  public void startScroll(int startX, int startY, int dx, int dy, int duration) {
    super.startScroll(startX, startY, dx, dy, (int) (duration * mScrollFactor));
  }

}


text: Application = Ember.Application.create();


text:
package net.maera.io;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

/**
 * Interface for a resource descriptor that abstracts from the actual
 * type of underlying resource, such as a file or class path resource.
 *

 * An InputStream can be opened for every resource if it exists in
 * physical form, but a URL or File handle can just be returned for
 * certain resources. The actual behavior is implementation-specific.
 *

 * Shamelessly copied from the Spring 3.0.3 distribution to prevent a runtime dependency on Spring for all API
 * implementations.  All license conditions and author attribution has remained in tact.
 *
 * @author Juergen Hoeller
 * @see #getInputStream()
 * @see #getURL()
 * @see #getURI()
 * @see #getFile()
 *      - @see FileSystemResource
 *      - @see ClassPathResource
 *      - @see UrlResource
 *      - @see ByteArrayResource
 *      - @see InputStreamResource
 *      - @see org.springframework.web.context.support.ServletContextResource
 * @since 28.12.2003
 */
//TODO - throw IOExceptions in this class?  Or create a common runtime ResourceException class?
public interface Resource extends InputStreamSource {

    /**
     * Return whether this resource actually exists in physical form.
     *

     * This method performs a definitive existence check, whereas the
     * existence of a {@code Resource} handle only guarantees a
     * valid descriptor handle.
     *
     * @return whether this resource actually exists in physical form.
     */
    boolean exists();

    /**
     * Return whether the contents of this resource can be read,
     * e.g. via {@link #getInputStream()} or {@link #getFile()}.
     *

     * Will be {@code true} for typical resource descriptors;
     * note that actual content reading may still fail when attempted.
     * However, a value of {@code false}} is a definitive indication
     * that the resource content cannot be read.
     *
     * @return whether the contents of this resource can be read.
     */
    boolean isReadable();

    /**
     * Return whether this resource represents a handle with an open
     * stream. If true, the InputStream cannot be read multiple times,
     * and must be read and closed to avoid resource leaks.
     *

     * Will be {@code false} for typical resource descriptors.
     *
     * @return whether this resource represents a handle with an open stream.
     */
    boolean isOpen();

    /**
     * Return a URL handle for this resource.
     *
     * @return a URL handle for this resource.
     * @throws IOException if the resource cannot be resolved as URL,
     *                     i.e. if the resource is not available as descriptor
     */
    URL getURL() throws IOException;

    /**
     * Return a URI handle for this resource.
     *
     * @return a URI handle for this resource.
     * @throws IOException if the resource cannot be resolved as URI,
     *                     i.e. if the resource is not available as descriptor
     */
    URI getURI() throws IOException;

    /**
     * Return a File handle for this resource.
     *
     * @return a File handle for this resource.
     * @throws IOException if the resource cannot be resolved as absolute
     *                     file path, i.e. if the resource is not available in a file system
     */
    File getFile() throws IOException;

    /**
     * Determine the last-modified timestamp for this resource.
     *
     * @return the last-modified timestamp for this resource.
     * @throws IOException if the resource cannot be resolved
     *                     (in the file system or as some other known physical resource type)
     */
    long lastModified() throws IOException;

    /**
     * Create a resource relative to this resource.
     *
     * @param relativePath the relative path (relative to this resource)
     * @return the resource handle for the relative resource
     * @throws IOException if the relative resource cannot be determined
     */
    Resource createRelative(String relativePath) throws IOException;

    /**
     * Return a filename for this resource, i.e. typically the last
     * part of the path: for example, "myfile.txt".
     *
     * @return a filename for this resource
     */
    String getFilename();

    /**
     * Return a description for this resource,
     * to be used for error output when working with the resource.
     *

     * Implementations are also encouraged to return this value from their {@link #toString() toString()}
     * implementation.
     *
     * @return a description for this resource
     * @see java.lang.Object#toString()
     */
    String getDescription();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QTec.Business
{
    using QTec.Core.Model;

    /// <summary>
    /// The Designation Manager interface.
    /// </summary>
    public interface IDesignationManager
    {
        /// <summary>
        /// The get designations.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        Task<IEnumerable<Designation>> GetDesignations();
    }
}


text:
linkTitle: How Wildlife Studios builds backend systems in Go
description: Wildlife is a Brazilian native global company focused on mobile
  gaming. We aim to develop games that will make billions of people happy. We
  have almost 40 million daily active users, and we rely on Go as the main
  language for our core platform, given its features to scale our backend
  services.
logoSrc: wildlife_light.svg
logoSrcDark: wildlife_dark.svg
company: Wildlife Studios
series: Case Studies
link:
  https://medium.com/tech-at-wildlife-studios/pitaya-wildlifes-golang-go-af57865f7a11
inLandingPageGrid: true
---


text:
<Product ProductID="56">
	<ProductName>Gnocchi di nonna Alice</ProductName>
	<SupplierID>26</SupplierID>
	<CategoryID>5</CategoryID>
	<QuantityPerUnit>24 - 250 g pkgs.</QuantityPerUnit>
	<UnitPrice>38.0000</UnitPrice>
	<UnitsInStock>21</UnitsInStock>
	<UnitsOnOrder>10</UnitsOnOrder>
	<ReorderLevel>30</ReorderLevel>
	<Discontinued>false</Discontinued>
</Product>


text:
describe("chorus.pages.AboutPage", function() {
    beforeEach(function () {
        this.page = new chorus.pages.AboutPage();
    });

    describe("when the fetch for the license completes", function() {
        beforeEach(function () {
            this.license = backboneFixtures.license();
            this.server.completeFetchFor(this.page.model, this.license);
        });

        it("has the styles for a logged in page", function () {
            expect(this.page.$el).toHaveClass("logged_in_layout");
        });

        it("includes the application name", function () {
            expect(this.page.$(".title")).toContainTranslation("about." + this.license.applicationKey());
        });

        describe("when the version string is returned", function () {
            beforeEach(function () {
                this.version = "0123456789ABCDEF012";
                _.find(this.server.fetches(), function(req) {
                    return req.url === "/VERSION";
                }, this).respond(200, {}, this.version);
            });

            it("displays the version info", function () {
                expect(this.page.$(".version")).toContainText(this.version);
            });
        });
    });

    describe("when the license vendor is alpine", function () {
        beforeEach(function () {
            this.license = backboneFixtures.license({vendor: "alpine"});
            this.server.completeFetchFor(this.page.model, this.license);
        });

        it("renders the license info", function () {
            _.each(["collaborators", "admins", "developers", "expires"], function(item) {
                expectItemExists(this.page, this.license, item);
            }, this);
        });
    });

    describe("when the license vendor is openchorus", function () {
        beforeEach(function () {
            this.license = backboneFixtures.license({vendor: "openchorus"});
            this.server.completeFetchFor(this.page.model, this.license);
        });

        it("displays only the version info", function () {
            _.each(["collaborators", "admins", "developers", "expires"], function(item) {
                expectItemDoesNotExist(this.page, this.license, item);
            }, this);
        });
    });

    describe("when the license vendor is pivotal", function () {
        beforeEach(function () {
            this.license = backboneFixtures.license({vendor: "pivotal"});
            this.server.completeFetchFor(this.page.model, this.license);
        });

        it("displays only the version info", function () {
            _.each(["collaborators", "admins", "developers"], function(item) {
                expectItemDoesNotExist(this.page, this.license, item);
            }, this);
            expectItemExists(this.page, this.license, "expires");
        });
    });

    function expectItemExists(page, license, item) {
        expect(page.$(".items ." + item)).toContainText(t("about." + item) + ": " + license.get(item));
    }

    function expectItemDoesNotExist(page, license, item) {
        expect(page.$(".items ." + item)).not.toContainText(t("about." + item) + ": " + license.get(item));
    }
});


text:
<?php

namespace YOOtheme\Widgetkit\Framework\Joomla;

use YOOtheme\Widgetkit\Framework\Config\Config;

class Option extends Config
{
    /**
     * Constructor.
     *
     * @param $db
     * @param $element
     */
    public function __construct($db, $element)
    {
        $self = $this;
        $row  = $db->fetchAssoc("SELECT params FROM @extensions WHERE element = :element LIMIT 1", compact('element'));

        parent::__construct(json_decode($row['params'], true) ?: array());

        register_shutdown_function(function () use ($self, $db, $row, $element) {
            if (($params = (string) $self) != $row['params']) {
                $db->update('@extensions', compact('params'), compact('element'));
            }
        });
    }
}


text:
var GB_HEADER = null;
var GB_WINDOW = null;
var GB_IFRAME = null;
var GB_OVERLAY = null;
var GB_TIMEOUT = null;

var GB_URL;

var GB_HEIGHT = 400;
var GB_WIDTH = 400;

var GB_caption = null;

//The url that was visited last
var GB_last_win_url = null;

function GB_show(caption, url /* optional */, height, width) {
  try {
    if(height != 'undefined')
      GB_HEIGHT = height;
    if(width != 'undefined')
      GB_WIDTH = width;

    initIfNeeded();

    GB_caption.innerHTML = caption;

    GB_setPosition();
    if(GB_ANIMATION) {
      positionRightVertically(GB_HEADER, -(GB_HEIGHT));
      positionRightVertically(GB_WINDOW, -(GB_HEIGHT+22));
    }

    showElement(GB_OVERLAY);
    showElement(GB_HEADER);
    showElement(GB_WINDOW);

    GB_setWidth();

    if(GB_ANIMATION) {
      GB_animateOut(-GB_HEIGHT);
      GB_URL = url;
    }
    else {
      GB_IFRAME.src = url;
      GB_IFRAME.opener = this;
    }

    return false;
  }
  catch (e) {
    return false;
  }
}

function GB_hide() {
  GB_IFRAME.src = "";
  hideElement(GB_WINDOW);
  hideElement(GB_HEADER);
  hideElement(GB_OVERLAY);
}

function GB_setPosition() {
  positionRightVertically(GB_HEADER, 0);
  positionRightVertically(GB_WINDOW, 22);
}

function GB_animateOut(top) {
  if(top+getScrollTop() < 0) {
    positionRightVertically(GB_WINDOW, top+22);
    positionRightVertically(GB_HEADER, top);
    GB_TIMEOUT = window.setTimeout(function() { GB_animateOut(top+50); }, 1);
  }
  else {
    GB_IFRAME.src = GB_URL;
    GB_IFRAME.opener = this;
    GB_WINDOW.style.top = getScrollTop()+22+"px";
    GB_HEADER.style.top = getScrollTop()+"px";
    clearTimeout(GB_TIMEOUT);
  }
}

function GB_setWidth() {
  var array_page_size = GB_getWindowSize();

  //Set size
  GB_WINDOW.style.width = GB_WIDTH + "px";
  GB_IFRAME.style.width = GB_WIDTH + "px";
  GB_HEADER.style.width = GB_WIDTH + "px";

  GB_WINDOW.style.height = GB_HEIGHT + "px";
  GB_IFRAME.style.height = GB_HEIGHT - 5 + "px";

  if((navigator.userAgent.toLowerCase().indexOf("firefox") != -1))
    GB_OVERLAY.style.width = "100%";
  else
    GB_OVERLAY.style.width = array_page_size[0] + "px";

  var max_height = Math.max(getScrollTop()+array_page_size[1], getScrollTop()+GB_HEIGHT+30);
  GB_OVERLAY.style.height = max_height + "px";

  GB_WINDOW.style.left = ((array_page_size[0] - GB_WINDOW.offsetWidth) /2) + "px";
  GB_HEADER.style.left = ((array_page_size[0] - GB_HEADER.offsetWidth) /2) + "px";

}

function GB_init() {
  //Create the overlay
  GB_OVERLAY = DIV({'id': 'GB_overlay'});

  if(GB_overlay_click_close)
    GB_OVERLAY.onclick = GB_hide;

  getBody().insertBefore(GB_OVERLAY, getBody().firstChild);

  //Create the window
  GB_WINDOW = DIV({'id': 'GB_window'});

  GB_HEADER = DIV({'id': 'GB_header'});
  GB_caption = DIV({'id': 'GB_caption'}, "");

  var close = DIV({'id': 'GB_close'}, IMG({'src': GB_IMG_DIR + 'close.gif', 'alt': 'Cerrar'}));
  close.onclick = GB_hide;
  ACN(GB_HEADER, close, GB_caption);

  getBody().insertBefore(GB_WINDOW, GB_OVERLAY.nextSibling);
  getBody().insertBefore(GB_HEADER, GB_OVERLAY.nextSibling);

}

function initIfNeeded() {
  if(GB_OVERLAY == null) {
    GB_init();
    GB_addOnWinResize(GB_setWidth);
    window.onscroll = function() { GB_setPosition(); GB_setWidth(); };
  }
  //Remove the old iFrame
  var new_frame = IFRAME({'id': 'GB_frame', 'name': 'GB_frame'});
  if (GB_IFRAME != null)
    removeElement(GB_IFRAME);
  ACN(GB_WINDOW, new_frame);
  GB_IFRAME = new_frame;
}

function GB_getWindowSize(){
	var window_width, window_height;
	if (self.innerHeight) {	// all except Explorer
		window_width = self.innerWidth;
		window_height = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		window_width = document.documentElement.clientWidth;
		window_height = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		window_width = document.body.clientWidth;
		window_height = document.body.clientHeight;
	}
	return [window_width, window_height];
}

function GB_addOnWinResize(func) {
  var oldonrezise = window.onresize;
  if (typeof window.onresize != 'function')
    window.onresize = func;
  else {
    window.onresize = function() {
      oldonrezise();
      func();
    }
  }
}

function positionRightVertically(elm, value) {
  elm.style.top = getScrollTop()+value+"px";
}

function getScrollTop() {
  //From: http://www.quirksmode.org/js/doctypes.html
  var theTop;
  if (document.documentElement && document.documentElement.scrollTop)
      theTop = document.documentElement.scrollTop;
  else if (document.body)
      theTop = document.body.scrollTop;
  return theTop;
}


text:
var util = require('util')
var fritzboxtools = require('../lib/fritzboxtools');
var express = require('express');
var argv = require('yargs')
			.usage('Usage: $0 --fboxuri [string] --user [string] --pass [string]')
    		.demand(['user', 'pass'])
    		.default('fboxuri', 'fritz.box')
    		.default('state', 1)
    		.default('port', 17800)
    		.argv;

var restproxy = express();

var fbox = new fritzboxtools(argv.fboxuri);

fbox.login(argv.user, argv.pass, function(){

	restproxy.get('/alloutlets', function (req, res) {

		util.debug("outletlist requested");

		fbox.getData(function(list){
			res.send(list.devices);
		});
	});

	restproxy.get('/switch/:id/:state', function (req, res) {

		util.debug("switchstatechange requested");

  		if(req.params.state == "on"){
  			var numstate = 1;
  		}else if(req.params.state == "off"){
  			var numstate = 0;
  		}else{
	  		res.send("wrong state submitted. nothing has been changed.");
  			return;
  		}

  		fbox.SwitchOnOff(req.params.id, numstate, function(result){
  			var resmsg = "";
  			if(result.status == "switchStateChanged"){
				resmsg = "device id " + req.params.id +
						   " successfully switched to " + (numstate == 1 ? "on" : "off");
			}else{
				resmsg = "device id " + req.params.id + " state could not be changed...";
			}

  			res.send(resmsg);
  		});

	});

	restproxy.listen(argv.port);
	util.debug("fritzboxtools restproxy is listening on " + argv.port)

	//keepalive every 5 minutes...TODO: implement restproxy.ini..
	setInterval(function(){
		fbox.login(argv.user, argv.pass);
	},300000);

});


text:
import React, { useState, useMemo } from 'react'
import styled from '../../lib/styled'
import { usePreferences } from '../../lib/preferences'
import TabButton from './TabButton'
import { useGlobalKeyDownHandler } from '../../lib/keyboard'
import GeneralTab from './GeneralTab'
import EditorTab from './EditorTab'
import MarkdownTab from './MarkdownTab'
import AboutTab from './AboutTab'
import BillingTab from './BillingTab'
import ImportTab from './ImportTab'
import { backgroundColor, closeIconColor } from '../../lib/styled/styleFunctions'
import { IconClose } from '../icons'
import { useTranslation } from 'react-i18next'

const Container = styled.div`
  z-index: 7000;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  ${backgroundColor}
  display: flex;
  overflow: hidden;
`

const Header = styled.h1`
  margin: 0;
  padding: 1em 0;
`

const TabNav = styled.nav`
  width: 200px;
  margin-left: 30px;
`

const TabContent = styled.div`
  flex: 1;
  overflow-y: auto;
  padding-left: 4px;
  padding-top: 4em;
  padding-right: 30px;
`

const CloseButton = styled.button`
  position: absolute;
  top: 0;
  right: 12px;
  width: 40px;
  height: 40px;
  background-color: transparent;
  border: none;
  font-size: 24px;
  ${closeIconColor}
`

const PreferencesModal = () => {
  const { t } = useTranslation()
  const { closed, toggleClosed } = usePreferences()
  const [tab, setTab] = useState('general')

  const keydownHandler = useMemo(() => {
    return (event: KeyboardEvent) => {
      if (!closed && event.key === 'Escape') {
        toggleClosed()
      }
    }
  }, [closed, toggleClosed])
  useGlobalKeyDownHandler(keydownHandler)

  const content = useMemo(() => {
    switch (tab) {
      case 'editor':
        return <EditorTab />
      case 'markdown':
        return <MarkdownTab />
      case 'about':
        return <AboutTab />
      case 'billing':
        return <BillingTab />
      case 'import':
        return <ImportTab />
      case 'general':
      default:
        return <GeneralTab />
    }
  }, [tab])

  if (closed) {
    return null
  }

  return (
    <Container>
      <TabNav>
        <Header>{t('preferences.general')}</Header>
        <TabButton
          label='General'
          tab='general'
          active={tab === 'general'}
          setTab={setTab}
        />
        <TabButton
          label='Editor'
          tab='editor'
          active={tab === 'editor'}
          setTab={setTab}
        />
        <TabButton
          label='Markdown'
          tab='markdown'
          active={tab === 'markdown'}
          setTab={setTab}
        />
        {/* <TabButton
          label='Hotkeys'
          tab='hotkeys'
          active={tab === 'hotkeys'}
          setTab={setTab}
        /> */}
        <TabButton
          label='About'
          tab='about'
          active={tab === 'about'}
          setTab={setTab}
        />
        <TabButton
          label='Billing'
          tab='billing'
          active={tab === 'billing'}
          setTab={setTab}
        />
        <TabButton
          label='Import'
          tab='import'
          active={tab === 'import'}
          setTab={setTab}
        />
      </TabNav>
      <TabContent>{content}</TabContent>
      <CloseButton onClick={toggleClosed}>
        <IconClose />
      </CloseButton>
    </Container>
  )
}

export default PreferencesModal


text:
require 'fog/openstack/requests/volume/delete_snapshot_metadata'
require 'fog/openstack/requests/volume_v1/real'


text:
package org.elasticsearch.index.query;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.QueryWrapperFilter;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MapperService;

import java.io.IOException;

/**
 *
 */
public class PrefixFilterParser implements FilterParser {

    public static final String NAME = "prefix";

    @Inject
    public PrefixFilterParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME};
    }

    @Override
    public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        String fieldName = null;
        Object value = null;

        String filterName = null;
        String currentFieldName = null;
        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token.isValue()) {
                if ("_name".equals(currentFieldName)) {
                    filterName = parser.text();
                } else {
                    fieldName = currentFieldName;
                    value = parser.objectBytes();
                }
            }
        }

        if (value == null) {
            throw new QueryParsingException(parseContext, "No value specified for prefix filter");
        }

        Filter filter = null;

        MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
        if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
            filter = smartNameFieldMappers.mapper().prefixFilter(value, parseContext);
        }
        if (filter == null) {
            filter = new QueryWrapperFilter(new PrefixQuery(new Term(fieldName, BytesRefs.toBytesRef(value))));
        }

        if (filterName != null) {
            parseContext.addNamedFilter(filterName, filter);
        }
        return filter;
    }
}


text:
"""Retrieves a list of installed apps from Splunk using the binding module."""

from xml.etree import ElementTree

import splunk.binding as binding

HOST = "localhost"
PORT = 8089
USERNAME = "admin"
PASSWORD = "changeme"

context = binding.connect(
    host=HOST,
    port=PORT,
    username=USERNAME,
    password=PASSWORD)

response = context.get('apps/local')
if response.status != 200:
    raise Exception, "%d (%s)" % (response.status, response.reason)

body = response.body.read()
data = ElementTree.XML(body)
apps = data.findall("{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title")
for app in apps:
    print app.text


text:
{
  if (Array.isArray(el.attrsList)) {
    el.attrsList.forEach(function(attr) {
      if (attr.name && attr.name.match(/\-/)) {
        var realName = normalizeKeyName(attr.name);

        if (el.attrsMap) {
          el.attrsMap[realName] = el.attrsMap[attr.name];
          delete el.attrsMap[attr.name];
        }

        attr.name = realName;
      }
    });
  }
}


text:
layout: post
date: 2016-07-15
title: "Lis Simon FARRAH 2014 Sleeveless Chapel Train Ballgown High Low"
category: Lis Simon
tags: [Lis Simon ,Lis Simon,Ballgown,High Low,Strapless,Chapel Train,Sleeveless,2014]
---
### Lis Simon FARRAH
Just **$349.99**
### 2014  Sleeveless Chapel Train Ballgown High Low

BRANDS	Lis Simon

Silhouette	Ballgown

Trend	High Low

Neckline	Strapless

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2014

Buy it: [https://www.readybrides.com/en/lis-simon-/44413-lis-simon-farrah.html](https://www.readybrides.com/en/lis-simon-/44413-lis-simon-farrah.html)


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

#include "components/autofill/core/browser/webdata/autofill_data_type_controller.h"

#include <memory>

#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/autofill/core/browser/webdata/autocomplete_syncable_service.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/sync/driver/data_type_controller_mock.h"
#include "components/sync/driver/fake_sync_client.h"
#include "components/sync/model/sync_error.h"
#include "components/webdata_services/web_data_service_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using autofill::AutofillWebDataService;
using autofill::AutofillWebDataBackend;

namespace browser_sync {

namespace {

using testing::_;
using testing::Return;

class NoOpAutofillBackend : public AutofillWebDataBackend {
 public:
  NoOpAutofillBackend() {}
  ~NoOpAutofillBackend() override {}
  WebDatabase* GetDatabase() override { return NULL; }
  void AddObserver(
      autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
  void RemoveObserver(
      autofill::AutofillWebDataServiceObserverOnDBThread* observer) override {}
  void RemoveExpiredFormElements() override {}
  void NotifyOfMultipleAutofillChanges() override {}
  void NotifyThatSyncHasStarted(syncer::ModelType /* model_type */) override {}
};

// Fake WebDataService implementation that stubs out the database loading.
class FakeWebDataService : public AutofillWebDataService {
 public:
  FakeWebDataService(
      const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner,
      const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner)
      : AutofillWebDataService(ui_task_runner, db_task_runner),
        is_database_loaded_(false),
        db_task_runner_(db_task_runner),
        db_loaded_callback_(base::Callback<void(void)>()) {}

  // Mark the database as loaded and send out the appropriate notification.
  void LoadDatabase() {
    StartSyncableService();
    is_database_loaded_ = true;

    if (!db_loaded_callback_.is_null()) {
      db_loaded_callback_.Run();
      // Clear the callback here or the WDS and DTC will have refs to each other
      // and create a memory leak.
      db_loaded_callback_ = base::Callback<void(void)>();
    }
  }

  bool IsDatabaseLoaded() override { return is_database_loaded_; }

  void RegisterDBLoadedCallback(
      const base::Callback<void(void)>& callback) override {
    db_loaded_callback_ = callback;
  }

  void StartSyncableService() {
    // The |autofill_profile_syncable_service_| must be constructed on the DB
    // thread.
    base::RunLoop run_loop;
    db_task_runner_->PostTaskAndReply(
        FROM_HERE, base::Bind(&FakeWebDataService::CreateSyncableService,
                              base::Unretained(this)),
        run_loop.QuitClosure());
    run_loop.Run();
  }

 private:
  ~FakeWebDataService() override {}

  void CreateSyncableService() {
    ASSERT_TRUE(db_task_runner_->BelongsToCurrentThread());
    // These services are deleted in DestroySyncableService().
    autofill::AutocompleteSyncableService::CreateForWebDataServiceAndBackend(
        this, &autofill_backend_);
  }

  bool is_database_loaded_;
  NoOpAutofillBackend autofill_backend_;
  const scoped_refptr<base::SingleThreadTaskRunner> db_task_runner_;
  base::Callback<void(void)> db_loaded_callback_;

  DISALLOW_COPY_AND_ASSIGN(FakeWebDataService);
};

class SyncAutofillDataTypeControllerTest : public testing::Test {
 public:
  SyncAutofillDataTypeControllerTest()
      : db_thread_("DB_Thread"),
        last_start_result_(syncer::DataTypeController::OK),
        weak_ptr_factory_(this) {}
  ~SyncAutofillDataTypeControllerTest() override {}

  void SetUp() override {
    db_thread_.Start();
    web_data_service_ = new FakeWebDataService(
        base::ThreadTaskRunnerHandle::Get(), db_thread_.task_runner());
    autofill_dtc_ = base::MakeUnique<AutofillDataTypeController>(
        db_thread_.task_runner(), base::Bind(&base::DoNothing), &sync_client_,
        web_data_service_);
  }

  void TearDown() override {
    web_data_service_->ShutdownOnUIThread();

    // Make sure WebDataService is shutdown properly on DB thread before we
    // destroy it.
    base::RunLoop run_loop;
    ASSERT_TRUE(db_thread_.task_runner()->PostTaskAndReply(
        FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()));
    run_loop.Run();
  }

  // Passed to AutofillDTC::Start().
  void OnStartFinished(syncer::DataTypeController::ConfigureResult result,
                       const syncer::SyncMergeResult& local_merge_result,
                       const syncer::SyncMergeResult& syncer_merge_result) {
    last_start_result_ = result;
    last_start_error_ = local_merge_result.error();
  }

  void OnLoadFinished(syncer::ModelType type, const syncer::SyncError& error) {
    EXPECT_FALSE(error.IsSet());
    EXPECT_EQ(type, syncer::AUTOFILL);
  }

  void BlockForDBThread() {
    base::RunLoop run_loop;
    ASSERT_TRUE(db_thread_.task_runner()->PostTaskAndReply(
        FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()));
    run_loop.Run();
  }

 protected:
  base::MessageLoop message_loop_;
  base::Thread db_thread_;
  syncer::FakeSyncClient sync_client_;
  std::unique_ptr<AutofillDataTypeController> autofill_dtc_;
  scoped_refptr<FakeWebDataService> web_data_service_;

  // Stores arguments of most recent call of OnStartFinished().
  syncer::DataTypeController::ConfigureResult last_start_result_;
  syncer::SyncError last_start_error_;
  base::WeakPtrFactory<SyncAutofillDataTypeControllerTest> weak_ptr_factory_;
};

// Load the WDS's database, then start the Autofill DTC.  It should
// immediately try to start association and fail (due to missing DB
// thread).
TEST_F(SyncAutofillDataTypeControllerTest, StartWDSReady) {
  web_data_service_->LoadDatabase();
  autofill_dtc_->LoadModels(
      base::Bind(&SyncAutofillDataTypeControllerTest::OnLoadFinished,
                 weak_ptr_factory_.GetWeakPtr()));

  autofill_dtc_->StartAssociating(
      base::Bind(&SyncAutofillDataTypeControllerTest::OnStartFinished,
                 weak_ptr_factory_.GetWeakPtr()));
  BlockForDBThread();

  EXPECT_EQ(syncer::DataTypeController::ASSOCIATION_FAILED, last_start_result_);
  EXPECT_TRUE(last_start_error_.IsSet());
  EXPECT_EQ(syncer::DataTypeController::DISABLED, autofill_dtc_->state());
}

// Start the autofill DTC without the WDS's database loaded, then
// start the DB.  The Autofill DTC should be in the MODEL_STARTING
// state until the database in loaded, when it should try to start
// association and fail (due to missing DB thread).
TEST_F(SyncAutofillDataTypeControllerTest, StartWDSNotReady) {
  autofill_dtc_->LoadModels(
      base::Bind(&SyncAutofillDataTypeControllerTest::OnLoadFinished,
                 weak_ptr_factory_.GetWeakPtr()));

  EXPECT_EQ(syncer::DataTypeController::OK, last_start_result_);
  EXPECT_FALSE(last_start_error_.IsSet());
  EXPECT_EQ(syncer::DataTypeController::MODEL_STARTING, autofill_dtc_->state());

  web_data_service_->LoadDatabase();

  autofill_dtc_->StartAssociating(
      base::Bind(&SyncAutofillDataTypeControllerTest::OnStartFinished,
                 weak_ptr_factory_.GetWeakPtr()));
  BlockForDBThread();

  EXPECT_EQ(syncer::DataTypeController::ASSOCIATION_FAILED, last_start_result_);
  EXPECT_TRUE(last_start_error_.IsSet());

  EXPECT_EQ(syncer::DataTypeController::DISABLED, autofill_dtc_->state());
}

}  // namespace

}  // namespace browser_sync


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="App\AppBundle\Entity\Colis" table="colis">
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="type" type="string" column="type" length="255" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
  </entity>
</doctrine-mapping>


text:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace RockLib.Logging.AspNetCore
{
    /// <summary>
    /// An implementation of <see cref="IContextProvider"/> used to add the ForwardedFor value to a <see cref="LogEntry"/>.
    /// </summary>
    public class ForwardedForContextProvider : IContextProvider
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ForwardedForContextProvider"/> class.
        /// </summary>
        /// <param name="httpContextAccessor">The http context accessor used to retreive the ForwardedFor value.</param>
        public ForwardedForContextProvider(IHttpContextAccessor httpContextAccessor)
            : this(httpContextAccessor?.HttpContext?.GetForwardedFor() ?? default)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ForwardedForContextProvider"/> class.
        /// </summary>
        /// <param name="forwardedFor">The FowardedFor value.</param>
        public ForwardedForContextProvider(StringValues forwardedFor)
        {
            ForwardedFor = forwardedFor;
        }

        /// <summary>
        /// Gets the ForwardedFor value.
        /// </summary>
        public StringValues ForwardedFor { get; }

        /// <summary>
        /// Add custom context to the <see cref="LogEntry"/> object.
        /// </summary>
        /// <param name="logEntry">The log entry to add custom context to.</param>
        public void AddContext(LogEntry logEntry)
        {
            logEntry.SetForwardedFor(ForwardedFor);
        }
    }
}


text:
name             'awscli'
maintainer       'Balanced'
maintainer_email 'mahmoud@balancedpayments.com'
license          'MIT'
description      'Installs/Configures awscli'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '1.0.2'

depends 'balanced-apt', '~> 1.0.12'
depends 'python', '~> 1.4.4'
depends 'balanced-citadel', '~> 1.0.2'


text:
package org.openstack.atlas.service.domain.pojo;

public class AccountLoadBalancer {
    private int loadBalancerId;
    private String loadBalancerName;
    private int clusterId;
    private String clusterName;
    private String status;
    private String protocol;

    public int getLoadBalancerId() {
        return loadBalancerId;
    }

    public void setLoadBalancerId(int loadBalancerId) {
        this.loadBalancerId = loadBalancerId;
    }

    public String getLoadBalancerName() {
        return loadBalancerName;
    }

    public void setLoadBalancerName(String loadBalancerName) {
        this.loadBalancerName = loadBalancerName;
    }

    public int getClusterId() {
        return clusterId;
    }

    public void setClusterId(int clusterId) {
        this.clusterId = clusterId;
    }

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String clusterStatus) {
        this.status = clusterStatus;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

}


text: Orwell::Application.config.session_store :cookie_store, key: '_orwell_session'


text:
videojs.addLanguage('zh-CN', {
  "No video has been loaded": "未加载视频",
  "Could not download the video": "无法下载视频",
  "The video connection was lost, please confirm you are connected to the internet": "视频连接丢失,请确认已连接至互联网",
  "The video is bad or in a format that cannot be played on your browser": "视频已损坏,或使用无法在浏览器中播放的格式",
  "This video is either unavailable or not supported in this browser": "此视频不可用或不受此浏览器支持",
  "Error Code": "错误代码",
  "Technical details": "技术细节",
  "The video download was cancelled": "视频下载已取消",
  "The video you are trying to watch is encrypted and we do not know how to decrypt it": "您尝试观看的视频已加密,而且解密方法未知",
  "An unanticipated problem was encountered, check back soon and try again": "发生意外问题,稍后请检查并重试"
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Static Analysis of Free Monads :: Reasonably Polymorphic</title>
        <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible" />
        <link href="/atom.xml" rel="alternate" title="Reasonably Polymorphic - Atom" type="application/atom+xml" />
        <link href="/feed.rss" rel="alternate" title="Reasonably Polymorphic - RSS" type="application/rss+xml" />

        <link href='https://fonts.googleapis.com/css?family=Amiri|Muli' rel='stylesheet' type='text/css' />
        <link href="/css/style.css" type="text/css" rel="stylesheet" />
        <link href="/css/syntax.css" type="text/css" rel="stylesheet" />

Static Analysis of Free Monads

        ←

        →

    <time>July  7, 2018</time>

        free, monad, library, announcement, prospect

Motivation

A common misperception of free monads is that they allow for analysis of an program expressed with them. This is not true, and in fact, monads are too liberal of an abstraction to allow for inspection in general.

In order to see why, consider the following monadic expression:

      getLine
  >>= \str -> if str == "backdoor"
                 then launchNukes
                 else pure ()

The problem here is that bind is expressed via a continuation, and we're unable to look inside that continuation without calling the function. So we're stuck. We can't determine if the above program will ever call launchNukes unless we just happen to call the lambda with the exact string "backdoor".

So, in general, we're unable to statically inspect monads. We can run them (not necessarily in the IO monad) and see what happens, but getting a free monad to help with this is equivalent to mocking the exact problem domain. But, even though we can't do it in general, it seems like we should be able to do it in certain cases. Consider the following monadic expression:

            getLine
  >>= \_ -> launchNukes

In this case, the computation doesn't actually care about the result of getLine, so in theory we can just call the continuation with undefined and find that yes indeed this expression will call launchNukes.

Notice that we can't use this strategy in the first expression we looked at, because that one scrutinized the result of getLine, and branched depending on it. If we tried passing undefined to it, it would crash with an error when we tried to force the final value of the monad (although this might be preferable to actually launching nukes.)

This example of launchNukes is admittedly rather silly. My original motivation for investigating this is in the context of ecstasy in which users can query and manipulate disparate pieces of data. For example, if we wanted to write a physics simulator where each object may or may not have any of a position :: V2 Double, a velocity :: V2 Double and a hasPhysics :: Bool, we could write the following piece of code to update the positions of any entities that have a velocity and are, in fact, affected by physics:

emap $ do
  p <- query position
  v <- query velocity
  h <- query hasPhysics

  guard h

  pure unchanged
    { position = Set $ p + v ^* timeDelta
    }

Because objects are not required to have all of the possible data, mapping this function will intentionally fail for any of the following reasons:

the object did not have a position field

the object did not have a velocity field

the object did not have a hasPhysics field

the object had a hasPhysics field whose value was False

Without being able to statically analyze this monadic code, our only recourse is to attempt to run it over every object in the universe, and be happy when we succeed. While such an approach works, it's terribly inefficient if the universe is large but any of the position, velocity or hasPhysics fields is sparse.

What would be significantly more efficient for large worlds with sparse data would be to compute the intersection of objects who have all three of position, velocity and hasPhysics, and then run the computation only over those objects. Free applicatives (which are amenable to static analysis) are no good here, since our guard h line really-and-truly is necessarily monadic.

Any such static analysis of this monad would be purely an optimization, which suggests we don't need it to be perfect; all that we are asking for is for it to be better than nothing. A best-effort approach in the spirit of our earlier "just pass undefined around and hope it doesn't crash" would be sufficient. If we can be convinced it won't actually crash.

What we'd really like to be able to do is count every occurrence of query in this monad before it branches based on the result of an earlier query. Which is to say we'd like to pass undefined around, do as much static analysis as we can, and then somehow fail our analysis just before Haskell would crash due to evaluating an undefined.

Prospecting Monads

I've been playing around with this conceptual approach for some time, but could never seem to get it to work. Laziness can sure be one hell of a bastard when you're trying to pervert Haskell's execution order.

However, last week Foner et al. dropped a bomb of a paper Keep Your Laziness in Check, which describes a novel approach for observing evaluations of thunks in Haskell. The gist of the technique is to use unsafePerformIO to build an IORef, and then set its value at the same time you force the thunk. If you (unsafely) read from the IORef and see that it hasn't been set, then nobody has forced your value yet.

We can use a similar approach to accomplish our optimization goals. For the crux of the approach, consider the follow verify function that will evaluate a pure thunk and return empty if it instead found a bottom:

verify :: Alternative f => a -> f b
verify f a = unsafePerformIO $ do
  catch
    (let !_ = a
      in pure $ pure a)
    (\(_ :: SomeException) -> pure empty)

The bang pattern !_ = a tells Haskell to seq a, which reduces it to WHNF, which, if its WHNF is bottom, will be caught inside of the catch. unsafePerformIO is necessary here, because exceptions can only be caught in IO.

Using this approach, if we're very careful, we can tear down a free monad by following its continuations using bottom, and doing the verify trick to stop exactly when we need to.

I call such a thing prospect, and you can find it on github. The name comes from the fact that this can lead to gold, but carries with it the intrinsic dangers of plumbing into the depths, such as cave-ins, blackened lungs, or the worse things that dwell in the darkness.

The primary export of prospect is the titular function prospect :: Free f a -> (Maybe a, [f ()]), which tears down a free monad, tells you whether or not it has a pure return value, and spits out as many f constructors as it could before the computation branched. If you got a Just back, it means it found every constructor, but there are no other guarantees.

Happy prospecting!

Huge shoutouts to Vikrem who was a very patient sounding-board for all of my crazy ideas, and to kcsongor who suggested that I pay a lot more attention to where I'm being strict.

        ←

        →

      Please enable JavaScript to view the comments powered by Disqus.

REASONABLY
POLYMORPHIC

 Hi there. I'm Sandy Maguire. I like improving life and
        making cool things.

If you want to get in touch, I'd love to hear from you! Send me an
        email; you can contact me via <tt>sandy</tt> at <tt>sandymaguire.me</tt>.

SITE LINKS

Archives

Talks

THINGS I MAKE

Code on github

Book archive

My other blog

WHAT I'M DOING

Erdos Project

Music at last.fm

Books at goodreads

Papers at mendeley

        © 2015-2020 Sandy Maguire

REASONABLY POLYMORPHIC

ARCHIVES


text:
package cn.hicc.information.sensorsignin.view;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.VideoView;

/**
 * 视频播放背景
 */

public class CustomVideoView extends VideoView {
    public CustomVideoView(Context context) {
        super(context);
    }

    public CustomVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //我们重新计算高度
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }
    @Override
    public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
        super.setOnPreparedListener(l);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
}


text:
using metaprogramming.interfaces;
using metaprogramming.server.Roslyn;
using System;
using System.Collections.Generic;
using System.Linq;
using Excess.Runtime;
using Ninject;

namespace metaprogramming.server
{
    [AutoInit]
    public class NinjectExcessModule : Ninject.Modules.NinjectModule
    {
        private class NinjectInstantiator : IInstantiator
        {
            IKernel _kernel = new StandardKernel(new NinjectExcessModule());
            public object Create(Type type)
            {
                return _kernel.GetService(type);
            }
        }

        public static void __init(__Scope scope)
        {
            scope.set<IInstantiator>(new NinjectInstantiator());
        }

        public override void Load()
        {
            Bind<ICodeTranspiler>().To<Transpiler>();
            Bind<IGraphTranspiler>().To<GraphTranspiler>();
        }
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Compute.Models
{
    internal partial class ContainerServiceListResult
    {
        internal static ContainerServiceListResult DeserializeContainerServiceListResult(JsonElement element)
        {
            Optional<IReadOnlyList<ContainerService>> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ContainerService> array = new List<ContainerService>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ContainerService.DeserializeContainerService(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new ContainerServiceListResult(Optional.ToList(value), nextLink.Value);
        }
    }
}


text:
package com.microsoft.azure.documentdb.sample.dao;

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

import com.google.gson.Gson;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.Document;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.sample.model.TodoItem;

public class DocDbDao implements TodoDao {
    // The name of our database.
    private static final String DATABASE_ID = "TestDB";

    // The name of our collection.
    private static final String COLLECTION_ID = "TestCollection";

    // We'll use Gson for POJO <=> JSON serialization for this example.
    private static Gson gson = new Gson();

    // The DocumentDB Client
    private static DocumentClient documentClient = DocumentClientFactory
            .getDocumentClient();

    // Cache for the database object, so we don't have to query for it to
    // retrieve self links.
    private static Database databaseCache;

    // Cache for the collection object, so we don't have to query for it to
    // retrieve self links.
    private static DocumentCollection collectionCache;

    @Override
    public TodoItem createTodoItem(TodoItem todoItem) {
        // Serialize the TodoItem as a JSON Document.
        Document todoItemDocument = new Document(gson.toJson(todoItem));

        // Annotate the document as a TodoItem for retrieval (so that we can
        // store multiple entity types in the collection).
        todoItemDocument.set("entityType", "todoItem");

        try {
            // Persist the document using the DocumentClient.
            todoItemDocument = documentClient.createDocument(
                    getTodoCollection().getSelfLink(), todoItemDocument, null,
                    false).getResource();
        } catch (DocumentClientException e) {
            e.printStackTrace();
            return null;
        }

        return gson.fromJson(todoItemDocument.toString(), TodoItem.class);
    }

    @Override
    public TodoItem readTodoItem(String id) {
        // Retrieve the document by id using our helper method.
        Document todoItemDocument = getDocumentById(id);

        if (todoItemDocument != null) {
            // De-serialize the document in to a TodoItem.
            return gson.fromJson(todoItemDocument.toString(), TodoItem.class);
        } else {
            return null;
        }
    }

    @Override
    public List<TodoItem> readTodoItems() {
        List<TodoItem> todoItems = new ArrayList<TodoItem>();

        // Retrieve the TodoItem documents
        List<Document> documentList = documentClient
                .queryDocuments(getTodoCollection().getSelfLink(),
                        "SELECT * FROM root r WHERE r.entityType = 'todoItem'",
                        null).getQueryIterable().toList();

        // De-serialize the documents in to TodoItems.
        for (Document todoItemDocument : documentList) {
            todoItems.add(gson.fromJson(todoItemDocument.toString(),
                    TodoItem.class));
        }

        return todoItems;
    }

    @Override
    public TodoItem updateTodoItem(String id, boolean isComplete) {
        // Retrieve the document from the database
        Document todoItemDocument = getDocumentById(id);

        // You can update the document as a JSON document directly.
        // For more complex operations - you could de-serialize the document in
        // to a POJO, update the POJO, and then re-serialize the POJO back in to
        // a document.
        todoItemDocument.set("complete", isComplete);

        try {
            // Persist/replace the updated document.
            todoItemDocument = documentClient.replaceDocument(todoItemDocument,
                    null).getResource();
        } catch (DocumentClientException e) {
            e.printStackTrace();
            return null;
        }

        return gson.fromJson(todoItemDocument.toString(), TodoItem.class);
    }

    @Override
    public boolean deleteTodoItem(String id) {
        // DocumentDB refers to documents by self link rather than id.

        // Query for the document to retrieve the self link.
        Document todoItemDocument = getDocumentById(id);

        try {
            // Delete the document by self link.
            documentClient.deleteDocument(todoItemDocument.getSelfLink(), null);
        } catch (DocumentClientException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    private Database getTodoDatabase() {
        if (databaseCache == null) {
            // Get the database if it exists
            List<Database> databaseList = documentClient
                    .queryDatabases(
                            "SELECT * FROM root r WHERE r.id='" + DATABASE_ID
                                    + "'", null).getQueryIterable().toList();

            if (databaseList.size() > 0) {
                // Cache the database object so we won't have to query for it
                // later to retrieve the selfLink.
                databaseCache = databaseList.get(0);
            } else {
                // Create the database if it doesn't exist.
                try {
                    Database databaseDefinition = new Database();
                    databaseDefinition.setId(DATABASE_ID);

                    databaseCache = documentClient.createDatabase(
                            databaseDefinition, null).getResource();
                } catch (DocumentClientException e) {
                    // TODO: Something has gone terribly wrong - the app wasn't
                    // able to query or create the collection.
                    // Verify your connection, endpoint, and key.
                    e.printStackTrace();
                }
            }
        }

        return databaseCache;
    }

    private DocumentCollection getTodoCollection() {
        if (collectionCache == null) {
            // Get the collection if it exists.
            List<DocumentCollection> collectionList = documentClient
                    .queryCollections(
                            getTodoDatabase().getSelfLink(),
                            "SELECT * FROM root r WHERE r.id='" + COLLECTION_ID
                                    + "'", null).getQueryIterable().toList();

            if (collectionList.size() > 0) {
                // Cache the collection object so we won't have to query for it
                // later to retrieve the selfLink.
                collectionCache = collectionList.get(0);
            } else {
                // Create the collection if it doesn't exist.
                try {
                    DocumentCollection collectionDefinition = new DocumentCollection();
                    collectionDefinition.setId(COLLECTION_ID);

                    collectionCache = documentClient.createCollection(
                            getTodoDatabase().getSelfLink(),
                            collectionDefinition, null).getResource();
                } catch (DocumentClientException e) {
                    // TODO: Something has gone terribly wrong - the app wasn't
                    // able to query or create the collection.
                    // Verify your connection, endpoint, and key.
                    e.printStackTrace();
                }
            }
        }

        return collectionCache;
    }

    private Document getDocumentById(String id) {
        // Retrieve the document using the DocumentClient.
        List<Document> documentList = documentClient
                .queryDocuments(getTodoCollection().getSelfLink(),
                        "SELECT * FROM root r WHERE r.id='" + id + "'", null)
                .getQueryIterable().toList();

        if (documentList.size() > 0) {
            return documentList.get(0);
        } else {
            return null;
        }
    }

}


text:
package com.amazonaws.services.lakeformation.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListDataCellsFilterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * A list of DataCellFilter structures.
     *

     */
    private java.util.List<DataCellsFilter> dataCellsFilters;
    /**
     *

     * A continuation token, if not all requested data cell filters have been returned.
     *

     */
    private String nextToken;

    /**
     *

     * A list of DataCellFilter structures.
     *

     *
     * @return A list of DataCellFilter structures.
     */

    public java.util.List<DataCellsFilter> getDataCellsFilters() {
        return dataCellsFilters;
    }

    /**
     *

     * A list of DataCellFilter structures.
     *

     *
     * @param dataCellsFilters
     *        A list of DataCellFilter structures.
     */

    public void setDataCellsFilters(java.util.Collection<DataCellsFilter> dataCellsFilters) {
        if (dataCellsFilters == null) {
            this.dataCellsFilters = null;
            return;
        }

        this.dataCellsFilters = new java.util.ArrayList<DataCellsFilter>(dataCellsFilters);
    }

    /**
     *

     * A list of DataCellFilter structures.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setDataCellsFilters(java.util.Collection)} or {@link #withDataCellsFilters(java.util.Collection)} if you
     * want to override the existing values.
     *

     *
     * @param dataCellsFilters
     *        A list of DataCellFilter structures.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListDataCellsFilterResult withDataCellsFilters(DataCellsFilter... dataCellsFilters) {
        if (this.dataCellsFilters == null) {
            setDataCellsFilters(new java.util.ArrayList<DataCellsFilter>(dataCellsFilters.length));
        }
        for (DataCellsFilter ele : dataCellsFilters) {
            this.dataCellsFilters.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of DataCellFilter structures.
     *

     *
     * @param dataCellsFilters
     *        A list of DataCellFilter structures.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListDataCellsFilterResult withDataCellsFilters(java.util.Collection<DataCellsFilter> dataCellsFilters) {
        setDataCellsFilters(dataCellsFilters);
        return this;
    }

    /**
     *

     * A continuation token, if not all requested data cell filters have been returned.
     *

     *
     * @param nextToken
     *        A continuation token, if not all requested data cell filters have been returned.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * A continuation token, if not all requested data cell filters have been returned.
     *

     *
     * @return A continuation token, if not all requested data cell filters have been returned.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * A continuation token, if not all requested data cell filters have been returned.
     *

     *
     * @param nextToken
     *        A continuation token, if not all requested data cell filters have been returned.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListDataCellsFilterResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDataCellsFilters() != null)
            sb.append("DataCellsFilters: ").append(getDataCellsFilters()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListDataCellsFilterResult == false)
            return false;
        ListDataCellsFilterResult other = (ListDataCellsFilterResult) obj;
        if (other.getDataCellsFilters() == null ^ this.getDataCellsFilters() == null)
            return false;
        if (other.getDataCellsFilters() != null && other.getDataCellsFilters().equals(this.getDataCellsFilters()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDataCellsFilters() == null) ? 0 : getDataCellsFilters().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListDataCellsFilterResult clone() {
        try {
            return (ListDataCellsFilterResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
import * as CleanCSS from 'clean-css';

let source = 'a{font-weight:bold;}';
console.log(new CleanCSS().minify(source).styles);

source = '@import url(http://path/to/remote/styles);';
new CleanCSS().minify(source, (error: any, minified: CleanCSS.Output): void => {
  console.log(minified.styles);
});

const pathToOutputDirectory = 'path';

new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory })
  .minify(source, (error: any, minified: CleanCSS.Output): void => {
    // access minified.sourceMap for SourceMapGenerator object
    // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
    // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI
    console.log(minified.sourceMap);
});

const inputSourceMapAsString = 'input';
new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory })
  .minify(source, inputSourceMapAsString, (error: any, minified: CleanCSS.Output): void => {
    // access minified.sourceMap to access SourceMapGenerator object
    // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
    // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI
    console.log(minified.sourceMap);
});

new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }).minify({
  'path/to/source/1': {
    styles: '...styles...',
    sourceMap: '...source-map...'
  },
  'path/to/source/2': {
    styles: '...styles...',
    sourceMap: '...source-map...'
  }
}, (error: any, minified: CleanCSS.Output): void => {
  // access minified.sourceMap as above
  console.log(minified.sourceMap);
});

new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']);

new CleanCSS().minify({
  'path/to/file/one': {
    styles: 'contents of file one'
  },
  'path/to/file/two': {
    styles: 'contents of file two'
  }
});

// new tests - promise resolution
new CleanCSS({ returnPromise: true, rebaseTo: pathToOutputDirectory }).minify(source)
    .then((minified: CleanCSS.Output): void => {
        console.log(minified.styles);
    }).catch((error: any): void => {
        console.log(error);
    }
);

new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source)
    .then((minified: CleanCSS.Output): void => {
        // access minified.sourceMap as above
        console.log(minified.sourceMap);
    }).catch((error: any): void => {
        console.log(error);
    }
);

new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source, inputSourceMapAsString)
    .then((minified: CleanCSS.Output): void => {
        // access minified.sourceMap as above
        console.log(minified.sourceMap);
    }).catch((error: any): void => {
        console.log(error);
    }
);

// test object return when passing options as object
let CleanCssOptions: CleanCSS.Options = { returnPromise: true };
new CleanCSS(CleanCssOptions).minify(source)
    .then((minified: CleanCSS.Output): void => {
        console.log(minified.styles);
    }).catch((error: any): void => {
        console.log(error);
    }
);

CleanCssOptions = { returnPromise: false };
new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => {
    console.log(minified.styles);
});

// test clean-css semicolonAfterLastProperty option works as expected
source = 'a{font-weight:bold;}';
CleanCssOptions = {
    format: {
        semicolonAfterLastProperty: true
    }
};

new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => {
    console.log(minified.styles);
});