text:
typedef unsigned int SkColor;

namespace ash {

// In the window corners, the resize areas don't actually expand bigger, but the
// 16 px at the end of each edge triggers diagonal resizing.
ASH_EXPORT extern const int kResizeAreaCornerSize;

// Ash windows do not have a traditional visible window frame. Window content
// extends to the edge of the window. We consider a small region outside the
// window bounds and an even smaller region overlapping the window to be the
// "non-client" area and use it for resizing.
ASH_EXPORT extern const int kResizeOutsideBoundsSize;
ASH_EXPORT extern const int kResizeOutsideBoundsScaleForTouch;
ASH_EXPORT extern const int kResizeInsideBoundsSize;

#if defined(OS_CHROMEOS)
// Background color used for the Chrome OS boot splash screen.
extern const SkColor kChromeOsBootColor;
#endif

// The border color of keyboard focus for launcher items and system tray.
extern const SkColor kFocusBorderColor;

}  // namespace ash

#endif  // ASH_COMMON_ASH_CONSTANTS_H_


text:
"use strict";

var _interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

exports.__esModule = true;

var _Transformer = require("./transformer");

var _Transformer2 = _interopRequireDefault(_Transformer);

var _normalizeAst = require("../helpers/normalize-ast");

var _normalizeAst2 = _interopRequireDefault(_normalizeAst);

var _assign = require("lodash/object/assign");

var _assign2 = _interopRequireDefault(_assign);

var _object = require("../helpers/object");

var _object2 = _interopRequireDefault(_object);

var _File = require("./file");

var _File2 = _interopRequireDefault(_File);

var TransformerPipeline = (function () {
  function TransformerPipeline() {
    _classCallCheck(this, TransformerPipeline);

    this.transformers = _object2["default"]();
    this.namespaces = _object2["default"]();
    this.deprecated = _object2["default"]();
    this.aliases = _object2["default"]();
    this.filters = [];
  }

  TransformerPipeline.prototype.addTransformers = function addTransformers(transformers) {
    for (var key in transformers) {
      this.addTransformer(key, transformers[key]);
    }
    return this;
  };

  TransformerPipeline.prototype.addTransformer = function addTransformer(key, transformer) {
    if (this.transformers[key]) throw new Error(); // todo: error

    var namespace = key.split(".")[0];
    this.namespaces[namespace] = this.namespaces[namespace] || [];
    this.namespaces[namespace].push(key);
    this.namespaces[key] = namespace;

    this.transformers[key] = new _Transformer2["default"](key, transformer);
  };

  TransformerPipeline.prototype.addAliases = function addAliases(names) {
    _assign2["default"](this.aliases, names);
    return this;
  };

  TransformerPipeline.prototype.addDeprecated = function addDeprecated(names) {
    _assign2["default"](this.deprecated, names);
    return this;
  };

  TransformerPipeline.prototype.addFilter = function addFilter(filter) {
    this.filters.push(filter);
    return this;
  };

  TransformerPipeline.prototype.canTransform = function canTransform(transformer, fileOpts) {
    var _arr = this.filters;

    for (var _i = 0; _i < _arr.length; _i++) {
      var filter = _arr[_i];
      var result = filter(transformer, fileOpts);
      if (result != null) return result;
    }

    return true;
  };

  TransformerPipeline.prototype.transform = function transform(code, opts) {
    var file = new _File2["default"](opts, this);
    return file.wrap(code, function () {
      file.addCode(code, true);
    });
  };

  TransformerPipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) {
    ast = _normalizeAst2["default"](ast);

    var file = new _File2["default"](opts, this);
    return file.wrap(code, function () {
      file.addCode(code);
      file.addAst(ast);
    });
  };

  TransformerPipeline.prototype._ensureTransformerNames = function _ensureTransformerNames(type, rawKeys) {
    var keys = [];

    for (var i = 0; i < rawKeys.length; i++) {
      var key = rawKeys[i];

      var deprecatedKey = this.deprecated[key];
      var aliasKey = this.aliases[key];
      if (aliasKey) {
        keys.push(aliasKey);
      } else if (deprecatedKey) {
        // deprecated key, remap it to the new one
        console.error("[BABEL] The transformer " + key + " has been renamed to " + deprecatedKey);
        rawKeys.push(deprecatedKey);
      } else if (this.transformers[key]) {
        // valid key
        keys.push(key);
      } else if (this.namespaces[key]) {
        // namespace, append all transformers within this namespace
        keys = keys.concat(this.namespaces[key]);
      } else {
        // invalid key
        throw new ReferenceError("Unknown transformer " + key + " specified in " + type);
      }
    }

    return keys;
  };

  return TransformerPipeline;
})();

exports["default"] = TransformerPipeline;
module.exports = exports["default"];

redpajama_set_name: RedPajamaGithub


text:
import Live
from _Framework.CompoundComponent import CompoundComponent
from _Framework.SubjectSlot import subject_slot
from _Framework.ButtonElement import ButtonElement
from _Framework.Util import find_if
from itertools import imap
from TrackControllerComponent import TrackControllerComponent
from ScaleComponent import *  # noqa
from StepSequencerComponent import StepSequencerComponent
from consts import *  # noqa

