text:
namespace thd {

namespace {
////////////////////////////////////////////////////////////////////////////////

std::unique_ptr<rpc::ByteArray> packInitMessage(
    const std::string& rank,
    const std::string& port
) {
  std::unique_ptr<rpc::ByteArray> arr_ptr(new rpc::ByteArray);

  arr_ptr.get()->append(std::string(rank + ";" + port).c_str(),
          rank.size() + 1 + port.size());

  return std::move(arr_ptr);
}

void unpackInitMessage(
    const char* msg,
    size_t length,
    int& rank,
    std::string& port
) {
  std::string data(msg, length);
  std::size_t separator = data.find(';');
  rank = std::stoi(data.substr(0, separator));
  port = data.substr(separator + 1, length);
}

void acceptInitConnection(
    asio::ip::tcp::acceptor& acceptor,
    asio::ip::tcp::socket& socket,
    asio::ip::tcp::endpoint& endpoint
) {
  asio::error_code ec;
  acceptor.accept(socket, endpoint, ec);
  asio::detail::throw_error(ec, "master failed to accept an initial "
      "connection");
}

asio::ip::basic_resolver_iterator<asio::ip::tcp> receiveInitMessage(
    asio::ip::tcp::resolver& resolver,
    asio::ip::tcp::socket& socket,
    const asio::ip::tcp::endpoint& endpoint,
    int& worker_rank
) {
  rpc::RPCMessage::size_type length;
  // Read the length of the incoming message.
  asio::read(socket, asio::buffer(&length, sizeof(length)));

  char* data = new char[length];
  // Read the incoming message.
  asio::read(socket, asio::buffer(data, length));

  std::string port;
  // Unpack the rank and the port to connec to from the message.
  unpackInitMessage(data, length, worker_rank, port);

  // Return an iterator to a list of endpoints to connect to.
  return resolver.resolve({endpoint.address().to_string(), port});
}

void sendMessage(
    std::unique_ptr<rpc::RPCMessage> msg,
    asio::ip::tcp::socket& socket
) {
  size_t length = msg.get()->bytes().length();
  asio::write(socket, asio::buffer(&length, sizeof(length)));
  asio::write(socket, asio::buffer(msg.get()->bytes().data(), length));
}

std::unique_ptr<rpc::RPCMessage> recvMessage(
    asio::ip::tcp::socket& socket
) {
  rpc::RPCMessage::size_type length;
  asio::read(socket, asio::buffer(&length, sizeof(length)));
  char* data = new char[length];
  asio::read(socket, asio::buffer(data, length));

  return std::unique_ptr<rpc::RPCMessage>(new rpc::RPCMessage(data, length));
}

const char* get_env(const char* env) {
  const char* value = std::getenv(env);
  if (value == nullptr) {
    throw std::logic_error(std::string("") + "failed to read the " + env +
        " environmental variable; maybe you forgot to set it properly?");
  }
  return value;
}

////////////////////////////////////////////////////////////////////////////////
} // anonymous namespace

MasterCommandChannel::MasterCommandChannel()
  : _io()
  , _rank(0)
{
  unsigned short init_port;
  _load_env(init_port, _world_size);

  _sockets.reserve(_world_size);
  for (int i = 0; i < _world_size; ++i)
    _sockets.emplace_back(_io);

  asio::ip::tcp::acceptor init_acceptor(_io,
      asio::ip::tcp::endpoint(asio::ip::tcp::v6(), init_port));
  asio::ip::tcp::resolver init_resolver(_io);
  asio::ip::tcp::socket init_socket(_io);

  for (int i = 1; i < _world_size; ++i) {
    asio::ip::tcp::endpoint worker_endpoint;
    acceptInitConnection(init_acceptor, init_socket, worker_endpoint);

    int worker_rank;
    auto final_endpoint = receiveInitMessage(init_resolver, init_socket,
        worker_endpoint, worker_rank);
    try {
      asio::connect(_sockets.at(worker_rank), final_endpoint);
    } catch (const asio::system_error& e) {
      throw std::runtime_error(std::string("") + "master failed to " +
          "establish the connection with worker " +
          std::to_string(worker_rank) + "; specifically: " + e.what());
    }
    init_socket.close();
  }
}

MasterCommandChannel::~MasterCommandChannel() {}

void MasterCommandChannel::sendMessage(
    std::unique_ptr<rpc::RPCMessage> msg,
    int rank
) {
  thd::sendMessage(std::move(msg), _sockets.at(rank));
}

std::unique_ptr<rpc::RPCMessage> MasterCommandChannel::recvMessage(int rank) {
  return thd::recvMessage(_sockets.at(rank));
}

void MasterCommandChannel::_load_env(unsigned short& port, int& world_size) {
  try {
    unsigned long value = std::stoul(get_env(MASTER_PORT_ENV));
    if (value > USHRT_MAX) {
      throw std::logic_error("the number representing the port is out of"
          "range");
    }
    port = value;
  } catch (const std::exception& e) {
    throw std::logic_error(std::string("") + "failed to convert the " +
        MASTER_PORT_ENV + " environmental variable to unsigned short (port "
        "number); specifically: " + e.what());
  }

  try {
    world_size = std::stoi(get_env(WORLD_SIZE_ENV));
  } catch (const std::exception& e) {
    throw std::logic_error(std::string("") + "failed to convert the " +
        WORLD_SIZE_ENV + " environmental variable to int: " + e.what());
  }
}

// XXX: asio::ip::address::from_string has been deprecated in favour of
//      asio::ip::address::make_address in v1.11.0. The version downloadable
//      with brew on macOS is v1.10.8.
WorkerCommandChannel::WorkerCommandChannel(int rank)
  : _rank(rank)
  , _io()
  , _socket(_io)
{
  asio::error_code ec;
  std::string master_ip_addr;
  unsigned short master_port;

  _load_env(master_ip_addr, master_port);

  asio::ip::tcp::acceptor init_acceptor(_io, asio::ip::tcp::endpoint(
        asio::ip::tcp::v6(), 0));

  asio::ip::tcp::resolver init_resolver(_io);
  asio::ip::tcp::resolver::query init_query(master_ip_addr,
      std::to_string(master_port),
      asio::ip::resolver_query_base::flags::v4_mapped |
      asio::ip::resolver_query_base::flags::numeric_service);
  auto init_endpoint = init_resolver.resolve(init_query);

  // Connect to the master.
  asio::ip::tcp::socket init_socket(_io);
  do {
    asio::connect(init_socket, init_endpoint, ec);
  } while (ec == asio::error::basic_errors::connection_refused);
	asio::detail::throw_error(ec, "failed to connect to master");

  // Get a local port.
  auto local_port = init_acceptor.local_endpoint(ec).port();
  asio::detail::throw_error(ec, "worker failed to get a local port");

  // Prepare the init message.
  auto arr = packInitMessage(std::to_string(_rank), std::to_string(local_port));

  // Send the init message.
  try {
    auto msg_length = arr.get()->length();
    asio::write(init_socket, asio::buffer(&msg_length, sizeof(msg_length)));
    asio::write(init_socket, asio::buffer(arr.get()->data(), msg_length));

    asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v6(), local_port);
    init_acceptor.accept(_socket, endpoint, ec);
    asio::detail::throw_error(ec, "worker failed to accept the connection from "
        "master");
  } catch (const std::exception& e) {
    throw std::runtime_error(std::string() + "unable to establish the " +
        "connection with master: " + e.what());
  }
}

WorkerCommandChannel::~WorkerCommandChannel() {}

void WorkerCommandChannel::sendMessage(std::unique_ptr<rpc::RPCMessage> msg) {
  thd::sendMessage(std::move(msg), _socket);
}

std::unique_ptr<rpc::RPCMessage> WorkerCommandChannel::recvMessage() {
  return thd::recvMessage(_socket);
}

void WorkerCommandChannel::_load_env(
    std::string& ip_addr,
    unsigned short& port
) {
  const std::string addr(get_env(MASTER_ADDR_ENV));
  auto separator_pos = addr.rfind(':');
  if (separator_pos == std::string::npos) {
    throw std::logic_error(std::string() + "failed to find the colon " +
        "separator (:) in the " + MASTER_ADDR_ENV + "environmental variable; " +
        "maybe you forgot to provide the port at all? " + MASTER_ADDR_ENV +
        "should be set to something like '127.0.0.1:12345'");
  }

  ip_addr = addr.substr(0, separator_pos);

  try {
    unsigned long value = std::stoul(addr.substr(separator_pos + 1));
    if (value > USHRT_MAX) {
      throw std::logic_error("the number representing the port is out of"
          "range");
    }
    port = value;
  } catch (const std::exception& e) {
    throw std::logic_error(std::string("") + "failed to convert the " +
        MASTER_PORT_ENV + " environmental variable to unsigned short (port "
        "number); specifically: " + e.what());
  }
}

} // namespace thd


text:
#ifndef __EXAMPLES_MOUNT_MOUNT_H
#define __EXAMPLES_MOUNT_MOUNT_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

/****************************************************************************
 * Definitions
 ****************************************************************************/

/* Configure the test */

#if defined(CONFIG_EXAMPLES_MOUNT_DEVNAME)
#  if !defined(CONFIG_FS_WRITABLE)
#    error "Writable filesystem required in this configuration"
#  endif
#  undef  CONFIG_EXAMPLES_MOUNT_NSECTORS
#  undef  CONFIG_EXAMPLES_MOUNT_SECTORSIZE
#  undef  CONFIG_EXAMPLES_MOUNT_RAMDEVNO
#  define MOUNT_DEVNAME CONFIG_EXAMPLES_MOUNT_DEVNAME
#else
#  if !defined(CONFIG_FS_FAT)
#    error "CONFIG_FS_FAT required in this configuration"
#  endif
#  if !defined(CONFIG_EXAMPLES_MOUNT_SECTORSIZE)
#    define CONFIG_EXAMPLES_MOUNT_SECTORSIZE 512
#  endif
#  if !defined(CONFIG_EXAMPLES_MOUNT_NSECTORS)
#    define CONFIG_EXAMPLES_MOUNT_NSECTORS   2048
#  endif
#  if !defined(CONFIG_EXAMPLES_MOUNT_RAMDEVNO)
#     define CONFIG_EXAMPLES_MOUNT_RAMDEVNO  0
#  endif
#  define STR_RAMDEVNO(m)    #m
#  define MKMOUNT_DEVNAME(m) "/dev/ram" STR_RAMDEVNO(m)
#  define MOUNT_DEVNAME      MKMOUNT_DEVNAME(CONFIG_EXAMPLES_MOUNT_RAMDEVNO)
#endif

/****************************************************************************
 * Public Types
 ****************************************************************************/

/****************************************************************************
 * Public Variables
 ****************************************************************************/

extern const char g_source[]; /* Mount 'source' path */

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#ifndef CONFIG_EXAMPLES_MOUNT_DEVNAME
extern int create_ramdisk(void);
#endif