class InstrumentControllerComponent(CompoundComponent):

	def __init__(self, matrix, side_buttons, top_buttons, parent):
		super(InstrumentControllerComponent, self).__init__()
		self._parent = parent
		self._osd = None
		self._matrix = None
		self._side_buttons = side_buttons
		self._remaining_buttons = []
		self._track_controller = None
		self.base_channel = 11
		self._quick_scales = [0, 1, 2, 3, 4, 5, 6, 7, 10, 13, 14, 15, 17, 18, 24]
		self._quick_scale_root = True
		self._normal_feedback_velocity = AMBER_FULL
		self._recordind_feedback_velocity = RED_FULL
		self._drum_group_device = None
		self._octave_up_button = None
		self._octave_down_button = None
		self._scales_toggle_button = None
		self.set_scales_toggle_button(side_buttons[0])
		self.set_octave_up_button(side_buttons[2])
		self.set_octave_down_button(side_buttons[3])

		self._track_controller = self.register_component(TrackControllerComponent())
		self._track_controller.set_enabled(False)
		self._track_controller.set_parent(self._parent._parent)
		self._track_controller.set_prev_scene_button(top_buttons[0])
		self._track_controller.set_next_scene_button(top_buttons[1])
		self._track_controller.set_prev_track_button(top_buttons[2])
		self._track_controller.set_next_track_button(top_buttons[3])
		self._track_controller.set_undo_button(side_buttons[1])
		self._track_controller.set_stop_button(side_buttons[4])
		self._track_controller.set_play_button(side_buttons[5])
		self._track_controller.set_session_record_button(side_buttons[7])
		self._track_controller.set_solo_button(side_buttons[6])

		self._scales = self.register_component(ScalesComponent())
		self._scales.set_enabled(False)
		self.set_matrix(matrix)
		self._scales.set_parent(self)
		self._scales.set_matrix(matrix)
		self._scales.set_osd(self._osd)

		self._on_session_record_changed.subject = self.song()

	def set_enabled(self, enabled):
		CompoundComponent.set_enabled(self, enabled)
		if self._track_controller != None:
			self._track_controller.set_enabled(enabled)
		feedback_channels = [self.base_channel, self.base_channel + 1, self.base_channel + 2, self.base_channel + 3]
		# non_feedback_channel = self.base_channel + 4
		self._set_feedback_velocity()
		self._parent._parent.set_feedback_channels(feedback_channels)
		if not enabled:
			self._parent._parent.release_controlled_track()
		else:
			self._parent._parent.set_controlled_track(self.song().view.selected_track)

		if self._track_controller != None:
			self._track_controller._do_implicit_arm(enabled)
			self._track_controller.set_enabled(enabled)
		if enabled:
			self._update_OSD()

	def _set_feedback_velocity(self):
		if self.song().session_record:
			self._parent._parent._c_instance.set_feedback_velocity(self._recordind_feedback_velocity)
		else:
			self._parent._parent._c_instance.set_feedback_velocity(self._normal_feedback_velocity)

	@subject_slot('session_record')
	def _on_session_record_changed(self):
		self._set_feedback_velocity()

	def set_scales_toggle_button(self, button):
		assert isinstance(button, (ButtonElement, type(None)))
		if (self._scales_toggle_button != None):
			self._scales_toggle_button.remove_value_listener(self._scales_toggle)
		self._scales_toggle_button = button
		if (self._scales_toggle_button != None):
			self._scales_toggle_button.add_value_listener(self._scales_toggle, identify_sender=True)
			self._scales_toggle_button.turn_off()

	def set_octave_up_button(self, button=None):
		assert isinstance(button, (ButtonElement, type(None)))
		if (self._octave_up_button != None):
			self._octave_up_button.remove_value_listener(self._scroll_octave_up)
		self._octave_up_button = button
		if (self._octave_up_button != None):
			self._octave_up_button.add_value_listener(self._scroll_octave_up, identify_sender=True)
			self._octave_up_button.turn_off()

	def set_octave_down_button(self, button=None):
		assert isinstance(button, (ButtonElement, type(None)))
		if (self._octave_down_button != None):
			self._octave_down_button.remove_value_listener(self._scroll_octave_down)
		self._octave_down_button = button
		if (self._octave_down_button != None):
			self._octave_down_button.add_value_listener(self._scroll_octave_down, identify_sender=True)
			self._octave_down_button.turn_off()

	def _scales_toggle(self, value, sender):
		if self.is_enabled():
			self._scales_toggle_button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
			if (value is not 0):
				self._osd_mode_backup = self._osd.mode
				self._scales.set_enabled(True)
				self._osd.mode = self._osd_mode_backup + ' - Scale'
				self._scales_toggle_button.turn_on()
				self._scales.update()
			else:
				self._scales_toggle_button.turn_off()
				self._scales.set_enabled(False)
				self._osd.mode = self._osd_mode_backup
				self.update()

	def _can_scroll_octave_up(self):
		return self._scales._octave_index + self._scales._presets.octave_index_offset < 10

	def _can_scroll_octave_down(self):
		return self._scales._octave_index + self._scales._presets.octave_index_offset > -2

	def _scroll_octave_up(self, value, sender):
		if self.is_enabled():
			if ((not sender.is_momentary()) or (value is not 0)):
				if self._can_scroll_octave_up():
					self._scales._octave_index += 1
					self.update()

	def _scroll_octave_down(self, value, sender):
		if self.is_enabled():
			if ((not sender.is_momentary()) or (value is not 0)):
				if self._can_scroll_octave_down():
					self._scales._octave_index -= 1
					self.update()

	def tuple_idx(self, tuple, obj):
		for i in xrange(0, len(tuple)):
			if (tuple[i] == obj):
				return i
		return(False)

	def _matrix_value_quickscale(self, value, x, y, is_momentary):  # matrix buttons listener for advanced mode
		if self.is_enabled() and not self._scales.is_enabled() and self._scales.is_quick_scale:
			keys = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
			if ((value != 0) or (not is_momentary)):
				if self._quick_scale_root:
					root = -1
					selected_key = self._scales._selected_key
					selected_modus = self._scales._selected_modus
					if y == 1 and x < 7 or y == 0 and x in[0, 1, 3, 4, 5]:
						if y == 1:
							root = [0, 2, 4, 5, 7, 9, 11, 12][x]
							self._parent._parent.show_message(keys[root]+" "+str(self._scales._modus_names[selected_modus]))
						if y == 0 and x < 6:
							root = [0, 2, 4, 5, 7, 9, 11, 12][x] + 1
							self._parent._parent.show_message(keys[root]+" "+str(self._scales._modus_names[selected_modus]))
						if root == selected_key:  # alternate minor/major
							if selected_modus == 0:
								selected_modus = self._scales._current_minor_mode
							elif selected_modus in [1, 13, 14]:
								self._scales._current_minor_mode = selected_modus
								selected_modus = 0
							elif selected_modus == 11:
								selected_modus = 12
							elif selected_modus == 12:
								selected_modus = 11
							self._parent._parent.show_message(keys[root]+" "+str(self._scales._modus_names[selected_modus]))
					else:
						if y == 0 and x == 7:  # change mode
							self._quick_scale_root = not self._quick_scale_root
							if self._quick_scale_root:
								self._parent._parent.show_message("quick scale : root")
							else:
								self._parent._parent.show_message("quick scale : modes")
							self.update()
						if y == 1 and x == 7 and False:  # rotate minor scales
							if self._scales._selected_modus in self._scales._minor_modes:
								self._scales.set_selected_modus(self._scales._minor_modes[(self.tuple_idx(self._scales._minor_modes, self._scales._selected_modus) + 1) % 3])
								self._parent._parent.show_message(keys[root]+" "+str(self._scales._modus_names[self._scales._selected_modus]))
								self.update()
						if y == 1 and x == 7:  # nav circle of 5th right
							root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 1 + 12) % 12]
							self._parent._parent.show_message("circle of 5ths -> "+keys[selected_key]+" "+str(self._scales._modus_names[selected_modus])+" => "+keys[root]+" "+str(self._scales._modus_names[selected_modus]))
						if y == 0 and x == 6:  # nav circle of 5th left
							root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 1 + 12) % 12]
							self._parent._parent.show_message("circle of 5ths <- "+keys[selected_key]+" "+str(self._scales._modus_names[selected_modus])+" => "+keys[root]+" "+str(self._scales._modus_names[selected_modus]))
						if y == 0 and x == 2:  # relative scale
							if selected_modus == 0:
								selected_modus = self._scales._current_minor_mode
								root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 3) % 12]
							elif selected_modus in [1, 13, 14]:
								self._scales._current_minor_mode = selected_modus
								selected_modus = 0
								root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 3 + 12) % 12]
							elif selected_modus == 11:
								selected_modus = 12
								root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 3) % 12]
							elif selected_modus == 12:
								selected_modus = 11
								root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 3 + 12) % 12]
							self._parent._parent.show_message("Relative scale : "+keys[root]+" "+str(self._scales._modus_names[selected_modus]))

					if root != -1:
						self._scales.set_selected_modus(selected_modus)
						self._scales.set_key(root)
						self.update()

				else:
					if(y == 0):
						if x < 7 and self._quick_scales[x] != -1:
							self._scales.set_selected_modus(self._quick_scales[x])
							self._parent._parent.show_message("mode : "+str(self._scales._modus_names[self._scales._selected_modus]))
							self.update()
						if x == 7:
							self._quick_scale_root = not self._quick_scale_root
							if self._quick_scale_root:
								self._parent._parent.show_message("quick scale : root")
							else:
								self._parent._parent.show_message("quick scale : modes")
							self.update()
					if(y == 1):
						if x < 8 and self._quick_scales[x + 7] != -1:
							self._scales.set_selected_modus(self._quick_scales[x + 7])
							self._parent._parent.show_message("mode : "+str(self._scales._modus_names[self._scales._selected_modus]))
							self.update()

	def update(self):
		if self.is_enabled():
			if self._track_controller != None:
				self._track_controller.set_enabled(True)

			self._update_matrix()

			for button in self._remaining_buttons:
				button.set_on_off_values(LED_OFF, LED_OFF)
				button.turn_off()

			if self._scales_toggle_button != None:
				self._scales_toggle_button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
				self._scales_toggle_button.turn_off()

			if self._octave_up_button != None:
				self._octave_up_button.set_on_off_values(GREEN_FULL, GREEN_THIRD)
				if(self._can_scroll_octave_up()):
					self._octave_up_button.turn_on()
				else:
					self._octave_up_button.turn_off()

			if self._octave_down_button != None:
				self._octave_down_button.set_on_off_values(GREEN_FULL, GREEN_THIRD)
				if(self._can_scroll_octave_down()):
					self._octave_down_button.turn_on()
				else:
					self._octave_down_button.turn_off()

			self._update_OSD()

	def set_osd(self, osd):
		self._osd = osd

	def _update_OSD(self):
		if self._osd != None:
			if self._scales.is_quick_scale:
				self._osd.mode = "Instrument (quick scale)"
			else:
				self._osd.mode = "Instrument"
			self._osd.attributes[0] = MUSICAL_MODES[self._scales._selected_modus * 2]
			self._osd.attribute_names[0] = "Scale"
			self._osd.attributes[1] = KEY_NAMES[self._scales._selected_key % 12]
			self._osd.attribute_names[1] = "Root Note"
			self._osd.attributes[2] = self._scales._octave_index
			self._osd.attribute_names[2] = "Octave"
			self._osd.attributes[3] = " "
			self._osd.attribute_names[3] = " "
			self._osd.attributes[4] = " "
			self._osd.attribute_names[4] = " "
			self._osd.attributes[5] = " "
			self._osd.attribute_names[5] = " "
			self._osd.attributes[6] = " "
			self._osd.attribute_names[6] = " "
			self._osd.attributes[7] = " "
			self._osd.attribute_names[7] = " "

			if self.song().view.selected_track != None:
				self._osd.info[0] = "track : " + self.song().view.selected_track.name
			else:
				self._osd.info[0] = " "

			self._osd.info[1] = " "
			self._osd.update()

	def set_matrix(self, matrix):
		self._matrix = matrix
		if matrix:
			matrix.reset()
		if (matrix != self._matrix):
			if (self._matrix != None):
				self._matrix.remove_value_listener(self._matrix_value_quickscale)
		self._matrix = matrix
		if (self._matrix != None):
			self._matrix.add_value_listener(self._matrix_value_quickscale)
		self._update_matrix()

	def on_selected_track_changed(self):
		if self._track_controller._implicit_arm:
			self._get_drumrack_device()
			if self._drum_group_device != None:
				self._scales.set_drumrack(True)
			else:
				self._scales.set_drumrack(False)
			self.update()

	def _get_drumrack_device(self):
		if self.song().view.selected_track != None:
			track = self.song().view.selected_track
			if(track.devices != None and len(track.devices) > 0):
				#device = track.devices[0]
				device = self.find_drum_group_device(track)
				if(device != None and device.can_have_drum_pads and device.has_drum_pads):
					self._drum_group_device = device
				else:
					self._drum_group_device = None
			else:
				self._drum_group_device = None
		else:
			self._drum_group_device = None

	def find_drum_group_device(self, track):
		device = find_if(lambda d: d.type == Live.Device.DeviceType.instrument, track.devices)
		if device:
			if device.can_have_drum_pads:
				return device
			elif device.can_have_chains:
				return find_if(bool, imap(self.find_drum_group_device, device.chains))
		else:
			return None

	def _update_matrix(self):

		if not self.is_enabled() or not self._matrix or self._scales.is_enabled():
			self._parent._parent.release_controlled_track()
			# self._parent._parent.set_feedback_channels([])
		else:
			# feedback_channels = [self.base_channel, self.base_channel + 1, self.base_channel + 2, self.base_channel + 3]
			non_feedback_channel = self.base_channel + 4

			# create array to keep last channel used for note.
			note_channel = range(128)
			for i in range(128):
				note_channel[i] = self.base_channel

			# select drumrack device
			self._get_drumrack_device()

			if self._scales.is_drumrack() and not self._scales._is_diatonic and not self._scales._is_chromatic:
				if self._drum_group_device != None:
					self._scales.set_drumrack(True)
				else:
					self._scales.set_diatonic()

			for button, (x, y) in self._matrix.iterbuttons():
				button.use_default_message()
				button.set_channel(non_feedback_channel)
				button.force_next_send()

			if self._scales.is_drumrack():

				for button, (x, y) in self._matrix.iterbuttons():
					if button:
						note = 0
						if(x < 4):
							note = 12 * self._scales._octave_index + x + 4 * (7 - y)
						else:
							note = 12 * self._scales._octave_index + 32 + x - 4 + 4 * (7 - y)

						if note < 128 and note >= 0:
							if self._drum_group_device != None and self._drum_group_device.can_have_drum_pads and self._drum_group_device.has_drum_pads and self._drum_group_device.drum_pads[note].chains:
								button.set_on_off_values(RED_FULL, GREEN_THIRD)
								button.set_enabled(False)
								button.set_channel(self.base_channel)
								button.set_identifier(note)
							else:
								button.set_on_off_values(GREEN_FULL, LED_OFF)
								button.set_enabled(False)
								button.set_channel(self.base_channel)
								button.set_identifier(note)
						else:
							button.set_on_off_values(LED_OFF, LED_OFF)
							button.set_enabled(True)
							button.set_channel(non_feedback_channel)
						button.force_next_send()
						button.turn_off()

			else:
				if self._scales.is_quick_scale:
					quick_scale_root_button = self._matrix.get_button(7, 0)
					quick_scale_root_button.set_on_off_values(RED_THIRD, RED_FULL)
					quick_scale_root_button.set_enabled(True)
					quick_scale_root_button.force_next_send()
					if self._quick_scale_root:
						quick_scale_root_button.turn_on()
					else:
						quick_scale_root_button.turn_off()

					selected_modus = self._scales._selected_modus
					selected_key = self._scales._selected_key

					if self._quick_scale_root:
						if selected_modus == 0 or selected_modus == 12:
							off_color = AMBER_THIRD
							on_color = AMBER_FULL
							fifth_button_color = RED_THIRD
							mode_button_color = RED_THIRD
							relative_scale_button_color = RED_THIRD
						elif selected_modus == 1 or selected_modus == 11:
							off_color = RED_THIRD
							on_color = RED_FULL
							fifth_button_color = GREEN_THIRD
							mode_button_color = GREEN_THIRD
							relative_scale_button_color = GREEN_THIRD
						else:
							off_color = GREEN_THIRD
							on_color = GREEN_FULL
							fifth_button_color = RED_THIRD
							mode_button_color = RED_THIRD
							relative_scale_button_color = RED_THIRD

						# circle of 5th nav right
						button = self._matrix.get_button(7, 1)
						button.set_on_off_values(fifth_button_color, fifth_button_color)
						button.force_next_send()
						button.turn_on()
						# circle of 5th nav left
						button = self._matrix.get_button(6, 0)
						button.set_on_off_values(fifth_button_color, fifth_button_color)
						button.force_next_send()
						button.turn_on()
						# mode button
						button = self._matrix.get_button(7, 0)
						button.set_on_off_values(mode_button_color, mode_button_color)
						button.force_next_send()
						button.turn_on()
						# relative scale button
						button = self._matrix.get_button(2, 0)
						button.set_on_off_values(relative_scale_button_color, relative_scale_button_color)
						button.force_next_send()
						button.turn_on()

						for x in [0, 1, 3, 4, 5]:
							button = self._matrix.get_button(x, 0)
							button.set_enabled(True)
							button.set_on_off_values(on_color, off_color)
							button.force_next_send()
							if [0, 2, 4, 5, 7, 9, 11, 12][x] + 1 == selected_key:
								button.turn_on()
							else:
								button.turn_off()

						for x in [0, 1, 2, 3, 4, 5, 6]:
							button = self._matrix.get_button(x, 1)
							button.set_enabled(True)
							button.set_on_off_values(on_color, off_color)
							button.force_next_send()
							if [0, 2, 4, 5, 7, 9, 11, 12][x] == selected_key:
								button.turn_on()
							else:
								button.turn_off()
					else:
						for x in range(7):
							button = self._matrix.get_button(x, 0)
							button.set_enabled(True)
							if self._quick_scales[x] != -1:
								button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
							else:
								button.set_on_off_values(LED_OFF, LED_OFF)
							button.force_next_send()
							if self._quick_scales[x] == selected_modus:
								button.turn_on()
							else:
								button.turn_off()

						for x in range(8):
							button = self._matrix.get_button(x, 1)
							button.set_enabled(True)
							if self._quick_scales[x + 7] != -1:
								button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
							else:
								button.set_on_off_values(LED_OFF, LED_OFF)
							button.force_next_send()
							if self._quick_scales[x + 7] == selected_modus:
								button.turn_on()
							else:
								button.turn_off()

				interval = self._scales._presets.interval
				pattern = self._get_pattern(interval)
				max_j = self._matrix.width() - 1
				for button, (i, j) in self._matrix.iterbuttons():
					if button and (not self._scales.is_quick_scale or j > 1):
						note_info = pattern.note(i, max_j - j)
						if note_info.index != None:
							button.set_on_off_values(RED_FULL, note_info.color)
							button.set_enabled(False)
							button.set_channel(note_channel[note_info.index])
							# comment the line above and use the one below if you want instrument controller to use one channel instead of 3
							# button.set_channel(note_channel[0])
							button.set_identifier(note_info.index)
							note_channel[note_info.index] = note_channel[note_info.index] + 1
						else:
							button.set_channel(non_feedback_channel)
							button.set_on_off_values(LED_OFF, LED_OFF)
							button.set_light(note_info.color)
							button.set_enabled(True)
						button.force_next_send()
						button.turn_off()

			for button in self._side_buttons:
				button.use_default_message()
				button.set_channel(non_feedback_channel)
				button.set_enabled(True)
				button.force_next_send()

			self._parent._config_button.send_value(32)

	def _get_pattern(self, interval):
		if(self._scales.is_drumrack()):
			pass
		else:
			# notes
			notes = self._scales.notes

			# origin
			if not self._scales.is_absolute:
				origin = 0
			elif self._scales.is_diatonic():
				origin = 0
				for k in xrange(len(notes)):
					if notes[k] >= 12:
						origin = k - len(notes)
						break
			else:
				origin = -notes[0]

			# interval
			if interval == None:
				interval = 8
			elif self._scales.is_chromatic():
				interval = [0, 2, 4, 5, 7, 9, 10, 11][interval]
			else:
				interval = interval
			# self._parent.log_message("interval:"+str(interval))

			# layout
			if self._scales._presets.is_horizontal:
				steps = [1, interval]
				origin = [origin, 0]
			else:
				steps = [interval, 1]
				origin = [0, origin]

			return MelodicPattern(steps=steps, scale=notes, origin=origin, base_note=self._scales._octave_index * 12, base_note_color=self._scales.get_base_note_color(), scale_note_color=self._scales.get_scale_note_color(), scale_highlight_color=self._scales.get_scale_highlight_color(), chromatic_mode=self._scales.is_chromatic(), chromatic_gtr_mode=self._scales.is_chromatic_gtr(), diatonic_ns_mode=self._scales.is_diatonic_ns())


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry
} from 'react-native';

import NavigatorComponent from './js/NavigatorComponent';

AppRegistry.registerComponent('RN_Coursera', () => NavigatorComponent);


text:
package com.getperka.flatpack.client.impl;

import java.util.Collections;
import java.util.Set;

import com.getperka.flatpack.BaseHasUuid;
import com.getperka.flatpack.PersistenceAware;
import com.getperka.flatpack.PostUnpack;
import com.getperka.flatpack.collections.DirtyFlag;
import com.getperka.flatpack.util.FlatPackCollections;

/**
 * A base type for generated model types.
 */
public class BasePersistenceAware extends BaseHasUuid implements PersistenceAware {
  private final Set<String> dirtyProperties = FlatPackCollections.setForIteration();
  private boolean persistent;

  @Override
  public Set<String> dirtyPropertyNames() {
    return Collections.unmodifiableSet(dirtyProperties);
  }

  @Override
  public void markPersistent() {
    persistent = true;
    dirtyProperties.clear();
  }

  @Override
  public boolean wasPersistent() {
    return persistent;
  }

  protected DirtyFlag dirtyFlag(String propertyName) {
    return new DirtyFlag(dirtyProperties, propertyName);
  }

  @PostUnpack
  void postUnpack() {
    dirtyProperties.clear();
  }
}


text:
using System;
using Gos.SimpleObjectStore;