#endif /* __EXAMPLES_MOUNT_MOUNT_H */

redpajama_set_name: RedPajamaGithub


text:
namespace llvm {

class MachineBasicBlock;

namespace AMDGPU {

bool laneDominates(MachineBasicBlock *MBBA, MachineBasicBlock *MBBB);

} // end namespace AMDGPU
} // end namespace llvm

#endif // LLVM_LIB_TARGET_AMDGPU_UTILS_AMDGPULANEDOMINATOR_H


text:
module RuboCop
  module Cop
    module Style
      # This cop checks for RuntimeError as the argument of raise/fail.
      #
      # It checks for code like this:
      #
      # @example
      #   # Bad
      #   raise RuntimeError, 'message'
      #
      #   # Bad
      #   raise RuntimeError.new('message')
      #
      #   # Good
      #   raise 'message'
      class RedundantException < Cop
        MSG_1 = 'Redundant `RuntimeError` argument can be removed.'
        MSG_2 = 'Redundant `RuntimeError.new` call can be replaced with ' \
                'just the message.'

        def on_send(node)
          exploded?(node) { return add_offense(node, message: MSG_1) }
          compact?(node) { add_offense(node, message: MSG_2) }
        end

        # Switch `raise RuntimeError, 'message'` to `raise 'message'`, and
        # `raise RuntimeError.new('message')` to `raise 'message'`.
        def autocorrect(node) # rubocop:disable Metrics/MethodLength
          exploded?(node) do |command, message|
            return lambda do |corrector|
              if node.parenthesized?
                corrector.replace(node.source_range,
                                  "#{command}(#{message.source})")
              else
                corrector.replace(node.source_range,
                                  "#{command} #{message.source}")
              end
            end
          end
          compact?(node) do |new_call, message|
            lambda do |corrector|
              corrector.replace(new_call.source_range, message.source)
            end
          end
        end

        def_node_matcher :exploded?, <<-PATTERN
          (send nil? ${:raise :fail} (const nil? :RuntimeError) $_)
        PATTERN

        def_node_matcher :compact?, <<-PATTERN
          (send nil? {:raise :fail} $(send (const nil? :RuntimeError) :new $_))
        PATTERN
      end
    end
  end
end


text:
import React from 'react';
import PropTypes from 'prop-types';
import get from 'lodash.get';

const styles = {
    list: {
        display: 'flex',
        listStyleType: 'none',
    },
    image: {
        margin: '0.5rem',
        maxHeight: '10rem',
    },
};

export const ImageField = ({ elStyle = {}, record, source, src, title }) => {
    const sourceValue = get(record, source);
    if (!sourceValue) {
        return
;
    }

    if (Array.isArray(sourceValue)) {
        const style = {
            ...styles.list,
            ...elStyle,
        };
        return (

                {sourceValue.map((file, index) => {
                    const titleValue = get(file, title) || title;
                    const srcValue = get(file, src) || title;

                    return (

                    );
                })}

        );
    }

    const titleValue = get(record, title) || title;

    return (

    );
};

ImageField.propTypes = {
    elStyle: PropTypes.object,
    record: PropTypes.object,
    source: PropTypes.string.isRequired,
    title: PropTypes.string,
};

export default ImageField;


text:
// @license
// Redistribution and use in source and binary forms ...

"use strict";

//
// VERIFY NAMESPACE
//

// Create the global symbol "org" if it doesn't exist.  Throw an error if it does exist but is not an object.
var org;
if (!org) {
  org = {};
} else {
  if ( typeof org != "object") {
    var orgExistsMessage = "Error: failed to create org namespace: org already exists and is not an object";
    alert(orgExistsMessage);
    throw new Error(orgExistsMessage);
  }
}

// Repeat the creation and type-checking for the next level
if (!org.gigapan) {
  org.gigapan = {};
} else {
  if ( typeof org.gigapan != "object") {
    var orgGigapanExistsMessage = "Error: failed to create org.gigapan namespace: org.gigapan already exists and is not an object";
    alert(orgGigapanExistsMessage);
    throw new Error(orgGigapanExistsMessage);
  }
}

// Repeat the creation and type-checking for the next level
if (!org.gigapan.timelapse) {
  org.gigapan.timelapse = {};
} else {
  if ( typeof org.gigapan.timelapse != "object") {
    var orgGigapanTimelapseExistsMessage = "Error: failed to create org.gigapan.timelapse namespace: org.gigapan.timelapse already exists and is not an object";
    alert(orgGigapanTimelapseExistsMessage);
    throw new Error(orgGigapanTimelapseExistsMessage);
  }
}

//
// DEPENDENCIES
//
if (!org.gigapan.timelapse.Timelapse) {
  var noTimelapseMsg = "The org.gigapan.timelapse.Timelapse library is required by org.gigapan.timelapse.CustomUI";
  alert(noTimelapseMsg);
  throw new Error(noTimelapseMsg);
}