namespace BooksCollector.Core
{
    public class Book : IEntity
    {
        public string Author { get; set; }
        public string Title { get; set; }
        public string Isbn { get; set; }

        public override bool Equals(object obj)
        {
            if(!(obj is Book)) return false;
            return Isbn.Equals(((Book)obj).Isbn);
        }

        public override int GetHashCode()
        {
            return Isbn.GetHashCode();
        }

        public override string ToString()
        {
            return String.Format("[{0}]", Isbn);
        }
    }
}


text:
package com.skyrocketgwt.demo.client.widgets;

import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.ui.*;
import com.skyrocketgwt.core.client.layouts.layoutpanel.SkyHorizontalPanel;
import com.skyrocketgwt.core.client.layouts.layoutpanel.SkyVerticalPanel;
import com.skyrocketgwt.core.client.widgets.SkyButton;
import com.skyrocketgwt.core.client.widgets.SkyPushButton;
import com.skyrocketgwt.core.client.widgets.appearance.DefaultSkyButtonAppearance;
import com.skyrocketgwt.demo.client.resources.code.CodeResources;
import com.skyrocketgwt.demo.client.widgets.exampleimages.ExampleImages;
import com.skyrocketgwt.demo.client.widgets.images.ImageResources;

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

/**
 * Created by v on 07/04/2015.
 */
public class SkyPushButtonDemo extends AbstractWidget {

    private final boolean isSky;

    public SkyPushButtonDemo(boolean isSky) {
        this.isSky = isSky;
    }

    @Override
    public Widget getWidgetDemo() {
        return isSky ? createSky() : createGwt();
    }

    private Widget createGwt() {
        SimplePanel panel = new SimplePanel();

        PushButton button = new PushButton(getWidgetDescription());
        panel.add(button);

        return panel;
    }

    private Widget createSky() {
        SkyVerticalPanel vpanel = new SkyVerticalPanel();

        SkyVerticalPanel pushPanel = new SkyVerticalPanel();
        pushPanel.setSpacing(10);
        vpanel.add(pushPanel);

        SkyPushButton button = new SkyPushButton(getWidgetDescription());
        SkyPushButton imgButton = new SkyPushButton(new Image(ExampleImages.INSTANCE.tux()));

        pushPanel.add(new Label("Push Button:"));
        pushPanel.add(button);
        pushPanel.add(new HTML("<br>"));
        pushPanel.add(new Label("Image Push Button:"));
        pushPanel.add(imgButton);

        return vpanel;
    }

    @Override
    public List<TextResource> getSourceList(CodeResources resources) {
        List<TextResource> sourceList = new ArrayList<TextResource>();
        sourceList.add(resources.skyPushButtonDemo_java());
        return sourceList;
    }

    @Override
    public String getWidgetDescription() {
        return isSky ? "SkyPushButton" : "GWT PushButton";
    }

    @Override
    public String getSourceCode() {
        return null;
    }

    @Override
    public String getCSS() {
        return null;
    }

    @Override
    public ImageResource getImageResource(ImageResources resources) {
        return resources.skyPushButton();
    }

    @Override
    public ImageResource getInactiveImageResource(ImageResources resources) {
        return resources.skyPushButtonBW();
    }
}


text:
<!--

    Copyright (C) 2015 Lable (info@lable.nl)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.lable.oss.dynamicconfig</groupId>
    <artifactId>dynamicconfig</artifactId>
    <version>3.2-SNAPSHOT</version>
  </parent>

  <groupId>org.lable.oss.dynamicconfig.serialization</groupId>
  <artifactId>dynamic-config-serialization-json</artifactId>
  <version>3.2-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Dynamic configuration :: JSON serialization</name>

  <dependencies>
    <dependency>
      <groupId>org.lable.oss.dynamicconfig</groupId>
      <artifactId>dynamic-config-core</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <!-- Testing dependencies. -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
exports.abc = function abc(def, ghi) {
//


text:
package org.pentaho.hadoop.shim.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.List;
import java.util.Properties;

import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.impl.util.PropertiesUtil;
import org.apache.pig.tools.grunt.GruntParser;
import org.apache.pig.tools.parameters.ParameterSubstitutionPreprocessor;
import org.apache.pig.tools.parameters.ParseException;
import org.pentaho.hadoop.shim.ShimVersion;
import org.pentaho.hadoop.shim.api.Configuration;
import org.pentaho.hadoop.shim.spi.PigShim;

public class CommonPigShim implements PigShim {
  private static final String[] EMPTY_STRING_ARRAY = new String[0];

  @Override
  public ShimVersion getVersion() {
    return new ShimVersion(1, 0);
  }

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

  @Override
  public void configure(Properties properties, Configuration configuration) {
    PropertiesUtil.loadDefaultProperties(properties);
    if (configuration != null) {
      properties.putAll(ConfigurationUtil.toProperties(ShimUtils.asConfiguration(configuration)));
    }
  }

  @Override
  public String substituteParameters(URL pigScript, List<String> paramList) throws IOException, ParseException {
    final InputStream inStream = pigScript.openStream();
    StringWriter writer = new StringWriter();
    // do parameter substitution
    ParameterSubstitutionPreprocessor psp = new ParameterSubstitutionPreprocessor(50);
    psp.genSubstitutedFile(new BufferedReader(new InputStreamReader(inStream)),
                           writer,
                           paramList.size() > 0 ? paramList.toArray(EMPTY_STRING_ARRAY) : null, null);
    return writer.toString();
  }

  /**
   * Convert {@link ExecutionMode} to {@link ExecType}
   *
   * @param mode Execution mode
   * @return Type of execution for mode
   */
  protected ExecType getExecType(ExecutionMode mode) {
    switch(mode) {
      case LOCAL:
        return ExecType.LOCAL;
      case MAPREDUCE:
        return ExecType.MAPREDUCE;
      default:
        throw new IllegalStateException("unknown execution mode: " + mode);
    }
  }

  @Override
  public int[] executeScript(String pigScript, ExecutionMode mode, Properties properties) throws IOException, org.apache.pig.tools.pigscript.parser.ParseException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {
      PigServer pigServer = new PigServer(getExecType(mode), properties);
      GruntParser grunt = new GruntParser(new StringReader(pigScript));
      grunt.setInteractive(false);
      grunt.setParams(pigServer);
      return grunt.parseStopOnError(false);
    } finally {
      Thread.currentThread().setContextClassLoader(cl);
    }
  }
}