//
// CODE
//
(function() {
  var UTIL = org.gigapan.Util;
  org.gigapan.timelapse.CustomUI = function(timelapse, settings) {
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Class variables
    //
    var datasetType = timelapse.getDatasetType();
    var timeMachineDivId = timelapse.getTimeMachineDivId();
    var viewerDivId = timelapse.getViewerDivId();
    var $viewer = $("#" + viewerDivId);
    var viewer_offset = $viewer.offset();
    var $video = $("#" + viewerDivId + " .tiledContentHolder");
    var playerWidth = $video.outerWidth();
    var $customControl;
    var $customPlay;
    var $customHelpLabel;
    var $customTimeline;
    var $timeText;
    var $timeTextLeft;
    var $timeTextRight;
    var $currentTimeTick;
    var $fastSpeed;
    var $mediumSpeed;
    var $slowSpeed;
    var $timeTextHover;
    var videoset = timelapse.getVideoset();
    var captureTimes = timelapse.getCaptureTimes();
    var numFrames = timelapse.getNumFrames();
    var timeTickX = [];
    var $defaultUIPlaybackButton = $("#" + viewerDivId + " .playbackButton");
    var numYears;
    var pixelRatio = getPixelRatio();
    var endFrameIdx = numFrames - 1;
    var extraHeight = 2;
    var $customSpeedhelp;

    // Modis dataset variables
    var $monthSpinnerContainer;
    var $monthSpinner;
    var $monthSpinnerTxt;
    var previousEffectiveSpinnerValue = 0;
    var previousSpinnerValue = 0;
    var locker = "none";
    var yearLockMinPlaybackFrame;
    var yearLockMaxPlaybackFrame;
    var yearDictionary = {};
    var frameDictionary = [];
    var firstYear;
    var endYear;
    var isPlaying = !timelapse.isPaused();
    var $noLock;
    var $withLock;
    var monthLockPlaybackFrames = [];
    var monthLockPlaybackInterval;
    var monthLockPlaybackIdx = 0;
    var monthLockPlaybackSpeed;
    var fps = timelapse.getFps();
    var firstYearFrameOffset;
    var spinnerRadius = 110;
    var endTimeDot_radius = 4;
    var endTimeDotGrow_radius = 8;
    var $endTimeDot;
    var spinnerCircleOffset1 = 8;
    var spinnerCircleOffset2 = 9;
    var spinnerAngleArc = 273;
    var spinnerAngleOffset = -47;
    var maxYearNumFrames;

    // In px.
    var sliderLeftMargin;
    var sliderRightMargin;

    var isShowHoverEffect = true;
    var useTouchFriendlyUI = timelapse.useTouchFriendlyUI();
    var timeTick_width = 2;
    var timeTick_height = useTouchFriendlyUI ? 21 : 15;
    var currentTimeTick_width = useTouchFriendlyUI ? 15 : 10;
    var currentTimeTick_height = useTouchFriendlyUI ? 43 : 31;
    var timeTickGrow_width = 2;
    var timeTickGrow_height = currentTimeTick_height;
    var originalIsPaused;
    var isSafari = org.gigapan.Util.isSafari();
    var editorEnabled = timelapse.isEditorEnabled();
    var timeTickSpan;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Private methods
    //
    var preProcessLandsat = function() {
      for (var i = 0; i < captureTimes.length; i++) {
        var year = captureTimes[i];
        frameDictionary[i] = {
          "x": undefined,
          "year": year
        };
        if (firstYear == undefined)
          firstYear = year;
        if (i == captureTimes.length - 1)
          endYear = year;
        if (yearDictionary[year] == undefined) {
          yearDictionary[year] = {
            "numFramesThisYear": 0,
            "currentStackEndIdx": i,
            "previousStackEndIdx": i - 1
          };
        }
        yearDictionary[year]["numFramesThisYear"]++;
      }
      numYears = numFrames;
    };

    var preProcessModis = function() {
      var year, month;
      for (var i = 0; i < captureTimes.length; i++) {
        var time = captureTimes[i].split(" ");
        var timeStart = time[0].split("-").map(parseFloat);
        var originalCaptureTime = new Date(timeStart[0], timeStart[1] - 1, timeStart[2]).toUTCString();
        originalCaptureTime = originalCaptureTime.split(",");
        originalCaptureTime = originalCaptureTime[1].split(" ");
        year = timeStart[0];
        month = timeStart[1];
        if (firstYear == undefined)
          firstYear = year;
        if (i == captureTimes.length - 1)
          endYear = year;
        if (yearDictionary[year] == undefined) {
          yearDictionary[year] = {
            "numFramesThisYear": 0,
            "currentStackEndIdx": -1,
            "previousStackEndIdx": -1,
            "maxSpinnerValue": -1,
            "minSpinnerValue": 0
          };
          if (yearDictionary[year - 1]) {
            yearDictionary[year]["currentStackEndIdx"] = yearDictionary[year - 1]["currentStackEndIdx"];
            yearDictionary[year]["previousStackEndIdx"] = yearDictionary[year - 1]["currentStackEndIdx"];
          }
        }
        yearDictionary[year][month] = yearDictionary[year]["numFramesThisYear"];
        frameDictionary[i] = {
          "x": undefined,
          "year": year,
          "monthFrameIdx": yearDictionary[year][month],
          "monthText": originalCaptureTime[2]
        };
        yearDictionary[year]["numFramesThisYear"]++;
        yearDictionary[year]["maxSpinnerValue"]++;
        yearDictionary[year]["currentStackEndIdx"]++;
        yearDictionary[year][month]++;
      }
      numYears = Object.keys(yearDictionary).length;
      // The first year is a special case that contains less frames than other years.
      // We need this variable to correctly seek to a desired time.
      // If there are more special cases, you need more special offset variables.
      maxYearNumFrames = yearDictionary[firstYear + 1]["numFramesThisYear"];
      firstYearFrameOffset = maxYearNumFrames - yearDictionary[firstYear]["numFramesThisYear"];
      for (var i = yearDictionary[firstYear]["minSpinnerValue"]; i <= yearDictionary[firstYear]["maxSpinnerValue"]; i++)
        frameDictionary[i]["monthFrameIdx"] += firstYearFrameOffset;
      yearDictionary[firstYear]["minSpinnerValue"] += firstYearFrameOffset;
      yearDictionary[firstYear]["maxSpinnerValue"] += firstYearFrameOffset;
      previousEffectiveSpinnerValue = yearDictionary[firstYear]["minSpinnerValue"];
      previousSpinnerValue = previousEffectiveSpinnerValue;
    };

    var createCustomControl = function() {
      if (useTouchFriendlyUI)
        $video.addClass("tiledContentHolder-touchFriendly");

      $customControl = $('

');
      // Append element
      $viewer.append($customControl);
      // Create google logo
      $customControl.append('

');
      if (useTouchFriendlyUI)
        $(".googleLogo").addClass("googleLogo-touchFriendly");
      // Create the spinner for months
      if (datasetType == "modis")
        createMonthSpinner();
      // Create timeline toolbar
      createCustomButtons();
      // Create timeline slider
      createCustomTimeline();

      if (datasetType == "modis") {
        timelapse.addTimeChangeListener(function() {
          if (locker == "year") {
            var currentFrame = timelapse.getCurrentFrameNumber();
            if (currentFrame >= numFrames - 2) {
              // If current time passes the end frame
              if (isPlaying) {
                timelapse.seekToFrame(yearLockMinPlaybackFrame);
                timelapse.play();
                $customPlay.button({
                  icons: {
                    primary: "ui-icon-custom-pause"
                  },
                  text: false
                }).attr({
                  "title": "Pause"
                });
                return;
              }
            } else if (currentFrame >= yearLockMaxPlaybackFrame) {
              if (timelapse.isPaused() == false)
                timelapse.seekToFrame(yearLockMinPlaybackFrame);
            } else if (currentFrame < yearLockMinPlaybackFrame)
              timelapse.seekToFrame(yearLockMinPlaybackFrame);
          }
        });
        timelapse.addVideoPlayListener(function() {
          if (locker == "year") {
            var currentYear = getCurrentYear();
            yearLockMinPlaybackFrame = yearDictionary[currentYear]["previousStackEndIdx"] + 1;
            yearLockMaxPlaybackFrame = yearDictionary[currentYear]["currentStackEndIdx"];
          }
        });
      }
    };

    var createMonthSpinner = function() {
      $monthSpinnerContainer = $('

');
      $monthSpinner = $('<input class="monthSpinner" data-width="' + spinnerRadius + '" data-height="' + spinnerRadius + '">');
      $monthSpinnerTxt = $('

');
      $monthSpinnerContainer.append($monthSpinner);
      $monthSpinnerContainer.append($monthSpinnerTxt);
      $customControl.append($monthSpinnerContainer);
      $monthSpinner.knob({
        min: 0,
        max: maxYearNumFrames - 1,
        fgColor: "#707070",
        bgColor: "#ffffff",
        thickness: 0.27,
        cursor: 15,
        width: spinnerRadius,
        height: spinnerRadius,
        displayInput: false,
        angleArc: spinnerAngleArc,
        angleOffset: spinnerAngleOffset,
        stopper: false,
        change: function(value) {
          var currentYear = getCurrentYear();
          var minSpinnerValue = yearDictionary[currentYear]["minSpinnerValue"];
          var maxSpinnerValue = yearDictionary[currentYear]["maxSpinnerValue"];
          if (previousSpinnerValue > maxYearNumFrames - 1) {
            if (value == 0) {
              seekToFrame(value, "year", 1);
              return false;
            } else if (value == maxYearNumFrames - 1) {
              seekToFrame(value, "year", -1);
              return false;
            }
          }
          previousSpinnerValue = value;
          if (value > maxSpinnerValue || value < minSpinnerValue) {
            if (previousEffectiveSpinnerValue >= minSpinnerValue && previousEffectiveSpinnerValue <= (maxSpinnerValue + minSpinnerValue) / 2)
              $monthSpinner.val(minSpinnerValue).trigger("change");
            else if (previousEffectiveSpinnerValue > (maxSpinnerValue + minSpinnerValue) / 2 && previousEffectiveSpinnerValue <= maxSpinnerValue)
              $monthSpinner.val(maxSpinnerValue).trigger("change");
            return false;
          } else {
            previousEffectiveSpinnerValue = value;
            seekToFrame(value, "year");
          }
        },
        release: function(value) {
          if (!originalIsPaused)
            timelapse.handlePlayPause();
          if (locker == "month" && isPlaying)
            playMonthLockFrames();
        },
        draw: function() {
          var angleOffset = 0.14;
          // Angle
          var a = this.angle(this.cv);
          // Start angle
          var sat = this.startAngle - angleOffset;
          // End angle
          var eat = sat + a - angleOffset;
          var offset = 4;

          // Background
          this.g.save();
          this.g.lineWidth = 2;
          this.g.fillStyle = this.o.bgColor;
          this.g.strokeStyle = "#656565";
          this.g.shadowOffsetX = 1;
          this.g.shadowOffsetY = 1;
          this.g.shadowBlur = 5;
          this.g.shadowColor = "rgba(0, 0, 0, 0.5)";
          this.g.beginPath();
          // The first arc() fills the area, and the second arc() substracts out the center area to make the circle hollow.
          this.g.arc(this.xy, this.xy, this.radius + this.lineWidth / 2 - offset - spinnerCircleOffset1 * pixelRatio, 1.2 * Math.PI, 0.8 * Math.PI, false);
          this.g.arc(this.xy, this.xy, this.radius - this.lineWidth / 2 - offset + spinnerCircleOffset2 * pixelRatio, 0.8 * Math.PI, 1.2 * Math.PI, true);
          this.g.stroke();
          this.g.fill();
          this.g.restore();

          // Cursor shadow
          this.g.save();
          this.o.cursor && ( sat = eat - this.cursorExt) && ( eat = eat + this.cursorExt);
          this.g.lineWidth = this.lineWidth + 2;
          this.g.globalAlpha = 0.4;
          this.g.beginPath();
          this.g.strokeStyle = "#656565";
          this.g.arc(this.xy, this.xy, this.radius - offset + 2, sat + 0.25, eat + 0.37, false);
          this.g.stroke();
          this.g.restore();

          // Cursor border
          this.o.cursor && ( sat = eat - this.cursorExt) && ( eat = eat + this.cursorExt);
          this.g.lineWidth = this.lineWidth + 2;
          this.g.beginPath();
          this.g.strokeStyle = "#656565";
          this.g.arc(this.xy, this.xy, this.radius - offset + 1, sat + 0.13, eat + 0.18, false);
          this.g.stroke();

          // Cursor background
          this.o.cursor && ( sat = eat - this.cursorExt) && ( eat = eat + this.cursorExt);
          this.g.lineWidth = this.lineWidth;
          this.g.beginPath();
          this.g.strokeStyle = this.o.bgColor;
          this.g.arc(this.xy, this.xy, this.radius - offset + 1, sat, eat, false);
          this.g.stroke();
          /*
           // Inner border
           this.g.lineWidth = 1;
           this.g.beginPath();
           this.g.strokeStyle = "#656565";
           this.g.arc(this.xy, this.xy, this.radius - this.lineWidth / 2 - offset - 3, 0, 2 * Math.PI, false);
           this.g.stroke();*/
          /*
           // Outer border
           this.g.lineWidth = 2;
           this.g.beginPath();
           this.g.strokeStyle = this.o.bgColor;
           this.g.arc(this.xy, this.xy, this.radius + this.lineWidth / 2 - offset + 3, 0, 2 * Math.PI, false);
           this.g.stroke();
           */
          return false;
        }
      }).on("mousedown", function() {
        originalIsPaused = timelapse.isPaused();
        if (!originalIsPaused)
          timelapse.handlePlayPause();
        if (locker == "month" && isPlaying)
          stopMonthLockFrames();
      });

      // Handle mouse leave iframe
      $monthSpinnerContainer.bind("mousedown", function() {
        if (window && (window.self !== window.top)) {
          $("body").one("mouseleave", function(event) {
            $monthSpinnerContainer.trigger("mouseup");
          });
        }
      });
    };

    function getPixelRatio() {
      var ctx = document.createElement("canvas").getContext("2d");
      // This is the pixel density of the device
      var dpr = window.devicePixelRatio || 1;
      // This is the pixel density of the canvas
      var bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backignStorePixelRatio || 1;
      return dpr / bsr;
    }

    var createSpeedControl = function() {
      // Toggle speed
      $fastSpeed = $('<button class="customToggleSpeed" title="Toggle playback speed">Fast</button>');
      $mediumSpeed = $('<button class="customToggleSpeed" title="Toggle playback speed">Medium</button>');
      $slowSpeed = $('<button class="customToggleSpeed" title="Toggle playback speed">Slow</button>');

      if (datasetType == "modis") {
        $fastSpeed.toggleClass("customToggleSpeed modisCustomToggleSpeed");
        $mediumSpeed.toggleClass("customToggleSpeed modisCustomToggleSpeed");
        $slowSpeed.toggleClass("customToggleSpeed modisCustomToggleSpeed");
      }

      var speedOptions = [$slowSpeed, $fastSpeed, $mediumSpeed];
      // Speeds < 0.5x in Safari, even if emulated, result in broken playback, so do not include the "slow" (0.25x) speed option
      if (isSafari)
        speedOptions.shift();

      $customControl.prepend(speedOptions);

      if (useTouchFriendlyUI) {
        $(".customToggleSpeed").addClass("customToggleSpeed-touchFriendly");
      }

      $fastSpeed.button({
        text: true
      }).click(function() {
        timelapse.setPlaybackRate(0.5, null, true);
        $customControl.prepend($mediumSpeed);
        $mediumSpeed.stop(true, true).show();
        $fastSpeed.slideUp(300);
        if (locker == "month" && isPlaying)
          playMonthLockFrames();
        UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-set-speed-to-medium');
      });

      $mediumSpeed.button({
        text: true
      }).click(function() {
        // Due to playback issues, we are not allowing the "slow" option for Safari users
        if (isSafari) {
          timelapse.setPlaybackRate(1, null, true);
          $customControl.prepend($fastSpeed);
          $fastSpeed.stop(true, true).show();
          UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-set-speed-to-fast');
        } else {
          timelapse.setPlaybackRate(0.25, null, true);
          $customControl.prepend($slowSpeed);
          $slowSpeed.stop(true, true).show();
          UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-set-speed-to-slow');
        }
        $mediumSpeed.slideUp(300);
        if (locker == "month" && isPlaying)
          playMonthLockFrames();
      });

      $slowSpeed.button({
        text: true
      }).click(function() {
        timelapse.setPlaybackRate(1, null, true);
        $customControl.prepend($fastSpeed);
        $fastSpeed.stop(true, true).show();
        $slowSpeed.slideUp(300);
        if (locker == "month" && isPlaying)
          playMonthLockFrames();
        UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-set-speed-to-fast');
      });

      timelapse.addPlaybackRateChangeListener(function(rate, skipUpdateUI) {
        if (!skipUpdateUI) {
          var snaplapse = timelapse.getSnaplapse();
          var snaplapseForSharedTour = timelapse.getSnaplapseForSharedTour();
          if ((snaplapse && snaplapse.isPlaying()) || (snaplapseForSharedTour && snaplapseForSharedTour.isPlaying()))
            return;
          $("#" + viewerDivId + " .customToggleSpeed").hide();
          if (rate >= 1) {
            $fastSpeed.show();
            $mediumSpeed.hide();
            $slowSpeed.hide();
          } else if ((rate < 1 && rate >= 0.5) || (isSafari && rate < 0.5)) {
            $mediumSpeed.show();
            $fastSpeed.hide();
            $slowSpeed.hide();
          } else {
            $slowSpeed.show();
            $mediumSpeed.hide();
            $fastSpeed.hide();
          }
        }
      });

      // Since the call to set the playback rate when first creating the timelapse
      // happens before the UI is setup, we need to run it again below to properly
      // update the UI.
      var playbackRate = timelapse.getPlaybackRate();
      if (playbackRate >= 1) {
        $fastSpeed.show();
      } else if (playbackRate < 1 && playbackRate >= 0.5) {
        $mediumSpeed.show();
      } else {
        $slowSpeed.show();
      }
    };

    var setLocker = function(lockType, status) {
      if (lockType == "year") {
        if (status == "enable") {
          locker = "year";
          timelapse.setLoopPlayback(false, true);
          var currentYear = getCurrentYear();
          yearLockMinPlaybackFrame = yearDictionary[currentYear]["previousStackEndIdx"] + 1;
          yearLockMaxPlaybackFrame = yearDictionary[currentYear]["currentStackEndIdx"];
        } else if (status == "disable") {
          locker = "none";
          timelapse.restoreLoopPlayback();
        }
      } else if (lockType == "month") {
        if (status == "enable") {
          locker = "month";
          if (isPlaying) {
            timelapse.pause();
            updateMonthLockPlaybackInterval();
          }
        } else if (status == "disable") {
          locker = "none";
          if (isPlaying) {
            clearTimeout(monthLockPlaybackInterval);
            monthLockPlaybackInterval = null;
            timelapse.play();
          }
        }
      }
    };

    // Gets a safe MODIS month lock value (String) from an unsafe object containing key-value pairs from the URL hash.
    var getModisLockFromHash = function(unsafeHashObj) {
      if (unsafeHashObj && unsafeHashObj.l) {
        var newMonthLock = String(unsafeHashObj.l);
        return newMonthLock;
      }
      return null;
    };

    var createLockControl = function() {
      $noLock = $('<button class="toggleLock" id="noLock" title="Click to lock playback to month">None</button>');
      $withLock = $('<button class="toggleLock" id="withLock" title="Playback locked to month, click to unlock">None</button>');
      var lockOptions = [$noLock, $withLock];
      $customControl.prepend(lockOptions);

      $noLock.button({
        icons: {
          primary: "ui-icon-unlocked"
        },
        text: false
      }).click(function() {
        setLocker("month", "enable");
        $customControl.prepend($withLock);
        $withLock.stop(true, true).slideDown();
        $noLock.slideUp(300);
        UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-enable-month-lock');
      });

      $withLock.button({
        icons: {
          primary: "ui-icon-locked"
        },
        text: false
      }).click(function() {
        setLocker("month", "disable");
        $customControl.prepend($noLock);
        $noLock.stop(true, true).slideDown();
        $withLock.slideUp(300);
        UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-disable-month-lock');
      });

      var unsafeHashObj = UTIL.getUnsafeHashVars();
      var modisLock = getModisLockFromHash(unsafeHashObj);
      if (modisLock == "month")
        $withLock.show();
      else
        $noLock.show();
    };

    var createCustomButtons = function() {
      createSpeedControl();

      if (datasetType == "modis")
        createLockControl();

      // Instruction mask
      var content_instruction = "";
      content_instruction += '
';
      content_instruction += '
'
      content_instruction += useTouchFriendlyUI ? 'Zoom in and out to explore in greater detail.' : 'Zoom in and out to explore in greater detail. Click or use the mouse scroll wheel.';
      content_instruction += '
';
      content_instruction += '
';
      content_instruction += useTouchFriendlyUI ? 'Drag or pinch to explore in greater detail.' : 'Click and drag to explore.';
      content_instruction += '
';
      content_instruction += '
';
      content_instruction += useTouchFriendlyUI ? 'Tap to toggle the playback speed.' : 'Click to toggle the playback speed.';
      content_instruction += '
';
      content_instruction += '
';
      $viewer.append(content_instruction);
      $customSpeedhelp = $("#" + viewerDivId + " .customSpeedhelp");
      if (datasetType == "modis")
        $customSpeedhelp.toggleClass("customSpeedhelp modisCustomSpeedhelp");

      // Play and stop button
      $customControl.append('<button class="customPlay" title="Play"></button>');

      if (useTouchFriendlyUI) {
        $(".customPlay").addClass("customPlay-touchFriendly");
        $(".customInstructions").addClass("customInstructions-touchFriendly");
      }

      $customPlay = $("#" + viewerDivId + " .customPlay");
      $customPlay.button({
        icons: {
          primary: "ui-icon-custom-play"
        },
        text: false
      }).click(function() {
        if ($defaultUIPlaybackButton.hasClass("from_help"))
          return;
        if (locker == "month")
          handleMonthLockFramesPlayPause();
        else
          timelapse.handlePlayPause();
        isPlaying = !isPlaying;
        if (isPlaying)
          UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-play');
        else
          UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-pause');
      });
      if (datasetType == "modis")
        $customPlay.toggleClass("customPlay modisCustomPlay");

      // Help button
      $customControl.append('<input type="checkbox" class="customHelpCheckbox"/>');
      $customControl.append('');

      if (useTouchFriendlyUI) {
        $(".customHelpLabel").addClass("customHelpLabel-touchFriendly");
      }

      var $customHelpCheckbox = $("#" + viewerDivId + " .customHelpCheckbox");
      $customHelpCheckbox.attr("id", timeMachineDivId + "_customHelpCheckbox");
      $customHelpLabel = $("#" + viewerDivId + " .customHelpLabel");
      $customHelpLabel.attr("for", timeMachineDivId + "_customHelpCheckbox");
      $customHelpCheckbox.button({
        icons: {
          primary: useTouchFriendlyUI ? "ui-icon-custom-help" : "ui-icon-help"
        },
        text: false
      }).change(function() {
        if ($customHelpCheckbox.is(":checked")) {
          doCustomHelpOverlay();
          $(document).one("mouseup", function(e) {
            if ($("#" + viewerDivId + " .customHelpCheckbox").has(e.target).length == 0)
              $customHelpCheckbox.prop("checked", false).button("refresh").change();
          });
          UTIL.addGoogleAnalyticEvent('button', 'click', 'viewer-show-help');
        } else {
          removeCustomHelpOverlay();
        }
      });
    };

    var createCustomTimeline = function() {
      // Create slider container
      $timeText = $('

');
      if (datasetType == "modis")
        $timeText.toggleClass("timeText modisTimeText");
      $customTimeline = $('

');
      $customControl.append($timeText, $customTimeline);
      if (useTouchFriendlyUI) {
        $(".customTimeline").addClass("customTimeline-touchFriendly");
        $(".timeText").addClass("timeText-touchFriendly");
      }
      var extraSliderLeftMargin = (datasetType == "landsat") ? 50 : 60;
      sliderLeftMargin = $customPlay.width() + $timeText.width() + extraSliderLeftMargin;
      var extraSliderRightMargin;
      if (datasetType == "landsat") {
        if (settings["isHyperwall"] && fields.fullControls != "true")
          extraSliderRightMargin = 5;
        else
          extraSliderRightMargin = 35;
      } else
        extraSliderRightMargin = 40;
      sliderRightMargin = $customHelpLabel.width() + extraSliderRightMargin;
      $customTimeline.css({
        "left": sliderLeftMargin + "px",
        "right": sliderRightMargin + "px"
      });

      // Create left, right, and hover date text
      $timeTextLeft = $('

');
      $timeTextRight = $('

');
      $timeTextHover = $('

');
      $customTimeline.append($timeTextLeft, $timeTextRight, $timeTextHover);

      // Create current time bar
      $currentTimeTick = $('

');
      $customTimeline.append($currentTimeTick);
      $currentTimeTick.css({
        "top": "0px",
        "left": "0px",
        "width": currentTimeTick_width + "px",
        "height": currentTimeTick_height + "px",
        "margin-left": (currentTimeTick_width / -2) + "px"
      });

      // Create time tick
      // Calculate the space between time ticks
      var numTicks = numYears;
      if (datasetType == "modis")
        numTicks = numTicks + 1;
      timeTickSpan = 100 / numTicks;
      var previousTargetFrameIdx = undefined;
      var targetFrame, targetFrameX, previousTargetFrameX, invisibleSpan;
      for (var i = 0; i < numYears; i++) {
        targetFrame = yearDictionary[captureTimes[i]]["previousStackEndIdx"] + 1;
        // Save the x position of every frame
        frameDictionary[targetFrame]["x"] = timeTickSpan * (i + 0.5);
        // Save the x position of every time tick
        timeTickX[i] = timeTickSpan * (i + 0.5);
        // In Landsat, frameDictionary and timeTickX are the same.
        // In MODIS, they are different. So we need to compute frameDictionary.
        if (previousTargetFrameIdx != undefined && datasetType == "modis") {
          targetFrameX = frameDictionary[targetFrame]["x"];
          previousTargetFrameX = frameDictionary[previousTargetFrameIdx]["x"];
          invisibleSpan = (targetFrameX - previousTargetFrameX) / (targetFrame - previousTargetFrameIdx);
          for (var j = previousTargetFrameIdx + 1; j < targetFrame; j++)
            frameDictionary[j]["x"] = frameDictionary[j - 1]["x"] + invisibleSpan;
        }
        previousTargetFrameIdx = targetFrame;
        var $timeTick = $('

');
        var $timeTickContainer = $('

');
        var $timeTickClickRegion = $('

');
        $timeTickContainer.css({
          "top": "0px",
          "left": (timeTickSpan * i) + "%",
          "width": timeTickSpan + "%",
          "height": currentTimeTick_height + 28 + "px"
        });
        $timeTickClickRegion.css({
          "top": "0px",
          "left": "0px",
          "width": "100%",
          "height": "100%"
        }).attr("tabindex", i);
        $timeTick.css({
          "margin-top": ((currentTimeTick_height - timeTick_height) / 2) + "px",
          "width": timeTick_width + "px",
          "height": timeTick_height + "px"
        });
        $timeTickContainer.on("mouseenter", handleTimeTickMouseover).on("mouseleave", handleTimeTickMouseout).on("mousedown", handleTimeTickMousedown);
        $timeTickContainer.append($timeTick, $timeTickClickRegion);
        $customTimeline.append($timeTickContainer);
      }
      // This part is used for creating the dot showing the final frame
      if (datasetType == "modis") {
        frameDictionary[endFrameIdx]["x"] = timeTickSpan * (numYears + 0.5);
        var endFrameX = frameDictionary[endFrameIdx]["x"];
        previousTargetFrameX = frameDictionary[previousTargetFrameIdx]["x"];
        invisibleSpan = (endFrameX - previousTargetFrameX) / (endFrameIdx - previousTargetFrameIdx);
        for (var j = previousTargetFrameIdx + 1; j < endFrameIdx; j++)
          frameDictionary[j]["x"] = frameDictionary[j - 1]["x"] + invisibleSpan;
        var $endTimeDotContainer = $('

');
        var $endTimeDotClickRegion = $('

');
        $endTimeDot = $('

');
        $endTimeDotContainer.css({
          "top": "0px",
          "left": (timeTickSpan * numYears) + "%",
          "width": timeTickSpan + "%",
          "height": currentTimeTick_height + 28 + "px"
        });
        $endTimeDotClickRegion.css({
          "top": "0px",
          "left": "0px",
          "width": "100%",
          "height": "100%"
        }).attr("tabindex", i);
        $endTimeDot.css({
          "margin-top": ((currentTimeTick_height / 2) - (endTimeDot_radius / 2)) + "px",
          "width": endTimeDot_radius + "px",
          "height": endTimeDot_radius + "px",
          "border-radius": (endTimeDot_radius / 2) + "px"
        });
        $endTimeDotContainer.on("mouseenter", handleEndTimeDotMouseover).on("mouseleave", handleEndTimeDotMouseout).on("mousedown", handleEndTimeDotMousedown);
        $endTimeDotContainer.append($endTimeDot, $endTimeDotClickRegion);
        $customTimeline.append($endTimeDotContainer);
      }
      var firstFrameForFirstYear = frameDictionary[0];
      $timeTextLeft.text(firstFrameForFirstYear["year"]).css({
        "left": firstFrameForFirstYear["x"] + "%",
        "top": currentTimeTick_height + (useTouchFriendlyUI ? 8 : 5) + "px",
        "margin-left": ($timeTextLeft.width() / -2) + "px"
      });
      var firstFrameForEndYear = frameDictionary[yearDictionary[endYear]["previousStackEndIdx"] + 1];
      $timeTextRight.text(firstFrameForEndYear["year"]).css({
        "left": firstFrameForEndYear["x"] + "%",
        "top": currentTimeTick_height + (useTouchFriendlyUI ? 8 : 5) + "px",
        "margin-left": ($timeTextRight.width() / -2) + "px"
      });
      $timeTextHover.text(firstFrameForFirstYear["year"]).css({
        "left": "50%",
        "top": currentTimeTick_height + (useTouchFriendlyUI ? 8 : 5) + "px",
        "margin-left": ($timeTextHover.width() / -2) + "px"
      });
      videoset.addEventListener('sync', function() {
        updateTimelineSlider(timelapse.getCurrentFrameNumber());
      });
      updateTimelineSlider(0);
    };

    var handleEndTimeDotMousedown = function(event) {
      originalIsPaused = timelapse.isPaused();
      if (!originalIsPaused)
        timelapse.handlePlayPause();
      if (locker != "month")
        seekToFrame(endFrameIdx, locker);
      else {
        if (isPlaying)
          stopMonthLockFrames();
      }
      isShowHoverEffect = false;
      // Track mouse
      $viewer.on("mousemove", trackMouseAndSlide);
      $(document).one("mouseup", function(event) {
        if (!originalIsPaused)
          timelapse.handlePlayPause();
        if (locker == "month" && isPlaying)
          playMonthLockFrames();
        $viewer.off("mousemove", trackMouseAndSlide);
        isShowHoverEffect = true;
      });
    };

    var handleEndTimeDotMouseover = function(event) {
      if (isShowHoverEffect) {
        $endTimeDot.stop(true, true).animate({
          "margin-top": ((currentTimeTick_height / 2) - (endTimeDotGrow_radius / 2)) + "px",
          "width": endTimeDotGrow_radius + "px",
          "height": endTimeDotGrow_radius + "px"
        }, {
          duration: 100
        });
      }
    };

    var handleEndTimeDotMouseout = function(event) {
      $endTimeDot.stop(true, true).animate({
        "margin-top": ((currentTimeTick_height / 2) - (endTimeDot_radius / 2)) + "px",
        "width": endTimeDot_radius + "px",
        "height": endTimeDot_radius + "px"
      }, {
        duration: 50
      });
    };

    var handleTimeTickMousedown = function(event) {
      originalIsPaused = timelapse.isPaused();
      if (!originalIsPaused)
        timelapse.handlePlayPause();
      var currentYearIdx = parseInt(this.id.split("_")[3]);
      var currentYear = captureTimes[currentYearIdx];
      if (locker != "year") {
        if (locker == "month") {
          if (isPlaying)
            stopMonthLockFrames();
          seekToFrame(currentYearIdx, "month");
        } else
          seekToFrame(yearDictionary[currentYear]["previousStackEndIdx"] + 1, locker);
        focusTimeTick(timelapse.getCurrentFrameNumber());
      }
      isShowHoverEffect = false;
      $(event.target).removeClass("openHand").addClass("closedHand");
      // Track mouse
      $viewer.on("mousemove", trackMouseAndSlide);
      $(document).one("mouseup", function(event) {
        $(event.target).removeClass("closedHand").addClass("openHand");
        if (!originalIsPaused)
          timelapse.handlePlayPause();
        if (locker == "month" && isPlaying)
          playMonthLockFrames();
        $viewer.off("mousemove", trackMouseAndSlide);
        isShowHoverEffect = true;
      });
      UTIL.addGoogleAnalyticEvent('slider', 'click', 'viewer-seek');
    };

    var handleTimeTickMouseover = function(event) {
      if (isShowHoverEffect) {
        var currentYearIdx = captureTimes[parseInt(this.id.split("_")[3])];
        var currentFrameIdx = yearDictionary[currentYearIdx]["previousStackEndIdx"] + 1;
        if (timelapse.getCurrentFrameNumber() == currentFrameIdx)
          $(event.target).removeClass("closedHand").addClass("openHand").attr("title", "Drag to go to a different point in time");
        else
          $(event.target).attr("title", "");
        var $timeTickContainer = $(event.target).parent();
        var $timeTick = $timeTickContainer.children("#" + viewerDivId + " .timeTick");
        growTimeTick($timeTick);
        if (currentYearIdx != firstYear && currentYearIdx != endYear)
          $timeTickContainer.append($timeTextHover.text(frameDictionary[currentFrameIdx]["year"]).stop(true, true).fadeIn(200));
      } else
        $(event.target).addClass("closedHand");
    };

    var handleTimeTickMouseout = function(event) {
      $(event.target).removeClass("openHand closedHand");
      var $timeTickContainer = $(event.target).parent();
      var $timeTick = $timeTickContainer.children("#" + viewerDivId + " .timeTick");
      resetTimeTick($timeTick);
      $timeTextHover.fadeOut(50);
    };

    var growTimeTick = function($timeTick) {
      $timeTick.stop(true, true).animate({
        "margin-top": ((currentTimeTick_height - timeTickGrow_height) / 2) + "px",
        "width": timeTickGrow_width + "px",
        "height": timeTickGrow_height + "px"
      }, {
        duration: 100
      });
    };

    var resetTimeTick = function($timeTick) {
      $timeTick.stop(true, true).animate({
        "margin-top": (timeTick_height / 2) + "px",
        "width": timeTick_width + "px",
        "height": timeTick_height + "px"
      }, {
        duration: 50
      });
    };

    var trackMouseAndSlide = function(event) {
      var sliderWidth = $customTimeline.width();
      var nowXpx = event.pageX - viewer_offset.left - sliderLeftMargin;
      var nowX = (nowXpx / sliderWidth) * 100;
      var targetFrameIdx;

      if (datasetType == "modis")
        targetFrameIdx = computeSliderHandlePosition_modis(nowX);
      else
        targetFrameIdx = computeSliderHandlePosition_landsat(nowX);

      if (locker == "month") {
        var currentYearIdx = getCurrentYear() - firstYear;
        if (currentYearIdx != targetFrameIdx)
          seekToFrame(targetFrameIdx, locker);
      } else {
        var currentFrameIdx = timelapse.getCurrentFrameNumber();
        if (currentFrameIdx != targetFrameIdx)
          timelapse.seekToFrame(targetFrameIdx);
      }

      $("#" + timeMachineDivId + "_customTimeline_timeTickClickRegion_" + targetFrameIdx).focus();
    };

    var computeSliderHandlePosition_landsat = function(nowX) {
      // Binary search
      var minFrameIdx = 0;
      var maxFrameIdx = frameDictionary.length - 1;
      var targetFrameIdx;
      while (minFrameIdx != maxFrameIdx) {
        targetFrameIdx = Math.round((minFrameIdx + maxFrameIdx) / 2);
        if (nowX <= frameDictionary[targetFrameIdx]["x"])
          maxFrameIdx = targetFrameIdx;
        else
          minFrameIdx = targetFrameIdx;
        if (maxFrameIdx == minFrameIdx + 1) {
          if (frameDictionary[maxFrameIdx]["x"] - nowX <= nowX - frameDictionary[minFrameIdx]["x"])
            targetFrameIdx = maxFrameIdx;
          else
            targetFrameIdx = minFrameIdx;
          break;
        }
      }
      return targetFrameIdx;
    };

    var computeSliderHandlePosition_modis = function(nowX) {
      // Binary search
      var minFrameIdx;
      var maxFrameIdx;
      var totalFrames = timelapse.getNumFrames();

      if (locker == "year") {
        var currentYear = getCurrentYear();
        minFrameIdx = yearDictionary[currentYear]["previousStackEndIdx"] + 1;
        maxFrameIdx = yearDictionary[currentYear]["currentStackEndIdx"];
        if (maxFrameIdx > totalFrames)
          maxFrameIdx = totalFrames - 1;
      } else if (locker == "month") {
        minFrameIdx = 0;
        maxFrameIdx = numYears - 1;
      } else {
        minFrameIdx = 0;
        maxFrameIdx = totalFrames - 1;
      }

      var targetFrameIdx;
      while (minFrameIdx != maxFrameIdx) {
        targetFrameIdx = Math.round((minFrameIdx + maxFrameIdx) / 2);
        var targetFramePositionX;
        if (locker == "month")
          targetFramePositionX = timeTickX[targetFrameIdx];
        else
          targetFramePositionX = frameDictionary[targetFrameIdx]["x"];
        if (nowX <= targetFramePositionX)
          maxFrameIdx = targetFrameIdx;
        else
          minFrameIdx = targetFrameIdx;
        if (maxFrameIdx == minFrameIdx + 1) {
          var maxFramePositionX;
          var minFramePositionX;
          if (locker == "month") {
            maxFramePositionX = timeTickX[maxFrameIdx];
            minFramePositionX = timeTickX[minFrameIdx];
          } else {
            maxFramePositionX = frameDictionary[maxFrameIdx]["x"];
            minFramePositionX = frameDictionary[minFrameIdx]["x"];
          }
          if (maxFramePositionX - nowX <= nowX - minFramePositionX)
            targetFrameIdx = maxFrameIdx;
          else
            targetFrameIdx = minFrameIdx;
          break;
        }
      }
      return targetFrameIdx;
    };

    var doCustomHelpOverlay = function() {
      $("#" + viewerDivId + " .customInstructions").fadeIn(200);
      if (locker == "month" && isPlaying)
        stopMonthLockFrames();
      if ($defaultUIPlaybackButton.hasClass('pause')) {
        timelapse.handlePlayPause();
        $defaultUIPlaybackButton.removeClass("pause").addClass("play from_help");
      }
    };

    var removeCustomHelpOverlay = function() {
      $("#" + viewerDivId + " .customInstructions").fadeOut(200);
      if (locker == "month" && isPlaying)
        playMonthLockFrames();
      if ($defaultUIPlaybackButton.hasClass('from_help')) {
        $defaultUIPlaybackButton.addClass("pause").removeClass("play from_help");
        timelapse.handlePlayPause();
      }
    };

    var getCurrentYear = function() {
      return parseInt($timeText.text());
    };

    var seekToFrame = function(desiredIdx, constraint, yearOffset) {
      var desiredFrameIdx = desiredIdx;
      if (datasetType == "modis") {
        var currentYear = getCurrentYear();
        if (constraint == "month") {
          // Fix month and seek to target year
          var desiredYear = desiredIdx + firstYear;
          var currentFrame = timelapse.getCurrentFrameNumber();
          var currentMonthIdx = frameDictionary[currentFrame]["monthFrameIdx"];
          var maxDesiredMonthIdx = yearDictionary[desiredYear]["maxSpinnerValue"];
          var minDesiredMonthIdx = yearDictionary[desiredYear]["minSpinnerValue"];
          if (currentMonthIdx > maxDesiredMonthIdx || currentMonthIdx < minDesiredMonthIdx)
            return;
          if (desiredYear == firstYear)
            currentMonthIdx -= firstYearFrameOffset;
          desiredFrameIdx = yearDictionary[desiredYear]["previousStackEndIdx"] + 1 + currentMonthIdx;
        } else if (constraint == "year") {
          // Fix year and seek to target month
          var desiredMonthIdx = desiredIdx;
          if (yearOffset) {
            currentYear += yearOffset;
            if (currentYear > endYear)
              currentYear = endYear;
            else if (currentYear < firstYear)
              currentYear = firstYear;
            if (yearOffset > 0)
              desiredMonthIdx = 0;
            else if (yearOffset < 0)
              desiredMonthIdx = yearDictionary[currentYear]["maxSpinnerValue"];
          }
          if (currentYear == firstYear)
            desiredMonthIdx -= firstYearFrameOffset;
          desiredFrameIdx = yearDictionary[currentYear]["previousStackEndIdx"] + 1 + desiredMonthIdx;
        }
      }
      timelapse.seekToFrame(desiredFrameIdx);
    };

    var computeMonthLockPlaybackFrames = function() {
      monthLockPlaybackFrames = [];
      var currentFrame = timelapse.getCurrentFrameNumber();
      var currentMonthIdx = frameDictionary[currentFrame]["monthFrameIdx"];
      // Compute the frame indicies that we need to loop through for the selected month
      for (var i = firstYear; i <= endYear; i++) {
        var year = yearDictionary[i];
        if (currentMonthIdx < year["minSpinnerValue"] || currentMonthIdx > year["maxSpinnerValue"])
          continue;
        var frameIdx = year["previousStackEndIdx"] + 1 + currentMonthIdx;
        if (i == firstYear)
          frameIdx -= firstYearFrameOffset;
        monthLockPlaybackFrames.push(frameIdx);
      }
    };

    var playMonthLockFrames = function() {
      updateMonthLockPlaybackInterval();
      $customPlay.button({
        icons: {
          primary: "ui-icon-custom-pause"
        }
      });
    };

    var setMonthLockPlaybackSpeed = function() {
      var speed = timelapse.getPlaybackRate();
      var desiredSpeed = (1000 / (speed * fps)) * 2;
      if (monthLockPlaybackIdx == 0 || monthLockPlaybackIdx == monthLockPlaybackFrames.length - 1)
        monthLockPlaybackSpeed = 500 + desiredSpeed;
      else
        monthLockPlaybackSpeed = desiredSpeed;
    };

    var startMonthLockPlaybackInterval = function() {
      monthLockPlaybackInterval = setTimeout(function() {
        setMonthLockPlaybackSpeed();
        timelapse.seekToFrame(monthLockPlaybackFrames[monthLockPlaybackIdx]);
        monthLockPlaybackIdx++;
        if (monthLockPlaybackIdx >= monthLockPlaybackFrames.length)
          monthLockPlaybackIdx = 0;
        startMonthLockPlaybackInterval();
      }, monthLockPlaybackSpeed);
    };

    var updateMonthLockPlaybackInterval = function() {
      clearTimeout(monthLockPlaybackInterval);
      setMonthLockPlaybackSpeed();
      monthLockPlaybackInterval = null;
      computeMonthLockPlaybackFrames();
      startMonthLockPlaybackInterval();
    };

    var stopMonthLockFrames = function() {
      clearTimeout(monthLockPlaybackInterval);
      monthLockPlaybackInterval = null;
      $customPlay.button({
        icons: {
          primary: "ui-icon-custom-play"
        }
      });
    };

    var handleMonthLockFramesPlayPause = function() {
      if (!isPlaying)
        playMonthLockFrames();
      else
        stopMonthLockFrames();
    };

    var updateTimelineSlider = function(frameIdx) {
      if (frameIdx < 0 || frameIdx > numFrames - 1)
        return;
      var currentYear = frameDictionary[frameIdx]["year"];
      if (datasetType == "modis") {
        $monthSpinnerTxt.text(frameDictionary[frameIdx]["monthText"]);
        $monthSpinner.val(frameDictionary[frameIdx]["monthFrameIdx"]).trigger('change');
      }
      $currentTimeTick.css("left", frameDictionary[frameIdx]["x"] + "%");
      $timeText.text(currentYear);
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Public methods
    //
    var focusTimeTick = function(frameIdx) {
      var elementIdx = frameIdx;
      if (datasetType == "modis")
        elementIdx = frameDictionary[frameIdx]["year"] - firstYear;
      $("#" + timeMachineDivId + "_customTimeline_timeTickClickRegion_" + elementIdx).focus();
    };
    this.focusTimeTick = focusTimeTick;

    this.getLocker = function() {
      return locker;
    };

    this.isPlaying = function() {
      return isPlaying;
    };

    this.handleHyperwallChangeUI = function() {
      var isShowControls = ( typeof (fields.showControls) != "undefined" && fields.showControls == "true");
      var isFullControls = ( typeof (fields.fullControls) != "undefined" && fields.fullControls == "true");

      if (!isShowControls || !isFullControls)
        $("#" + viewerDivId + " .sideToolBar").remove();

      if (!isShowControls) {
        $customControl.hide();
        $("#" + viewerDivId + " .scaleBarContainer").remove();
      }

      if (!isFullControls) {
        $("#" + viewerDivId + " .customToggleSpeed").remove();
        $customHelpLabel.remove();
        $customPlay.remove();
        $timeText.css({
          "text-align": "center",
          "left": "-=" + 18 + "px",
          "padding-left": "30px",
          "padding-right": "25px"
        });
      }
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // Constructor code
    //
    if (datasetType == "modis")
      preProcessModis();
    else
      preProcessLandsat();

    createCustomControl();

    if (timelapse.getPlayOnLoad()) {
      $customPlay.click();
      $customPlay.button({
        icons: {
          primary: "ui-icon-custom-pause"
        }
      });
    }
  };
  //end of org.gigapan.timelapse.CustomUI
})();
//end of (function() {


text:
class CreateUserDetails < ActiveRecord::Migration
  def change
    create_table :user_details do |t|
      t.belongs_to :actor, index: true
      t.text :name, :default => '', :null => false

      t.timestamps :null => false
    end
  end
end


text:
'use strict';
const ipc = require('electron').ipcRenderer;

ipc.on('reload', () => {
	window.location.reload();
});

ipc.on('show-notifications', () => {
	document.querySelector('button.toolbar-button').click();
});

ipc.on('log-out', () => {
	// create the menu for the below
	document.querySelector('md-toolbar md-menu:last-child button').click();

	document.querySelector('.md-open-menu-container md-menu-item:last-child button').click();
});


text:
fn main() {
    loop { break.push(1); } //~ ERROR type `!` does not implement any method in scope named `push`
}


text:
package achecrawler.memex.cdr;

import java.util.Date;

import com.fasterxml.jackson.core.JsonProcessingException;

public class Sample {

    @SuppressWarnings("unused")
    public static void main(String[] args) throws JsonProcessingException {

        CDR2Document.Builder builder = new CDR2Document.Builder();

        builder.setUrl("http://www.darpa.mil/program/memex")
               .setRawContent("<title>Sample title</title>Original text")
//               .setContentType("text/html")
               .setCrawler("memex-crawler")
               .setTeam("DARPA")
               .setVersion("2.0")
               .setTimestamp(new Date().getTime());

        // A object to acccess CDR document fields
        CDR2Document doc = builder.build();

        // A object already serialized in JSON format
        String json = builder.buildAsJson();

        System.out.println(json);

    }

}


text:
package org.apache.activemq.artemis.core.journal;

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

public class PreparedTransactionInfo
{
   public final long id;

   public final byte[] extraData;

   public final List<RecordInfo> records = new ArrayList<RecordInfo>();

   public final List<RecordInfo> recordsToDelete = new ArrayList<RecordInfo>();

   public PreparedTransactionInfo(final long id, final byte[] extraData)
   {
      this.id = id;

      this.extraData = extraData;
   }
}


text:
import random
import string

def create_url():
    """
    Creates a unique 50 figure string.
    """
    from lfs_downloadable_products.models import ProductUrl
    while 1:
        url =  "".join([random.choice(string.ascii_letters + string.digits) for n in xrange(50)])
        try:
            ProductUrl.objects.get(url=url)
        except ProductUrl.DoesNotExist:
            return url


text:
desc "Prints lines of code metrics"
task :stats do
  lines, codelines, total_lines, total_codelines = 0, 0, 0, 0

  FileList["lib/keymap/**/*.rb"].each { |file_name|
    next if file_name =~ /vendor/
    f = File.open(file_name)

    while (line = f.gets)
      lines += 1
      next if line =~ /^\s*$/
      next if line =~ /^\s*#/
      codelines += 1
    end
    puts "L: #{sprintf("%4d", lines)}, LOC #{sprintf("%4d", codelines)} | #{file_name}"

    total_lines += lines
    total_codelines += codelines

    lines, codelines = 0, 0
  }

  puts "Total: Lines #{total_lines}, LOC #{total_codelines}"
end


text:
CHANGELOG
=========

2.1.0 (2022-10-31)
------------------

* Messages for `DeserializationException` have been improved, and the cause
 is included, if any. Moreover, the message provides detail about the involved
 types, if the exception is caused by an `IllegalArgumentException`.

2.0.0 (2020-10-13)
------------------

* No changes since 2.0.0-rc2.

2.0.0-rc2 (2020-09-29)
----------------------

* Build using the `--release` command-line option so linking when using
  Java 8 works.

2.0.0-rc1 (2020-09-24)
----------------------

* Significant API changes. The `get()` and `getRecord()` methods now take a
  class parameter specifying the type of object to deserialize into. You
  can either deserialize into a `Map` or to model classes that use the
  `MaxMindDbConstructor` and `MaxMindDbParameter` annotations to identify
  the constructors and parameters to deserialize into.
* `jackson-databind` is no longer a dependency.
* The `Record` class is now named `DatabaseRecord`. This is to avoid a
  conflict with `java.lang.Record` in Java 14.

1.4.0 (2020-06-12)
------------------

* IMPORTANT: Java 8 is now required. If you need Java 7 support, please
  continue using 1.3.1 or earlier.
* The decoder will now throw an `InvalidDatabaseException` on an invalid
  control byte in the data section rather than an
  `ArrayIndexOutOfBoundsException`. Reported by Edwin Delgado H. GitHub
  #68.
* In order to improve performance when lookups are done from multiple
  threads, a use of `synchronized` has been removed. GitHub #65 & #69.
* `jackson-databind` has been upgraded to 2.11.0.

1.3.1 (2020-03-03)
------------------

* Correctly decode strings that are between 157 and 288 bytes long. 1.3.0
  introduced a regression when decoding these due to using a signed `byte`
  as an unsigned value. Reported by Dongmin Yu. GitHub #181 in
  maxmind/GeoIP2-java.
* Update `jackson-databind` dependency.

1.3.0 (2019-12-13)
------------------

* IMPORTANT: Java 7 is now required. If you need Java 6 support, please
  continue using 1.2.2 or earlier.
* The method `getRecord` was added to `com.maxmind.db.Reader`. This method
  returns a `com.maxmind.db.Record` object that includes the data for the
  record as well as the network associated with the record.

1.2.2 (2017-02-22)
------------------

* Remove the version range. As of today, `jackson-databind` is no longer
  resolved correctly when a range is used. GitHub #28.

1.2.1 (2016-04-15)
------------------

* Specify a hard minimum dependency for `jackson-databind`. This API will not
  work with versions earlier than 2.7.0, and Maven's nearest-first resolution
  rule often pulled in older versions.

1.2.0 (2016-01-13)
------------------

* `JsonNode` containers returned by the `get(ip)` are now backed by
  unmodifiable collections. Any mutation done to them will fail with an
  `UnsupportedOperationException` exception. This allows safe caching of the
  nodes to be done without doing a deep copy of the cached data. Pull request
  by Viktor Szathmáry. GitHub #24.

1.1.0 (2016-01-04)
------------------

* The reader now supports pluggable caching of the decoded data. By default,
  no caching is performed. Please see the `README.md` file or the API docs
  for information on how to enable caching. Pull requests by Viktor Szathmáry.
  GitHub #21.
* This release also includes several additional performance enhancements as
  well as code cleanup from Viktor Szathmáry. GitHub #18, #19, #20, #22,and
  #23.

1.0.1 (2015-12-17)
------------------

* Several optimizations have been made to reduce allocations when decoding a
  record. Pull requests by Viktor Szathmáry. GitHub #16 & #17.

1.0.0 (2014-09-29)
------------------

* First production release.

0.4.0 (2014-09-23)
------------------

* Made `com.maxmind.db.Metadata` public and added public getters for most
  of the interesting metadata. This is accessible through the `getMetadata()`
  method on a `Reader` object.

0.3.4 (2014-08-27)
------------------

* Previously the Reader would hold onto the underlying file and FileChannel,
  not closing them until the Reader was closed. This was unnecessary; they
  are now closed immediately after they are used. Fix by Andrew Snare; GitHub
  issue #7.
* The Reader now discards the reference to the underlying buffer when
  `close()` is called. This is done to help ensure that the buffer is garbage
  collected sooner, which may mitigate file locking issues that some users
  have experienced on Windows when updating the database. Patch by Andrew
  Snare; GitHub issue #8.

0.3.3 (2014-06-02)
------------------

* A potential (small) resource leak when using this library with a thread
  pool was fixed.

0.3.2 (2014-04-02)
------------------

* Added tests and documentation for multi-threaded use.

0.3.1 (2013-11-05)
------------------

* An `InputStream` constructor was added to the `Reader` class. This reads the
  stream into memory as if it was using `FileMode.MEMORY`. Patch by Matthew
  Daniel.
* The source code is now attached during packaging. Patch by Matthew Daniel.
* The artifact ID was changed to `maxmind-db` in order to increase naming
  consistency.

0.3.0 (2013-10-17)
------------------

* IMPORTANT: The package name was changed to `com.maxmind.db`. The
  `MaxMindDbReader` class was renamed to `Reader`.
* Improved error handling and test coverage.
* Performance improvements.

0.2.0 (2013-07-08)
------------------

* The reader and database format now uses IEEE 754 doubles and floats.
* FileMode.IN_MEMORY was renamed to FileMode.MEMORY.
* Cache Type enum values array.

0.1.0 (2013-06-14)
------------------

* Initial release


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Àà·Ö²ã½á¹¹ (Spring Security 4.2.2.RELEASE API)</title>
<meta name="date" content="2017-10-31">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

ÄúµÄä¯ÀÀÆ÷ÒѽûÓà JavaScript¡£

Ìø¹ýµ¼º½Á´½Ó

³ÌÐò°ü

Àà

Ê÷

Òѹýʱ

Ë÷Òý

°ïÖú

spring-security-samples-javaconfig-form

ÉÏÒ»¸ö

ÏÂÒ»¸ö

¿ò¼Ü

ÎÞ¿ò¼Ü

ËùÓÐÀà

ËùÓгÌÐò°üµÄ·Ö²ã½á¹¹

³ÌÐò°ü·Ö²ã½á¹¹:

org.springframework.security.samples.config

Àà·Ö²ã½á¹¹

java.lang.Object

org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer (implements org.springframework.web.WebApplicationInitializer)

org.springframework.security.samples.config.MessageSecurityWebApplicationInitializer

org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter (implements org.springframework.security.config.annotation.web.WebSecurityConfigurer<T>)

org.springframework.security.samples.config.SecurityConfig

Ìø¹ýµ¼º½Á´½Ó

³ÌÐò°ü

Àà

Ê÷

Òѹýʱ

Ë÷Òý

°ïÖú

spring-security-samples-javaconfig-form

ÉÏÒ»¸ö

ÏÂÒ»¸ö

¿ò¼Ü

ÎÞ¿ò¼Ü

ËùÓÐÀà


text:
require 'spec_helper'
require 'pdk/cli/exec/command'

describe PDK::CLI::Exec::Command do
  subject(:command) { described_class.new('/bin/echo', 'foo') }

  before(:each) do
    allow(PDK::CLI::Util).to receive(:ci_environment?).and_return(false)
  end

  describe '.context=' do
    context 'when setting to an expected value' do
      it 'accepts :system' do
        expect { command.context = :system }.not_to raise_error
        expect(command.context).to eq :system
      end

      it 'accepts :module' do
        expect { command.context = :module }.not_to raise_error
        expect(command.context).to eq :module
      end

      it 'rejects other values' do
        expect { command.context = :foo }.to raise_error ArgumentError
      end
    end
  end

  describe '.add_spinner' do
    context 'without --debug' do
      before(:each) do
        allow(logger).to receive(:debug?).and_return(false)
        allow($stderr).to receive(:isatty).and_return(true)
        command.add_spinner('message')
      end

      it { expect(command.spinner).to be_a TTY::Spinner }
    end

    context 'with --debug' do
      before(:each) do
        allow(logger).to receive(:debug?).and_return(true)
        command.add_spinner('message')
      end

      it { expect(command.spinner).to be_nil }
    end

    context 'when run non-interactive' do
      before(:each) do
        allow($stderr).to receive(:isatty).and_return(false)
        command.add_spinner('message')
      end

      it { expect(command.spinner).to be_nil }
    end
  end

  describe '.register_spinner' do
    let(:spinner) { instance_double('spinner') }

    context 'without --debug' do
      before(:each) do
        allow(logger).to receive(:debug?).and_return(false)
        allow($stderr).to receive(:isatty).and_return(true)
        command.register_spinner(spinner)
      end

      it { expect(command.spinner).to eq spinner }
    end

    context 'with --debug' do
      before(:each) do
        allow(logger).to receive(:debug?).and_return(true)
        command.register_spinner(spinner)
      end

      it { expect(command.spinner).to be_nil }
    end

    context 'when run non-interactive' do
      before(:each) do
        allow($stderr).to receive(:isatty).and_return(false)
        command.register_spinner(spinner)
      end

      it { expect(command.spinner).to be_nil }
    end
  end

  describe '.execute!' do
    let(:process) { instance_double('ChildProcess.build(*@argv)') }
    let(:io) { instance_double('ChildProcess.io') }

    before(:each) do
      expect(ChildProcess).to receive(:build).with('/bin/echo', 'foo').and_return(process)
      allow(process).to receive(:leader=)
      allow(io).to receive(:stdout=)
      allow(io).to receive(:stderr=)
      allow(process).to receive(:io).and_return(io)
      allow(process).to receive(:wait)
    end

    context 'when running in the :system context' do
      before(:each) do
        command.context = :system
        expect(process).to receive(:start).with(no_args)
        allow(process).to receive(:exit_code).and_return 0
        allow(process).to receive(:environment).and_return({})
      end

      it { expect { command.execute! }.not_to raise_error }
    end

    context 'when running in the :module context' do
      let(:environment) { {} }

      before(:each) do
        command.context = :module
        expect(process).to receive(:start).with(no_args)
        allow(PDK::Util).to receive(:module_root).with(no_args).and_return('/invalid_path')
        allow(Dir).to receive(:chdir).with('/invalid_path').and_yield
        allow(process).to receive(:exit_code).and_return 0
        allow(process).to receive(:environment).at_least(:once).and_return environment
      end

      it { expect { command.execute! }.not_to raise_error }

      it 'includes gem bin paths in PATH' do
        command.execute!

        expect(environment).to include('PATH')

        path_array = environment['PATH'].split(File::PATH_SEPARATOR)

        expect(path_array).to include(File.join(PDK::Util::RubyVersion.gem_home, 'bin'))
        expect(path_array).to include(*PDK::Util::RubyVersion.gem_paths_raw.map { |gem_path| File.join(gem_path, 'bin') })
      end
    end
  end
end


text:
#pragma once

#include <inviwo/core/common/inviwomodule.h>
#include <modules/abuffergl/abufferglmoduledefine.h>
#include <inviwo/core/io/serialization/versionconverter.h>

namespace inviwo {

class IVW_MODULE_ABUFFERGL_API ABufferGLModule : public InviwoModule {
public:
    ABufferGLModule(InviwoApplication* app);

    virtual int getVersion() const override;
    virtual std::unique_ptr<VersionConverter> getConverter(int version) const override;

private:
    class Converter : public VersionConverter {
    public:
        Converter(int version);
        virtual bool convert(TxElement* root) override;

    private:
        int version_;
    };
};

}  // namespace inviwo


text:
package org.apache.hadoop.hdfs.server.blockmanagement;

public class ReportStatistics{
  private int numBuckets;
  private int numBucketsMatching;
  private int numBlocks;
  private int numToRemove;
  private int numToInvalidate;
  private int numToCorrupt;
  private int numToUC;
  private int numToAdd;
  int numConsideredSafeIfInSafemode;

  public int getNumBuckets() {
    return numBuckets;
  }

  public void setNumBuckets(int numBuckets) {
    this.numBuckets = numBuckets;
  }

  public int getNumBucketsMatching() {
    return numBucketsMatching;
  }

  public void setNumBucketsMatching(int numBucketsMatching) {
    this.numBucketsMatching = numBucketsMatching;
  }

  public int getNumBlocks() {
    return numBlocks;
  }

  public void setNumBlocks(int numBlocks) {
    this.numBlocks = numBlocks;
  }

  public int getNumToRemove() {
    return numToRemove;
  }

  public void setNumToRemove(int numToRemove) {
    this.numToRemove = numToRemove;
  }

  public int getNumToInvalidate() {
    return numToInvalidate;
  }

  public void setNumToInvalidate(int numToInvalidate) {
    this.numToInvalidate = numToInvalidate;
  }

  public int getNumToCorrupt() {
    return numToCorrupt;
  }

  public void setNumToCorrupt(int numToCorrupt) {
    this.numToCorrupt = numToCorrupt;
  }

  public int getNumToUC() {
    return numToUC;
  }

  public void setNumToUC(int numToUC) {
    this.numToUC = numToUC;
  }

  public int getNumToAdd() {
    return numToAdd;
  }

  public void setNumToAdd(int numToAdd) {
    this.numToAdd = numToAdd;
  }

  public int getNumConsideredSafeIfInSafemode() {
    return numConsideredSafeIfInSafemode;
  }

  public void setNumConsideredSafeIfInSafemode(int numConsideredSafeIfInSafemode) {
    this.numConsideredSafeIfInSafemode = numConsideredSafeIfInSafemode;
  }

  @Override
  public String toString() {
    return "ReportStatistics{" +
            "numBuckets=" + numBuckets +
            ", numBlocks=" + numBlocks +
            ", numBucketsMatching=" + numBucketsMatching +
            ", numToRemove=" + numToRemove +
            ", numToInvalidate=" + numToInvalidate +
            ", numToCorrupt=" + numToCorrupt +
            ", numToUC=" + numToUC +
            ", numToAdd=" + numToAdd +
            ", numConsideredSafeIfInSafemode=" + numConsideredSafeIfInSafemode +
            '}';
  }
}


text:
using testing::_;
using testing::DoAll;
using testing::Mock;
using testing::SaveArg;

namespace remoting {
namespace protocol {

namespace {
const char kTestMessage1[] = "Message1";
const char kTestMessage2[] = "Message2";

ACTION(CallDoneTask) {
  arg0.Run();
}
}  // namespace

class MockMessageReceivedCallback {
 public:
  MOCK_METHOD1(OnMessage, void(const base::Closure&));
};

class MessageReaderTest : public testing::Test {
 public:
  MessageReaderTest()
      : in_callback_(false) {
  }

  // Following two methods are used by the ReadFromCallback test.
  void AddSecondMessage(const base::Closure& task) {
    AddMessage(kTestMessage2);
    in_callback_ = true;
    task.Run();
    in_callback_ = false;
  }

  void OnSecondMessage(const base::Closure& task) {
    EXPECT_FALSE(in_callback_);
    task.Run();
  }

  // Used by the DeleteFromCallback() test.
  void DeleteReader(const base::Closure& task) {
    reader_.reset();
    task.Run();
  }

 protected:
  virtual void SetUp() OVERRIDE {
    reader_.reset(new MessageReader());
  }

  virtual void TearDown() OVERRIDE {
    STLDeleteElements(&messages_);
  }

  void InitReader() {
    reader_->Init(&socket_, base::Bind(
        &MessageReaderTest::OnMessage, base::Unretained(this)));
  }

  void AddMessage(const std::string& message) {
    std::string data = std::string(4, ' ') + message;
    talk_base::SetBE32(const_cast<char*>(data.data()), message.size());

    socket_.AppendInputData(std::vector<char>(data.begin(), data.end()));
  }

  bool CompareResult(CompoundBuffer* buffer, const std::string& expected) {
    std::string result(buffer->total_bytes(), ' ');
    buffer->CopyTo(const_cast<char*>(result.data()), result.size());
    return result == expected;
  }

  void OnMessage(scoped_ptr<CompoundBuffer> buffer,
                 const base::Closure& done_callback) {
    messages_.push_back(buffer.release());
    callback_.OnMessage(done_callback);
  }

  MessageLoop message_loop_;
  scoped_ptr<MessageReader> reader_;
  FakeSocket socket_;
  MockMessageReceivedCallback callback_;
  std::vector<CompoundBuffer*> messages_;
  bool in_callback_;
};

// Receive one message and process it with delay
TEST_F(MessageReaderTest, OneMessage_Delay) {
  base::Closure done_task;

  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(1)
      .WillOnce(SaveArg<0>(&done_task));

  InitReader();
  message_loop_.RunUntilIdle();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(messages_[0], kTestMessage1));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  done_task.Run();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive one message and process it instantly.
TEST_F(MessageReaderTest, OneMessage_Instant) {
  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(1)
      .WillOnce(CallDoneTask());

  InitReader();
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(socket_.read_pending());
  EXPECT_EQ(1U, messages_.size());
}

// Receive two messages in one packet.
TEST_F(MessageReaderTest, TwoMessages_Together) {
  base::Closure done_task1;
  base::Closure done_task2;

  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(2)
      .WillOnce(SaveArg<0>(&done_task1))
      .WillOnce(SaveArg<0>(&done_task2));

  InitReader();
  message_loop_.RunUntilIdle();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(messages_[0], kTestMessage1));
  EXPECT_TRUE(CompareResult(messages_[1], kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  done_task1.Run();
  message_loop_.RunUntilIdle();

  EXPECT_FALSE(socket_.read_pending());

  done_task2.Run();
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in one packet, and process the first one
// instantly.
TEST_F(MessageReaderTest, TwoMessages_Instant) {
  base::Closure done_task2;

  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(2)
      .WillOnce(CallDoneTask())
      .WillOnce(SaveArg<0>(&done_task2));

  InitReader();
  message_loop_.RunUntilIdle();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(messages_[1], kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the second message.
  EXPECT_FALSE(socket_.read_pending());

  done_task2.Run();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in one packet, and process both of them
// instantly.
TEST_F(MessageReaderTest, TwoMessages_Instant2) {
  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(2)
      .WillOnce(CallDoneTask())
      .WillOnce(CallDoneTask());

  InitReader();
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in separate packets.
TEST_F(MessageReaderTest, TwoMessages_Separately) {
  base::Closure done_task;

  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(1)
      .WillOnce(SaveArg<0>(&done_task));

  InitReader();
  message_loop_.RunUntilIdle();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(messages_[0], kTestMessage1));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  done_task.Run();
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(socket_.read_pending());

  // Write another message and verify that we receive it.
  EXPECT_CALL(callback_, OnMessage(_))
      .Times(1)
      .WillOnce(SaveArg<0>(&done_task));
  AddMessage(kTestMessage2);
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(CompareResult(messages_[1], kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  done_task.Run();

  EXPECT_TRUE(socket_.read_pending());
}

// Read() returns error.
TEST_F(MessageReaderTest, ReadError) {
  socket_.set_next_read_error(net::ERR_FAILED);

  // Add a message. It should never be read after the error above.
  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(0);

  InitReader();
}

// Verify that we the OnMessage callback is not reentered.
TEST_F(MessageReaderTest, ReadFromCallback) {
  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_))
      .Times(2)
      .WillOnce(Invoke(this, &MessageReaderTest::AddSecondMessage))
      .WillOnce(Invoke(this, &MessageReaderTest::OnSecondMessage));

  InitReader();
  message_loop_.RunUntilIdle();

  EXPECT_TRUE(socket_.read_pending());
}

// Verify that we stop getting callbacks after deleting MessageReader.
TEST_F(MessageReaderTest, DeleteFromCallback) {
  base::Closure done_task1;
  base::Closure done_task2;

  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  // OnMessage() should never be called for the second message.
  EXPECT_CALL(callback_, OnMessage(_))
      .Times(1)
      .WillOnce(Invoke(this, &MessageReaderTest::DeleteReader));

  InitReader();
  message_loop_.RunUntilIdle();
}

}  // namespace protocol
}  // namespace remoting


text:
Crops and/or pads an image to a target width and height.

Resizes an image to a target width and height by either centrally
cropping the image or padding it evenly with zeros.

If `width` or `height` is greater than the specified `target_width` or
`target_height` respectively, this op centrally crops along that dimension.
If `width` or `height` is smaller than the specified `target_width` or
`target_height` respectively, this op centrally pads with 0 along that
dimension.

##### Args:

*  <b>`image`</b>: 3-D tensor of shape [height, width, channels]
*  <b>`target_height`</b>: Target height.
*  <b>`target_width`</b>: Target width.

##### Raises:

*  <b>`ValueError`</b>: if `target_height` or `target_width` are zero or negative.

##### Returns:

  Cropped and/or padded image of shape
  `[target_height, target_width, channels]`