text:
- Fixed `no-empty-blocks` to not report inherited constructors with empty blocks ([#264](https://github.com/duaraghav8/Ethlint/issues/264#issue-447647594)).
- Added option `errorMessageMaxLength` for rule `error-reason` to specify a character limit on error message.

## 1.2.4 (2019-04-08)
- Added rule `no-trailing-whitespace` to warn the user when code, comment or blank lines contain trailing whitespaces. This rule will supply the `fix` functionality in a future release.
- Added `getLines()` sourceCode utility function for rule developers. This method returns the source code split into lines.
- Added `getComments()` sourceCode utility function for rule developers. This method returns a list of AST Nodes representing comments in the source code.

## 1.2.3 (2019-02-11)
- Added support for `solium-disable-previous-line` comment directive.
- Added support for `solium-enable` comment directive. See [configuring with comments](https://ethlint.readthedocs.io/en/latest/user-guide.html#configuring-with-comments). This feature currently has a limitation which has been documented in [Known Issues](https://ethlint.readthedocs.io/en/latest/known-issues.html).
- Added Pull Request template.
- Fixed rule `no-empty-blocks` to report function declarations with empty bodies. Fallback and `payable` functions and `payable` constructors are not reported if their body is empty. See [#254](https://github.com/duaraghav8/Ethlint/issues/254).
- Fixed rule `quotes` to stop reporting false positives due to brackets enclosing strings (see [#240](https://github.com/duaraghav8/Ethlint/issues/240)).
- Modified rule `uppercase` to allow up to 2 leading and trailing underscores for a constant's name.

## 1.2.2 (2019-01-13)
- Added support for parsing function declarations inside Inline Assembly blocks.
- Added Issue Templates to the repository for Bug report, Feature request and Lint rule suggestion.
- Added Contribution guidelines.
- Changed `.soliumignore`-related warning messages to be more user-friendly.
- Fixed bugs in parser related to Inline Assembly variable declaration.
- Fixed `uppercase` rule to allow single-character names, where the character must be an alphabet.
- Fixed `indentation` rule to allow Call expression arguments to start with circular bracket ([#223](https://github.com/duaraghav8/Ethlint/issues/223)).
- Fixed `BinaryExpression` position bug in parser that led to [#175](https://github.com/duaraghav8/Ethlint/issues/175) & [#223](https://github.com/duaraghav8/Ethlint/issues/223).

## 1.2.1 (2019-01-01) :sparkler:
- Added `fix` functionality to `linebreak-style` rule.
- Added `linebreak-style` rule configuration to default `.soliumrc.json`.
- Added support for tilde for specifying version literals in `pragma` statements.
- Added rule `constructor` to warn the user when the deprecated style of constructor declaration is being used.
- Added `--fix-dry-run` option to CLI to allow users to see a git-style diff of the changes the `--fix` option will make.
- Fixed Hex literal parsing. Incorrect parsing caused the linter to crash in some [cases](https://github.com/duaraghav8/Ethlint/issues/232).
- Fixed source code util's `getTextOnLine()` to account for both linebreak-styles on both platforms (see [issue](https://github.com/duaraghav8/Ethlint/issues/173))
- Changed documentation URL to [ethlint.readthedocs.io](https://ethlint.readthedocs.io). `solium.readthedocs.io` is deprecated but will receive updates.
- Moved deprecated rules in documentation into their own section.

## 1.2.0 (2018-12-25) :santa:
- Deprecated the npm package `solium`. All updates will be pushed simultaneously to npm packages `solium` and `ethlint`. There is no difference between the software being pushed to these packages, but it is highly recommended that you move to the `ethlint` npm package.
- Added Changelog
- Added syntax support for Solidity `0.5`.
- Added `ignore` option for `function-order` rule (See [issue](https://github.com/duaraghav8/Ethlint/issues/235))
- Added file name in addition to stack trace in the output of `--debug` option.
- Fixed the ignore feature to account for windows line endings in `.soliumignore` file. (Thanks to @romaric-juniet)
- Fixed documentation errors.


text:
import unittest

from vtkVgCorePython import vtkVgTimeStamp

class TestTimeStamp(unittest.TestCase):
  def testConstruction(self):
    # Constructing with time only
    t1 = vtkVgTimeStamp(123456.0)
    self.assertTrue(t1.IsValid())
    self.assertTrue(t1.HasTime())
    self.assertFalse(t1.HasFrameNumber())
    self.assertEqual(t1.GetTime(), 123456.0)
    # Constructing with time and frame number
    t2 = vtkVgTimeStamp(123456.0, 42)
    self.assertTrue(t2.IsValid())
    self.assertTrue(t2.HasTime())
    self.assertTrue(t2.HasFrameNumber())
    self.assertEqual(t2.GetTime(), 123456.0)
    self.assertEqual(t2.GetFrameNumber(), 42)
    # Constructing minimum time
    tmin = vtkVgTimeStamp(False)
    tmax = vtkVgTimeStamp(True)
    self.assertTrue(tmin.IsMinTime())
    self.assertTrue(tmax.IsMaxTime())

  def testTime(self):
    t = vtkVgTimeStamp()
    # Test initial state
    self.assertFalse(t.IsValid())
    self.assertFalse(t.HasTime())
    # Test setting and getting time
    t.SetTime(123456.0)
    self.assertTrue(t.IsValid())
    self.assertTrue(t.HasTime())
    self.assertEqual(t.GetTime(), 123456.0)

  def testFrameNumber(self):
    t = vtkVgTimeStamp()
    # Test initial state
    self.assertFalse(t.IsValid())
    self.assertFalse(t.HasFrameNumber())
    # Test setting and getting frame number
    t.SetFrameNumber(42)
    self.assertTrue(t.IsValid())
    self.assertTrue(t.HasFrameNumber())
    self.assertEqual(t.GetFrameNumber(), 42)

  def testMinMax(self):
    t = vtkVgTimeStamp()
    self.assertFalse(t.IsValid())
    t.SetToMinTime()
    self.assertTrue(t.IsMinTime())
    t.SetToMaxTime()
    self.assertTrue(t.IsMaxTime())

  def testReset(self):
    t = vtkVgTimeStamp(0.0, 0);
    self.assertTrue(t.IsValid())
    self.assertTrue(t.HasTime())
    self.assertTrue(t.HasFrameNumber())
    t.Reset()
    self.assertFalse(t.IsValid())
    self.assertFalse(t.HasTime())
    self.assertFalse(t.HasFrameNumber())

if __name__ == "__main__":
    unittest.main()


text:
module APN
  # Encapsulates the logic necessary to convert an iPhone token and an array of options into a string of the format required
  # by Apple's servers to send the notification.  Much of the processing code here copied with many thanks from
  # http://github.com/samsoffes/apple_push_notification/blob/master/lib/apple_push_notification.rb
  #
  # APN::Notification.new's first argument is the token of the iPhone which should receive the notification.  The second argument
  # is a hash with any of :alert, :badge, and :sound keys. All three accept string arguments, while :sound can also be set to +true+
  # to play the default sound installed with the application. At least one of these keys must exist.  Any other keys are merged into
  # the root of the hash payload ultimately sent to the iPhone:
  #
  #   APN::Notification.new(token, {:alert => 'Stuff', :custom => {:code => 23}})
  #   # Writes this JSON to servers: {"aps" => {"alert" => "Stuff"}, "custom" => {"code" => 23}}
  #
  # As a shortcut, APN::Notification.new also accepts a string as the second argument, which it converts into the alert to send.  The
  # following two lines are equivalent:
  #
  #   APN::Notification.new(token, 'Some Alert')
  #   APN::Notification.new(token, {:alert => 'Some Alert'})
  #
  class Notification
    # Available to help clients determine before they create the notification if their message will be too large.
    # Each iPhone Notification payload must be 256 or fewer characters (not including the token or other push data), see Apple specs at:
    # https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW4
    DATA_MAX_BYTES = 255

    attr_accessor :options, :token
    def initialize(token, opts)
      @options = opts.is_a?(Hash) ? opts.symbolize_keys : {:alert => opts}
      @token = token

      raise "The maximum size allowed for a notification payload is #{DATA_MAX_BYTES} bytes." if payload_size > DATA_MAX_BYTES
    end

    def to_s
      packaged_notification
    end

    def payload_size
      packaged_message.bytesize
    end

    # Ensures at least one of <code>%w(alert badge sound)</code> is present
    def valid?
      return true if [:alert, :badge, :sound].any?{|key| options.keys.include?(key) }
      false
    end

    # Completed encoded notification, ready to send down the wire to Apple
    def packaged_notification
      pt = packaged_token
      pm = packaged_message
      [0, 0, 32, pt, 0, payload_size, pm].pack("ccca*cca*")
    end

    # Device token, compressed and hex-ified
    def packaged_token
      [@token.gsub(/[\s|<|>]/,'')].pack('H*')
    end

    # Converts the supplied options into the JSON needed for Apple's push notification servers.
    # Extracts :alert, :badge, :sound and :category keys into the 'aps' hash, merges any other hash data
    # into the root of the hash to encode and send to apple.
    def packaged_message
      @packaged_message ||=
        begin
          opts = @options.dup
          hsh = {'aps' => {}}
          if alert = opts.delete(:alert)
            alert = alert.to_s unless alert.is_a?(Hash)
            hsh['aps']['alert'] = alert
          end
          hsh['aps']['badge'] = opts.delete(:badge).to_i if opts[:badge]
          hsh['aps']['category'] = opts.delete(:category).to_s if opts[:category]
          if sound = opts.delete(:sound)
            hsh['aps']['sound'] = sound.is_a?(TrueClass) ? 'default' : sound.to_s
          end
          if content_available = opts.delete(:content_available)
            hsh['aps']['content-available'] = 1 if [1,true].include? content_available
          end
          hsh.merge!(opts)
          payload(hsh)
        end
    end

    private

      def payload(hash)
        str = ActiveSupport::JSON::encode(hash)

        if APN.truncate_alert && str.bytesize > DATA_MAX_BYTES
          if hash['aps']['alert'].is_a?(Hash)
            alert = hash['aps']['alert']['loc-args'][0]
          else
            alert = hash['aps']['alert']
          end
          max_bytesize = DATA_MAX_BYTES - (str.bytesize - alert.bytesize)

          raise "Even truncating the alert won't be enough to have a #{DATA_MAX_BYTES} message" if max_bytesize <= 0
          alert = truncate_alert(alert, max_bytesize)

          if hash['aps']['alert'].is_a?(Hash)
            hash['aps']['alert']['loc-args'][0] = alert
          else
            hash['aps']['alert'] = alert
          end
          str = ActiveSupport::JSON::encode(hash)
        end
        str
      end

      def truncate_alert(alert, max_size)
        alert.each_char.each_with_object('') do |char, result|
          if result.bytesize + char.bytesize > max_size
            break result
          else
            result << char
          end
        end
      end

  end
end


text:
;(function() {
  'use strict';

  sigma.utils.pkg('sigma.canvas.edges');

  /**
   * The default edge renderer. It renders the edge as a simple line.
   *
   * @param  {object}                   edge         The edge object.
   * @param  {object}                   source node  The edge source node.
   * @param  {object}                   target node  The edge target node.
   * @param  {CanvasRenderingContext2D} context      The canvas context.
   * @param  {configurable}             settings     The settings function.
   */
  sigma.canvas.edges.def = function(edge, source, target, context, settings) {
    var color = edge.color,
        prefix = settings('prefix') || '',
        edgeColor = settings('edgeColor'),
        defaultNodeColor = settings('defaultNodeColor'),
        defaultEdgeColor = settings('defaultEdgeColor');

    if (!color)
      switch (edgeColor) {
        case 'source':
          color = source.color || defaultNodeColor;
          break;
        case 'target':
          color = target.color || defaultNodeColor;
          break;
        default:
          color = defaultEdgeColor;
          break;
      }

    context.strokeStyle = color;
    context.lineWidth = edge[prefix + 'size'] || 1;
    context.beginPath();
    context.moveTo(
      source[prefix + 'x'],
      source[prefix + 'y']
    );
    context.lineTo(
      target[prefix + 'x'],
      target[prefix + 'y']
    );
    context.stroke();

    if (settings('drawEdgeLabels'))
      sigma.canvas.labels.edges.def(
        edge,
        source,
        target,
        context,
        settings
    );
  };
})();


text:
package org.elasticsearch.index.rankeval;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.script.Script;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

/**
 * Specification of the ranking evaluation request.<br>
 * This class groups the queries to evaluate, including their document ratings,
 * and the evaluation metric including its parameters.
 */
public class RankEvalSpec implements Writeable, ToXContentObject {
    /** List of search request to use for the evaluation */
    private final List<RatedRequest> ratedRequests;
    /** Definition of the quality metric, e.g. precision at N */
    private final EvaluationMetric metric;
    /** Maximum number of requests to execute in parallel. */
    private int maxConcurrentSearches = MAX_CONCURRENT_SEARCHES;
    /** Default max number of requests. */
    private static final int MAX_CONCURRENT_SEARCHES = 10;
    /** optional: Templates to base test requests on */
    private final Map<String, Script> templates = new HashMap<>();

    public RankEvalSpec(List<RatedRequest> ratedRequests, EvaluationMetric metric, Collection<ScriptWithId> templates) {
        this.metric = Objects.requireNonNull(metric, "Cannot evaluate ranking if no evaluation metric is provided.");
        if (ratedRequests == null || ratedRequests.isEmpty()) {
            throw new IllegalArgumentException(
                    "Cannot evaluate ranking if no search requests with rated results are provided. Seen: " + ratedRequests);
        }
        this.ratedRequests = ratedRequests;
        if (templates == null || templates.isEmpty()) {
            for (RatedRequest request : ratedRequests) {
                if (request.getEvaluationRequest() == null) {
                    throw new IllegalStateException("Cannot evaluate ranking if neither template nor evaluation request is "
                            + "provided. Seen for request id: " + request.getId());
                }
            }
        }
        if (templates != null) {
            for (ScriptWithId idScript : templates) {
                this.templates.put(idScript.id, idScript.script);
            }
        }
    }

    public RankEvalSpec(List<RatedRequest> ratedRequests, EvaluationMetric metric) {
        this(ratedRequests, metric, null);
    }

    public RankEvalSpec(StreamInput in) throws IOException {
        int specSize = in.readVInt();
        ratedRequests = new ArrayList<>(specSize);
        for (int i = 0; i < specSize; i++) {
            ratedRequests.add(new RatedRequest(in));
        }
        metric = in.readNamedWriteable(EvaluationMetric.class);
        int size = in.readVInt();
        for (int i = 0; i < size; i++) {
            String key = in.readString();
            Script value = new Script(in);
            this.templates.put(key, value);
        }
        maxConcurrentSearches = in.readVInt();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVInt(ratedRequests.size());
        for (RatedRequest spec : ratedRequests) {
            spec.writeTo(out);
        }
        out.writeNamedWriteable(metric);
        out.writeVInt(templates.size());
        for (Entry<String, Script> entry : templates.entrySet()) {
            out.writeString(entry.getKey());
            entry.getValue().writeTo(out);
        }
        out.writeVInt(maxConcurrentSearches);
    }

    /** Returns the metric to use for quality evaluation.*/
    public EvaluationMetric getMetric() {
        return metric;
    }

    /** Returns a list of intent to query translation specifications to evaluate. */
    public List<RatedRequest> getRatedRequests() {
        return Collections.unmodifiableList(ratedRequests);
    }

    /** Returns the template to base test requests on. */
    public Map<String, Script> getTemplates() {
        return this.templates;
    }

    /** Returns the max concurrent searches allowed. */
    public int getMaxConcurrentSearches() {
        return this.maxConcurrentSearches;
    }

    /** Set the max concurrent searches allowed. */
    public void setMaxConcurrentSearches(int maxConcurrentSearches) {
        this.maxConcurrentSearches = maxConcurrentSearches;
    }

    private static final ParseField TEMPLATES_FIELD = new ParseField("templates");
    private static final ParseField METRIC_FIELD = new ParseField("metric");
    private static final ParseField REQUESTS_FIELD = new ParseField("requests");
    private static final ParseField MAX_CONCURRENT_SEARCHES_FIELD = new ParseField("max_concurrent_searches");
    @SuppressWarnings("unchecked")
    private static final ConstructingObjectParser<RankEvalSpec, Void> PARSER = new ConstructingObjectParser<>("rank_eval",
            a -> new RankEvalSpec((List<RatedRequest>) a[0], (EvaluationMetric) a[1], (Collection<ScriptWithId>) a[2]));

    static {
        PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), (p, c) -> RatedRequest.fromXContent(p), REQUESTS_FIELD);
        PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> parseMetric(p), METRIC_FIELD);
        PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> ScriptWithId.fromXContent(p),
                TEMPLATES_FIELD);
        PARSER.declareInt(RankEvalSpec::setMaxConcurrentSearches, MAX_CONCURRENT_SEARCHES_FIELD);
    }

    private static EvaluationMetric parseMetric(XContentParser parser) throws IOException {
        XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
        XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, parser.nextToken(), parser::getTokenLocation);
        EvaluationMetric metric = parser.namedObject(EvaluationMetric.class, parser.currentName(), null);
        XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, parser.nextToken(), parser::getTokenLocation);
        return metric;
    }

    public static RankEvalSpec parse(XContentParser parser) {
        return PARSER.apply(parser, null);
    }

    static class ScriptWithId {
        private Script script;
        private String id;

        private static final ParseField TEMPLATE_FIELD = new ParseField("template");
        private static final ParseField TEMPLATE_ID_FIELD = new ParseField("id");

        ScriptWithId(String id, Script script) {
            this.id = id;
            this.script = script;
        }

        private static final ConstructingObjectParser<ScriptWithId, Void> PARSER =
                new ConstructingObjectParser<>("script_with_id",
                        a -> new ScriptWithId((String) a[0], (Script) a[1]));

        public static ScriptWithId fromXContent(XContentParser parser) {
            return PARSER.apply(parser, null);
        }

        static {
            PARSER.declareString(ConstructingObjectParser.constructorArg(), TEMPLATE_ID_FIELD);
            PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> {
                try {
                    return Script.parse(p, "mustache");
                } catch (IOException ex) {
                    throw new ParsingException(p.getTokenLocation(), "error parsing rank request", ex);
                }
            }, TEMPLATE_FIELD);
        }
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.startArray(TEMPLATES_FIELD.getPreferredName());
        for (Entry<String, Script> entry : templates.entrySet()) {
            builder.startObject();
            builder.field(ScriptWithId.TEMPLATE_ID_FIELD.getPreferredName(), entry.getKey());
            builder.field(ScriptWithId.TEMPLATE_FIELD.getPreferredName(), entry.getValue());
            builder.endObject();
        }
        builder.endArray();

        builder.startArray(REQUESTS_FIELD.getPreferredName());
        for (RatedRequest spec : this.ratedRequests) {
            spec.toXContent(builder, params);
        }
        builder.endArray();
        builder.field(METRIC_FIELD.getPreferredName(), this.metric);
        builder.field(MAX_CONCURRENT_SEARCHES_FIELD.getPreferredName(), maxConcurrentSearches);
        builder.endObject();
        return builder;
    }

    @Override
    public String toString() {
        return Strings.toString(this);
    }

    @Override
    public final boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        RankEvalSpec other = (RankEvalSpec) obj;

        return Objects.equals(ratedRequests, other.ratedRequests) &&
                Objects.equals(metric, other.metric) &&
                Objects.equals(maxConcurrentSearches, other.maxConcurrentSearches) &&
                Objects.equals(templates, other.templates);
    }

    @Override
    public final int hashCode() {
        return Objects.hash(ratedRequests, metric, templates, maxConcurrentSearches);
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="550dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:fitsSystemWindows="true"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/intro"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="25dp"
        android:textSize="18sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MindMe/AlarmPad Extensions API"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="https://github.com/riclage/mindme_extensions_api"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SystemBarTint"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:linksClickable="true"
            android:text="https://github.com/jgilfelt/SystemBarTint"
            android:textSize="16sp" />
    </LinearLayout>

</LinearLayout>


text:
/**
 */
package CIM15.IEC61970.Informative.InfOperations;

import CIM15.IEC61968.Common.Document;

import CIM15.IEC61968.Customers.Customer;

import CIM15.IEC61970.Outage.OutageSchedule;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.util.BasicInternalEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * A representation of the model object 'Planned Outage'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getKind Kind}

 *
{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getCustomerDatas Customer Datas}

 *
{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getOutageSchedules Outage Schedules}

 *

 *

 *
 * @generated
 */
public class PlannedOutage extends Document {
	/**
	 * The default value of the '{@link #getKind() Kind}' attribute.
	 *
	 *
	 * @see #getKind()
	 * @generated
	 * @ordered
	 */
	protected static final OutageKind KIND_EDEFAULT = OutageKind.FIXED;

	/**
	 * The cached value of the '{@link #getKind() Kind}' attribute.
	 *
	 *
	 * @see #getKind()
	 * @generated
	 * @ordered
	 */
	protected OutageKind kind = KIND_EDEFAULT;

	/**
	 * This is true if the Kind attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean kindESet;

	/**
	 * The cached value of the '{@link #getCustomerDatas() Customer Datas}' reference list.
	 *
	 *
	 * @see #getCustomerDatas()
	 * @generated
	 * @ordered
	 */
	protected EList<Customer> customerDatas;

	/**
	 * The cached value of the '{@link #getOutageSchedules() Outage Schedules}' reference list.
	 *
	 *
	 * @see #getOutageSchedules()
	 * @generated
	 * @ordered
	 */
	protected EList<OutageSchedule> outageSchedules;

	/**
	 *
	 *
	 * @generated
	 */
	protected PlannedOutage() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InfOperationsPackage.Literals.PLANNED_OUTAGE;
	}

	/**
	 * Returns the value of the 'Kind' attribute.
	 * The literals are from the enumeration {@link CIM15.IEC61970.Informative.InfOperations.OutageKind}.
	 *
	 *

	 * If the meaning of the 'Kind' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Kind' attribute.
	 * @see CIM15.IEC61970.Informative.InfOperations.OutageKind
	 * @see #isSetKind()
	 * @see #unsetKind()
	 * @see #setKind(OutageKind)
	 * @generated
	 */
	public OutageKind getKind() {
		return kind;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getKind Kind}' attribute.
	 *
	 *
	 * @param value the new value of the 'Kind' attribute.
	 * @see CIM15.IEC61970.Informative.InfOperations.OutageKind
	 * @see #isSetKind()
	 * @see #unsetKind()
	 * @see #getKind()
	 * @generated
	 */
	public void setKind(OutageKind newKind) {
		kind = newKind == null ? KIND_EDEFAULT : newKind;
		kindESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getKind Kind}' attribute.
	 *
	 *
	 * @see #isSetKind()
	 * @see #getKind()
	 * @see #setKind(OutageKind)
	 * @generated
	 */
	public void unsetKind() {
		kind = KIND_EDEFAULT;
		kindESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61970.Informative.InfOperations.PlannedOutage#getKind Kind}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Kind' attribute is set.
	 * @see #unsetKind()
	 * @see #getKind()
	 * @see #setKind(OutageKind)
	 * @generated
	 */
	public boolean isSetKind() {
		return kindESet;
	}

	/**
	 * Returns the value of the 'Customer Datas' reference list.
	 * The list contents are of type {@link CIM15.IEC61968.Customers.Customer}.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Customers.Customer#getPlannedOutage Planned Outage}'.
	 *
	 *

	 * If the meaning of the 'Customer Datas' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Customer Datas' reference list.
	 * @see CIM15.IEC61968.Customers.Customer#getPlannedOutage
	 * @generated
	 */
	public EList<Customer> getCustomerDatas() {
		if (customerDatas == null) {
			customerDatas = new BasicInternalEList<Customer>(Customer.class);
		}
		return customerDatas;
	}

	/**
	 * Returns the value of the 'Outage Schedules' reference list.
	 * The list contents are of type {@link CIM15.IEC61970.Outage.OutageSchedule}.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Outage.OutageSchedule#getPlannedOutage Planned Outage}'.
	 *
	 *

	 * If the meaning of the 'Outage Schedules' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Outage Schedules' reference list.
	 * @see CIM15.IEC61970.Outage.OutageSchedule#getPlannedOutage
	 * @generated
	 */
	public EList<OutageSchedule> getOutageSchedules() {
		if (outageSchedules == null) {
			outageSchedules = new BasicInternalEList<OutageSchedule>(OutageSchedule.class);
		}
		return outageSchedules;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getCustomerDatas()).basicAdd(otherEnd, msgs);
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getOutageSchedules()).basicAdd(otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				return ((InternalEList<?>)getCustomerDatas()).basicRemove(otherEnd, msgs);
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				return ((InternalEList<?>)getOutageSchedules()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__KIND:
				return getKind();
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				return getCustomerDatas();
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				return getOutageSchedules();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__KIND:
				setKind((OutageKind)newValue);
				return;
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				getCustomerDatas().clear();
				getCustomerDatas().addAll((Collection<? extends Customer>)newValue);
				return;
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				getOutageSchedules().clear();
				getOutageSchedules().addAll((Collection<? extends OutageSchedule>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__KIND:
				unsetKind();
				return;
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				getCustomerDatas().clear();
				return;
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				getOutageSchedules().clear();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case InfOperationsPackage.PLANNED_OUTAGE__KIND:
				return isSetKind();
			case InfOperationsPackage.PLANNED_OUTAGE__CUSTOMER_DATAS:
				return customerDatas != null && !customerDatas.isEmpty();
			case InfOperationsPackage.PLANNED_OUTAGE__OUTAGE_SCHEDULES:
				return outageSchedules != null && !outageSchedules.isEmpty();
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (kind: ");
		if (kindESet) result.append(kind); else result.append("<unset>");
		result.append(')');
		return result.toString();
	}

} // PlannedOutage


text:
/*globals describe it beforeEach afterEach */
"use strict";

const should = require("should");
const LinkResolver = require("../lib/LinkResolver");

describe("LinkResolver", () => {
	it("should not throw when a path resolves with ENOENT", () => {
		const resolver = new LinkResolver();
		const result = resolver.resolve("/path/to/nonexistent/file/or/folder");
		should.exist(result);
	});
});


text:
<?php

namespace Article\InterfaceSegregation\Step1;

class ParamsMissingException extends \Exception
{

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using Xunit.Sdk;

namespace Xunit
{
    [Flags]
    public enum PlatformID
    {
        Windows = 1,
        Linux = 2,
        OSX = 4,
        FreeBSD = 8,
        AnyUnix = FreeBSD | Linux | OSX,
        Any = ~0
    }
}


text:
using v8::Integer;

NAN_METHOD(WrappedRE2::Search) {

	// unpack arguments

	WrappedRE2* re2 = Nan::ObjectWrap::Unwrap<WrappedRE2>(info.This());
	if (!re2) {
		info.GetReturnValue().Set(-1);
		return;
	}

	StrVal a(info[0]);

	// actual work

	StringPiece match;

	if (re2->regexp.Match(a, 0, a.size, RE2::UNANCHORED, &match, 1)) {
		info.GetReturnValue().Set(static_cast<int>(a.isBuffer ? match.data() - a.data :
			getUtf16Length(a.data, match.data())));
		return;
	}

	info.GetReturnValue().Set(-1);
}


text:
package git4idea.actions;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitUtil;
import git4idea.commands.GitLineHandler;
import git4idea.commands.GitTask;
import git4idea.commands.GitTaskResult;
import git4idea.commands.GitTaskResultHandlerAdapter;
import git4idea.i18n.GitBundle;
import git4idea.rebase.GitInteractiveRebaseEditorHandler;
import git4idea.rebase.GitRebaseEditorService;
import git4idea.rebase.GitRebaseLineListener;
import git4idea.repo.GitRepositoryManager;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.List;
import java.util.Set;

/**
 * The base class for rebase actions that use editor
 */
public abstract class GitRebaseActionBase extends GitRepositoryAction {
  /**
   * {@inheritDoc}
   */
  protected void perform(@Nonnull final Project project,
                         @Nonnull final List<VirtualFile> gitRoots,
                         @Nonnull final VirtualFile defaultRoot,
                         final Set<VirtualFile> affectedRoots,
                         final List<VcsException> exceptions) throws VcsException {
    GitLineHandler h = createHandler(project, gitRoots, defaultRoot);
    if (h == null) {
      return;
    }
    final VirtualFile root = h.workingDirectoryFile();
    GitRebaseEditorService service = GitRebaseEditorService.getInstance();
    final GitInteractiveRebaseEditorHandler editor = new GitInteractiveRebaseEditorHandler(service, project, root, h);
    final GitRebaseLineListener resultListener = new GitRebaseLineListener();
    h.addLineListener(resultListener);
    configureEditor(editor);
    affectedRoots.add(root);

    service.configureHandler(h, editor.getHandlerNo());
    GitTask task = new GitTask(project, h, GitBundle.message("rebasing.title"));
    task.executeInBackground(false, new GitTaskResultHandlerAdapter() {
      @Override
      protected void run(GitTaskResult taskResult) {
        editor.close();
        GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
        manager.updateRepository(root);
        root.refresh(false, true);
        notifyAboutErrorResult(taskResult, resultListener, exceptions, project);
      }
    });
  }

  private static void notifyAboutErrorResult(GitTaskResult taskResult, GitRebaseLineListener resultListener, List<VcsException> exceptions, Project project) {
    if (taskResult == GitTaskResult.CANCELLED) {
      return;
    }
    final GitRebaseLineListener.Result result = resultListener.getResult();
    String messageId;
    boolean isError = true;
    switch (result.status) {
      case CONFLICT:
        messageId = "rebase.result.conflict";
        break;
      case ERROR:
        messageId = "rebase.result.error";
        break;
      case CANCELLED:
        // we do not need to show a message if editing was cancelled.
        exceptions.clear();
        return;
      case EDIT:
        isError = false;
        messageId = "rebase.result.amend";
        break;
      case FINISHED:
      default:
        messageId = null;
    }
    if (messageId != null) {
      String message = GitBundle.message(messageId, result.current, result.total);
      String title = GitBundle.message(messageId + ".title");
      if (isError) {
        Messages.showErrorDialog(project, message, title);
      }
      else {
        Messages.showInfoMessage(project, message, title);
      }
    }
  }

  /**
   * This method could be overridden to supply additional information to the editor.
   *
   * @param editor the editor to configure
   */
  protected void configureEditor(GitInteractiveRebaseEditorHandler editor) {
  }

  /**
   * Create line handler that represents a git operation
   *
   * @param project     the context project
   * @param gitRoots    the git roots
   * @param defaultRoot the default root
   * @return the line handler or null
   */
  @Nullable
  protected abstract GitLineHandler createHandler(Project project, List<VirtualFile> gitRoots, VirtualFile defaultRoot);
}