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

  angular.module('angularAwesomeSlider', [])
    // DIRECTIVE
    .directive('slider', [
      '$compile', '$templateCache','$timeout', '$window', 'slider',
      function(compile, templateCache, timeout, win, Slider) {
        return {
          restrict : 'AE',
          require: '?ngModel',
          scope: { options:'=', ngDisabled: '='},
          priority: 1,
          link : function(scope, element, attrs, ngModel) {

          if(!ngModel) return;

          if (!scope.options)
            throw new Error('You must provide a value for "options" attribute.');

          var injector = angular.injector();

          // options as inline variable
          if (angular.isString(scope.options)) {
            scope.options = angular.toJson(scope.options);
          }

          scope.mainSliderClass = 'jslider';
          scope.mainSliderClass += scope.options.skin ? ' jslider_' + scope.options.skin : ' ';
          scope.mainSliderClass += scope.options.vertical ? ' vertical ' : '';
          scope.mainSliderClass += scope.options.css ? ' sliderCSS' : '';
          scope.mainSliderClass += scope.options.className ? ' ' + scope.options.className : '';

          // handle limit labels visibility
          scope.options.limits = angular.isDefined(scope.options.limits) ? scope.options.limits : true;

          // compile template
          element.after(compile(templateCache.get('ng-slider/slider-bar.tmpl.html'))(scope, function(clonedElement, scope) {
            scope.tmplElt = clonedElement;
          }));

          // init

          var initialized = false;

          var init = function() {
            scope.from = ''+scope.options.from;
            scope.to = ''+scope.options.to;
            if (scope.options.calculate && typeof scope.options.calculate === 'function') {
              scope.from = scope.options.calculate(scope.from);
              scope.to = scope.options.calculate(scope.to);
            }

            var OPTIONS = {
              from: !scope.options.round ? parseInt(scope.options.from, 10) : parseFloat(scope.options.from),
              to: !scope.options.round ? parseInt(scope.options.to, 10) : parseFloat(scope.options.to),
              step: scope.options.step,
              smooth: scope.options.smooth,
              limits: scope.options.limits,
              round: scope.options.round || false,
              value: ngModel.$viewValue,
              dimension: "",
              scale: scope.options.scale,
              modelLabels: scope.options.modelLabels,
              vertical: scope.options.vertical,
              css: scope.options.css,
              className: scope.options.className,
              realtime: scope.options.realtime,
              cb: forceApply,
              threshold: scope.options.threshold,
              heterogeneity: scope.options.heterogeneity
            };

            OPTIONS.calculate = scope.options.calculate || undefined;
            OPTIONS.onstatechange = scope.options.onstatechange || undefined;

            // slider
            scope.slider = !scope.slider ? slidering(element, scope.tmplElt, OPTIONS) : scope.slider.init(element, scope.tmplElt, OPTIONS);

            if (!initialized) {
              initListener();
            }

            // scale
            var scaleDiv = scope.tmplElt.find('div')[7];
            angular.element(scaleDiv).html(scope.slider.generateScale());
            scope.slider.drawScale(scaleDiv);

            if (scope.ngDisabled) {
              disabler(scope.ngDisabled);
            }

            initialized = true;
          };

          function initListener() {
            // window resize listener
            angular.element(win).bind('resize', function(event) {
              scope.slider.onresize();
            });
          }

          // model -> view
          ngModel.$render = function () {
            //elm.html(ctrl.$viewValue);
            var singleValue = false;

            if (!ngModel.$viewValue && ngModel.$viewValue !== 0) {
              return;
            }

            if (typeof(ngModel.$viewValue) === 'number') {
              ngModel.$viewValue = ''+ngModel.$viewValue;
            }

            if( !ngModel.$viewValue.split(";")[1]) {
              scope.mainSliderClass += ' jslider-single';
            }

            if (scope.slider) {
              var vals = ngModel.$viewValue.split(";");
              scope.slider.getPointers()[0].set(vals[0], true);
              if (vals[1]) {
                scope.slider.getPointers()[1].set(vals[1], true);
                //if moving left to right with two pointers
                //we need to "finish" moving the first
                if(parseInt(vals[1]) > parseInt(vals[0])){
                  scope.slider.getPointers()[0].set(vals[0], true);
                }
              }
            }
          };

          // view -> model
          var forceApply = function(value, released) {
            if (scope.disabled)
              return;
            scope.$apply(function() {
              ngModel.$setViewValue(value);
            });
            if (scope.options.callback){
              scope.options.callback(value, released);
            }
          };

          // watch options
          scope.$watch('options', function(value) {
            timeout(function(){
              init();
            });
          }, scope.watchOptions || true);

          // disabling
          var disabler = function(value) {
            scope.disabled = value;
            if (scope.slider) {
              scope.tmplElt.toggleClass('disabled');
              scope.slider.disable(value);
            }
          };

          scope.$watch('ngDisabled', function(value) {
            disabler(value);
          });

          scope.limitValue = function(value) {
            if (scope.options.modelLabels) {
              if (angular.isFunction(scope.options.modelLabels)) {
                return scope.options.modelLabels(value);
              }
              return scope.options.modelLabels[value] !== undefined ? scope.options.modelLabels[value] : value;
            }
            return value;
          };

          var slidering = function( inputElement, element, settings) {
            return new Slider( inputElement, element, settings );
          };
        }
      };
    }])
.config(function() {})
.run(function() {});
})(angular);
;(function(angular){
  'use strict';
  angular.module('angularAwesomeSlider').constant('sliderConstants', {
    SLIDER: {
      settings: {
        from: 1,
        to: 40,
        step: 1,
        smooth: true,
        limits: false,
        round: false,
        value: "3",
        dimension: "",
        vertical: false,
        calculate: false,
        onstatechange: false,
        callback: false,
        realtime: false
      },
      className: "jslider",
      selector: ".jslider-",
      css: {
        visible : { visibility: "visible" },
        hidden : { visibility: "hidden" }
      }
    },
    EVENTS: {

    }
  });

}(angular));;(function(angular){
  'use strict';

  angular.module('angularAwesomeSlider').factory('sliderUtils', ['$window', function(win) {
    return {
      offset: function(elm) {
        // try {return elm.offset();} catch(e) {}
        var rawDom = elm[0];
        var _x = 0;
        var _y = 0;
        var body = document.documentElement || document.body;
        var scrollX = window.pageXOffset || body.scrollLeft;
        var scrollY = window.pageYOffset || body.scrollTop;
        _x = rawDom.getBoundingClientRect().left + scrollX;
        _y = rawDom.getBoundingClientRect().top + scrollY;
        return { left: _x, top:_y };
      },
      browser: function() {
        // TODO finish browser detection and this case
        var userAgent = win.navigator.userAgent;
        var browsers = {mozilla: /mozilla/i, chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i};
        for(var key in browsers) {
          if (browsers[key].test(userAgent)) {
            return key;
          }
        }
        return 'unknown';
      }
    };
  }]);
})(angular);

;(function(angular){
  'use strict';

  angular.module('angularAwesomeSlider').factory('sliderDraggable', ['sliderUtils', function(utils) {

    function Draggable(){
      this._init.apply( this, arguments );
    }

    Draggable.prototype.oninit = function(){
    };

    Draggable.prototype.events = function(){
    };

    Draggable.prototype.onmousedown = function(){
      this.ptr.css({ position: 'absolute' });
    };

    Draggable.prototype.onmousemove = function( evt, x, y ){
      this.ptr.css({ left: x, top: y });
    };

    Draggable.prototype.onmouseup = function(){};

    Draggable.prototype.isDefault = {
      drag: false,
      clicked: false,
      toclick: true,
      mouseup: false
    };

    Draggable.prototype._init = function() {
      if( arguments.length > 0 ){
        this.ptr = arguments[0];
        this.parent = arguments[2];

        if (!this.ptr)
          return;
        //this.outer = $(".draggable-outer");

        this.is = {};
        angular.extend( this.is, this.isDefault );
        var offset = utils.offset(this.ptr);

        this.d = {
          left: offset.left,
          top: offset.top,
          width: this.ptr[0].clientWidth,
          height: this.ptr[0].clientHeight
        };

        this.oninit.apply( this, arguments );

        this._events();
      }
    };

    Draggable.prototype._getPageCoords = function( event ){
      if( event.targetTouches && event.targetTouches[0] ){
        return { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY };
      } else
      return { x: event.pageX, y: event.pageY };
    };

    Draggable.prototype._bindEvent = function( ptr, eventType, handler ){
      var self = this;

      // PS need to bind to touch and non-touch events for devices which support both
      if( this.supportTouches_ ){
        ptr[0].addEventListener( this.events_[ eventType ].touch, handler, false );
      }

      ptr.bind( this.events_[ eventType ].nonTouch, handler );
    };

    Draggable.prototype._events = function(){
      var self = this;

      this.supportTouches_ = 'ontouchend' in document;
      this.events_ = {
        'click': { touch : 'touchstart', nonTouch : 'click' },
        'down': { touch : 'touchstart', nonTouch : 'mousedown' },
        'move': { touch : 'touchmove', nonTouch : 'mousemove' },
        'up'  : { touch : 'touchend', nonTouch: 'mouseup'},
        'mousedown'  : { touch : 'mousedown', nonTouch : 'mousedown' }
      };

      var documentElt = angular.element(window.document);

      this._bindEvent(documentElt, 'move', function(event) {
        if(self.is.drag) {
          event.stopPropagation();
          event.preventDefault();
          if (!self.parent.disabled) {
            self._mousemove(event);
          }
        }
      });
      this._bindEvent(documentElt, 'down', function(event) {
        if(self.is.drag) {
          event.stopPropagation();
          event.preventDefault();
        }
      });
      this._bindEvent(documentElt, 'up', function(event) {
        self._mouseup(event);
      });

      this._bindEvent( this.ptr, 'down', function(event) {
        self._mousedown( event );
        return false;
      });
      this._bindEvent( this.ptr, 'up', function(event) {
        self._mouseup( event );
      });

      // TODO see if needed
      this.events();
    };

    Draggable.prototype._mousedown = function( evt ){
      this.is.drag = true;
      this.is.clicked = false;
      this.is.mouseup = false;

      var coords = this._getPageCoords( evt );
      this.cx = coords.x - this.ptr[0].offsetLeft;
      this.cy = coords.y - this.ptr[0].offsetTop;

      angular.extend(this.d, {
        left: coords.x,
        top: coords.y,
        width: this.ptr[0].clientWidth,
        height: this.ptr[0].clientHeight
      });

      if( this.outer && this.outer.get(0) ){
        this.outer.css({ height: Math.max(this.outer.height(), $(document.body).height()), overflow: 'hidden' });
      }

      this.onmousedown( evt );
    };

    Draggable.prototype._mousemove = function( evt ){
      this.is.toclick = false;
      var coords = this._getPageCoords( evt );
      this.onmousemove( evt, coords.x - this.cx, coords.y - this.cy );
    };

    Draggable.prototype._mouseup = function( evt ){
      var oThis = this;

      if( this.is.drag ){
        this.is.drag = false;

        var browser = utils.browser();

        if( this.outer && this.outer.get(0) ) {

          if( browser === 'mozilla' ){
            this.outer.css({ overflow: "hidden" });
          } else {
            this.outer.css({ overflow: "visible" });
          }

          // TODO finish browser detection and this case, remove following line
          this.outer.css({ height: "auto" });
          // if( browser === 'ie' && $.browser.version == '6.0' ){
          //   this.outer.css({ height: "100%" });
          // } else {
          //   this.outer.css({ height: "auto" });
          // }

        }

        this.onmouseup( evt );
      }
    };

    return Draggable;
  }]);
}(angular));;(function(angular){
  'use strict';

  angular.module('angularAwesomeSlider').factory('sliderPointer', ['sliderDraggable', 'sliderUtils', function(Draggable, utils) {

    function SliderPointer() {
      Draggable.apply(this, arguments);
    }

    SliderPointer.prototype = new Draggable();

    SliderPointer.prototype.oninit = function( ptr, id, vertical, _constructor ) {
      this.uid = id;
      this.parent = _constructor;
      this.value = {};
      this.vertical = vertical;
      this.settings = angular.copy(_constructor.settings);
      this.threshold = this.settings.threshold;
    };

    SliderPointer.prototype.onmousedown = function( evt ) {
      var off = utils.offset(this.parent.domNode);

      var offset = {
        left: off.left,
        top: off.top,
        width: this.parent.domNode[0].clientWidth,
        height: this.parent.domNode[0].clientHeight
      };

      this._parent = {
        offset: offset,
        width: offset.width,
        height: offset.height
      };

      this.ptr.addClass('jslider-pointer-hover');
    };

    SliderPointer.prototype.onmousemove = function( evt, x, y ){
      var coords = this._getPageCoords( evt );
      this._set(!this.vertical ? this.calc( coords.x ) : this.calc( coords.y ));
      if( this.settings.realtime && this.settings.cb && angular.isFunction(this.settings.cb) )
        this.settings.cb.call( this.parent, this.parent.getValue(), !this.is.drag  );
    };

    SliderPointer.prototype.onmouseup = function(evt){
      if( this.settings.cb && angular.isFunction(this.settings.cb))
        this.settings.cb.call( this.parent, this.parent.getValue(), !this.is.drag );

      if (!this.is.drag)
        this.ptr.removeClass('jslider-pointer-hover');
    };

    SliderPointer.prototype.limits = function( x ){
      return this.parent.limits(x, this);
    };

    SliderPointer.prototype.calc = function( coords ){
      return !this.vertical ?
        this.limits(((coords-this._parent.offset.left)*100)/this._parent.width)
        :
        this.limits(((coords-this._parent.offset.top)*100)/this._parent.height);
    };

    SliderPointer.prototype.set = function( value, opt_origin ){
      this.value.origin = this.parent.round(value);
      this._set(this.parent.valueToPrc(value,this), opt_origin);
    };

    SliderPointer.prototype._set = function( prc, opt_origin ){
      this.allowed = true;

      var oldOrigin = this.value.origin;
      var oldPerc = this.value.prc;

      this.value.origin = this.parent.prcToValue(prc);
      this.value.prc = prc;

      // check threshold
      if (this.threshold && this.parent.o.pointers[1]) {
        var v1 = this.value.origin,
            v2 = this.parent.o.pointers[this.uid === 0 ? 1:0].value.origin;
        this.allowed =  Math.abs(v2 - v1) >= this.threshold;
        if (!this.allowed && oldOrigin !== undefined && oldPerc !== undefined){
          this.value.origin = oldOrigin;
          this.value.prc = oldPerc;
        }
      }

      if (!this.vertical)
        this.ptr.css({left:this.value.prc+'%'});
      else
        this.ptr.css({top:this.value.prc+'%', marginTop: -5});
      this.parent.redraw(this);
    };

    return SliderPointer;
  }]);
}(angular));;(function(angular){
  'use strict';

  angular.module('angularAwesomeSlider').factory('slider', ['sliderPointer', 'sliderConstants', 'sliderUtils', function(SliderPointer, sliderConstants, utils) {

    function Slider(){
      return this.init.apply(this, arguments);
    }

    Slider.prototype.init = function( inputNode, templateNode, settings ){
      this.settings = settings;
      this.inputNode = inputNode;
      this.inputNode.addClass("ng-hide");

      this.settings.interval = this.settings.to-this.settings.from;

      if(this.settings.calculate && angular.isFunction(this.settings.calculate))
        this.nice = this.settings.calculate;

      if(this.settings.onstatechange && angular.isFunction(this.settings.onstatechange))
        this.onstatechange = this.settings.onstatechange;

      this.css = sliderConstants.SLIDER.css;
      this.is = {init: false};
      this.o = {};
      this.initValue = {};
      this.isAsc = settings.from < settings.to;

      this.create(templateNode);

      return this;
    };

    Slider.prototype.create = function( templateNode ){
      // set skin class
      //   if( this.settings.skin && this.settings.skin.length > 0 )
      //     this.setSkin( this.settings.skin );

      var self = this;

      this.domNode = templateNode;

      var divs = this.domNode.find('div'),
          is = this.domNode.find('i'),
          angElt = angular.element,
          angExt = angular.extend,
          angForEach = angular.forEach,
          pointer1 = angElt(divs[1]),
          pointer2 = angElt(divs[2]),
          pointerLabel1 = angElt(divs[5]),
          pointerLabel2 = angElt(divs[6]),
          indicatorLeft = angElt(is[0]),
          indicatorRight = angElt(is[1]),
          range = angElt(is[2]),
          indicator1 = angElt(is[3]),
          indicator2 = angElt(is[4]),
          indicator3 = angElt(is[5]),
          indicator4 = angElt(is[6]),
          pointers = [pointer1, pointer2],
          off = utils.offset(this.domNode),
          offset = {
            left: off.left,
            top: off.top,
            width: this.domNode[0].clientWidth,
            height: this.domNode[0].clientHeight
          },
          values = self.settings.value.split(';');

      this.sizes = {
        domWidth: this.domNode[0].clientWidth,
        domHeight: this.domNode[0].clientHeight,
        domOffset: offset
      };

      // find some objects
      angExt(this.o, {
        pointers: {},
        labels: { 0: { o : pointerLabel1 }, 1: { o : pointerLabel2 } },
        limits: { 0: angular.element(divs[3]), 1: angular.element(divs[4]) },
        indicators: { 0: indicator1, 1: indicator2, 2: indicator3, 3: indicator4 }
      });

      angExt(this.o.labels[0], {
        value: this.o.labels[0].o.find("span")
      });

      angExt(this.o.labels[1], {
        value: this.o.labels[1].o.find("span")
      });

      // single pointer
      this.settings.single = !self.settings.value.split(";")[1];

      if (this.settings.single) {
        range.addClass('ng-hide');
      }

      angForEach(pointers, function(pointer, key) {
        self.settings = angular.copy(self.settings);

        var value = values[key],
            prev,
            prevValue,
            test,
            value1,
            offset;

        if(value) {
          self.o.pointers[key] = new SliderPointer(pointer, key, self.settings.vertical, self);

          prev = values[key-1];
          prevValue = prev ? parseInt(prev, 10 ) : undefined;

          value = self.settings.round ? parseFloat(value) : parseInt(value, 10);

          if( prev && self.isAsc ? value < prevValue : value > prevValue ) {
            value = prev;
          }

          // limit threshold adjust
/*          test = self.isAsc ? value < self.settings.from : value > self.settings.from,
          value1 = test ? self.settings.from : value;              */

          test = self.isAsc ? value > self.settings.to : value < self.settings.to;
          value1 = test ? self.settings.to : value;

          self.o.pointers[key].set( value1, true );

          // reinit position d
          offset = utils.offset(self.o.pointers[key].ptr);

          self.o.pointers[key].d = {
            left: offset.left,
            top: offset.top
          };
        }
      });

      self.domNode.bind('mousedown', self.clickHandler.apply(self));

      this.o.value = angElt(this.domNode.find("i")[2]);
      this.is.init = true;

      // CSS SKIN
      if (this.settings.css) {
        indicatorLeft.css(this.settings.css.background ? this.settings.css.background : {});
        indicatorRight.css(this.settings.css.background ? this.settings.css.background : {});
        if (!this.o.pointers[1]) {
          indicator1.css(this.settings.css.before ? this.settings.css.before : {});
          indicator4.css(this.settings.css.after ? this.settings.css.after : {});
        }

        indicator2.css(this.settings.css.default ? this.settings.css.default : {});
        indicator3.css(this.settings.css.default ? this.settings.css.default : {});

        range.css(this.settings.css.range ? this.settings.css.range : {});
        pointer1.css(this.settings.css.pointer ? this.settings.css.pointer : {});
        pointer2.css(this.settings.css.pointer ? this.settings.css.pointer : {});
      }

      angForEach(this.o.pointers, function(pointer, key){
        self.redraw(pointer);
      });

    };

    Slider.prototype.clickHandler = function() {
      var self = this;

      // in case of showing/hiding
      var resetPtrSize = function( ptr ) {
        var ptr1 = self.o.pointers[0].ptr,
            ptr2 = self.o.pointers[1].ptr,
            offset1 = utils.offset(ptr1),
            offset2 = utils.offset(ptr2);

        self.o.pointers[0].d = {
          left: offset1.left,
          top: offset1.top,
          width: ptr1[0].clientWidth,
          height: ptr1[0].clientHeight
        };

        self.o.pointers[1].d = {
          left: offset2.left,
          top: offset2.top,
          width: ptr2[0].clientWidth,
          height: ptr2[0].clientHeight
        };
      };

      return function(evt) {
        if (self.disabled)
          return;
        var vertical = self.settings.vertical,
            targetIdx = 0,
            _off = utils.offset(self.domNode),
            firstPtr = self.o.pointers[0],
            secondPtr = self.o.pointers[1] ? self.o.pointers[1] : null,
            tmpPtr,
            evtPosition = evt.originalEvent ? evt.originalEvent: evt,
            mouse = vertical ? evtPosition.pageY : evtPosition.pageX,
            css = vertical ? 'top' : 'left',
            offset = { left: _off.left, top: _off.top, width: self.domNode[0].clientWidth, height: self.domNode[0].clientHeight },
            targetPtr = self.o.pointers[targetIdx];

        if (secondPtr) {
          if (!secondPtr.d.width) {
            resetPtrSize();
          }
          var firstPtrPosition = utils.offset(firstPtr.ptr)[css];
          var secondPtrPosition = utils.offset(secondPtr.ptr)[css];
          var middleGap = Math.abs((secondPtrPosition - firstPtrPosition) / 2);
          var testSecondPtrToMove = mouse >= secondPtrPosition || mouse >= (secondPtrPosition - middleGap);
          if (testSecondPtrToMove) {
            targetPtr = secondPtr;
          }
        }
        targetPtr._parent = {offset: offset, width: offset.width, height: offset.height};
        var coords = firstPtr._getPageCoords( evt );
        targetPtr.cx = coords.x - targetPtr.d.left;
        targetPtr.cy = coords.y - targetPtr.d.top;
        targetPtr.onmousemove( evt, coords.x, coords.y);
        targetPtr.onmouseup();
        angular.extend(targetPtr.d, {
           left: coords.x,
           top: coords.y
        });

        self.redraw(targetPtr);
        return false;
      };
    };

    Slider.prototype.disable = function( bool ) {
      this.disabled = bool;
    };

    Slider.prototype.nice = function( value ){
      return value;
    };

    Slider.prototype.onstatechange = function(){};

    Slider.prototype.limits = function( x, pointer ){
      // smooth
      if(!this.settings.smooth){
        var step = this.settings.step*100 / ( this.settings.interval );
        x = Math.round( x/step ) * step;
      }

      if (pointer) {
        var another = this.o.pointers[1-pointer.uid];
        if(another && pointer.uid && x < another.value.prc) x = another.value.prc;
        if(another && !pointer.uid && x > another.value.prc) x = another.value.prc;
      }
      // base limit
      if(x < 0) x = 0;
      if(x > 100) x = 100;

      return Math.round(x*10) / 10;
    };

    Slider.prototype.getPointers = function(){
      return this.o.pointers;
    };

    Slider.prototype.generateScale = function(){
      if (this.settings.scale && this.settings.scale.length > 0){
        var str = '',
            s = this.settings.scale,
        // FIX Big Scale Failure #34
        // var prc = Math.round((100/(s.length-1))*10)/10;
            prc,
            label,
            duplicate = {},
            position = this.settings.vertical ? 'top' : 'left',
            i=0;
        for(; i < s.length; i++) {
          if (!s[i].val) {
             prc = (100/(s.length-1)).toFixed(2);
             str += '<span style="'+ position + ': ' + i*prc + '%">' + ( s[i] != '|' ? '<ins>' + s[i] + '</ins>' : '' ) + '</span>';
          }

          if (s[i].val <= this.settings.to && s[i].val >= this.settings.from &&  ! duplicate[s[i].val]) {
            duplicate[s[i].val] = true;
            prc = this.valueToPrc(s[i].val);
            label = s[i].label ? s[i].label : s[i].val;
            str += '<span style="'+ position + ': ' + prc + '%">' + '<ins>' + label + '</ins>' + '</span>';
          }
        }
        return str;
      }

      return '';
    };

    Slider.prototype.onresize = function(){
      var self = this;

      this.sizes = {
        domWidth: this.domNode[0].clientWidth,
        domHeight: this.domNode[0].clientHeight,
        domOffset: {
          left: this.domNode[0].offsetLeft,
          top: this.domNode[0].offsetTop,
          width: this.domNode[0].clientWidth,
          height: this.domNode[0].clientHeight
        }
      };

      angular.forEach(this.o.pointers, function(ptr, key) {
        self.redraw(ptr);
      });
    };

    Slider.prototype.update = function(){
      this.onresize();
      this.drawScale();
    };

    Slider.prototype.drawScale = function( scaleDiv ){
      angular.forEach(angular.element(scaleDiv).find('ins'), function(scaleLabel, key) {
        scaleLabel.style.marginLeft = - scaleLabel.clientWidth / 2;
      });
    };

    Slider.prototype.redraw = function( pointer ){
      if(!this.is.init) {
        // this.settings.single
        if(this.o.pointers[0] && !this.o.pointers[1]) {
          this.originValue = this.o.pointers[0].value.prc;
          this.o.indicators[0].css(!this.settings.vertical ? {left:0, width:this.o.pointers[0].value.prc + "%"} : {top:0, height:this.o.pointers[0].value.prc + "%"});
          this.o.indicators[1].css(!this.settings.vertical ? {left:this.o.pointers[0].value.prc + "%"} : {top:this.o.pointers[0].value.prc + "%"});
          this.o.indicators[3].css(!this.settings.vertical ? {left:this.o.pointers[0].value.prc + "%"} : {top:this.o.pointers[0].value.prc + "%"});
        } else {
          this.o.indicators[2].css(!this.settings.vertical ? {left:this.o.pointers[1].value.prc + "%"} : {top:this.o.pointers[1].value.prc + "%"});
          this.o.indicators[0].css(!this.settings.vertical ? {left:0, width:"0"} : {top:0, height:"0"});
          this.o.indicators[3].css(!this.settings.vertical ? {left:"0", width:"0"} : {top:"0", height:"0"});
        }

        return false;
      }

      this.setValue();

      var newPos,
          newWidth;

      // redraw range line
      if(this.o.pointers[0] && this.o.pointers[1]) {
        newPos = !this.settings.vertical ?
          { left: this.o.pointers[0].value.prc + "%", width: ( this.o.pointers[1].value.prc - this.o.pointers[0].value.prc ) + "%" }
          :
          { top: this.o.pointers[0].value.prc + "%", height: ( this.o.pointers[1].value.prc - this.o.pointers[0].value.prc ) + "%" };

        this.o.value.css(newPos);

        // both pointer overlap on limits
        if (this.o.pointers[0].value.prc === this.o.pointers[1].value.prc) {
          this.o.pointers[1].ptr.css("z-index", this.o.pointers[0].value.prc === 0 ? '3' : '1');
        }

      }

      if(this.o.pointers[0] && !this.o.pointers[1]) {
        newWidth = this.o.pointers[0].value.prc - this.originValue;
        if (newWidth >= 0) {
          this.o.indicators[3].css(!this.settings.vertical ? {width: newWidth + "%"} : {height: newWidth + "%"});
        }
        else {
          this.o.indicators[3].css(!this.settings.vertical ? {width: 0} : {height: 0});
        }

        if (this.o.pointers[0].value.prc < this.originValue) {
         this.o.indicators[0].css(!this.settings.vertical ? {width: this.o.pointers[0].value.prc + "%"} : {height: this.o.pointers[0].value.prc + "%"});
        }
        else {
          this.o.indicators[0].css(!this.settings.vertical ? {width: this.originValue + "%"} : {height: this.originValue + "%"});
        }

      }

      var value = this.nice(pointer.value.origin);
      if (this.settings.modelLabels) {
        if (angular.isFunction(this.settings.modelLabels)) {
          value = this.settings.modelLabels(value);
        }
        else {
          value = this.settings.modelLabels[value] !== undefined ? this.settings.modelLabels[value] : value;
        }
      }

      this.o.labels[pointer.uid].value.html(value);

      // redraw position of labels
      this.redrawLabels( pointer );
    };

    Slider.prototype.redrawLabels = function( pointer ) {

      function setPosition( label, sizes, prc ) {
        sizes.margin = -sizes.label/2;
        var domSize = !self.settings.vertical ? self.sizes.domWidth : self.sizes.domHeight;

        if (self.sizes.domWidth) {
          // left limit
          var label_left = sizes.border + sizes.margin;
          if(label_left < 0)
            sizes.margin -= label_left;

          // right limit
          if(self.sizes.domWidth > 0 && sizes.border+sizes.label / 2 > domSize){
            sizes.margin = 0;
            sizes.right = true;
          } else
          sizes.right = false;
        }

        if (!self.settings.vertical)
          label.o.css({ left: prc + "%", marginLeft: sizes.margin+"px", right: "auto" });
        else
          label.o.css({ top: prc + "%", marginLeft: "20px", marginTop: sizes.margin, bottom: "auto" });
        if(sizes.right && self.sizes.domWidth > 0) {
          if (!self.settings.vertical)
            label.o.css({ left: "auto", right: 0 });
          else
            label.o.css({ top: "auto", bottom: 0 });
        }
        return sizes;
      }

      var self = this,
          label = this.o.labels[pointer.uid],
          prc = pointer.value.prc,
          // case hidden
          labelWidthSize = label.o[0].offsetWidth === 0 ? (label.o[0].textContent.length)*7 : label.o[0].offsetWidth;

      this.sizes.domWidth = this.domNode[0].clientWidth;
      this.sizes.domHeight = this.domNode[0].clientHeight;

      var sizes = {
        label: !self.settings.vertical ? labelWidthSize : label.o[0].offsetHeight,
        right: false,
        border: (prc * (!self.settings.vertical ? this.sizes.domWidth: this.sizes.domHeight)) / 100
      };

      var anotherIdx = pointer.uid === 0 ? 1:0,
          anotherLabel,
          anotherPtr;

      if (!this.settings.single && !this.settings.vertical){
        // glue if near;
        anotherLabel = this.o.labels[anotherIdx];
        anotherPtr = this.o.pointers[anotherIdx];
        var label1 = this.o.labels[0],
            label2 = this.o.labels[1],
            ptr1 = this.o.pointers[0],
            ptr2 = this.o.pointers[1],
            gapBetweenLabel = ptr2.ptr[0].offsetLeft - ptr1.ptr[0].offsetLeft,
            value = this.nice(anotherPtr.value.origin);

        label1.o.css(this.css.visible);
        label2.o.css(this.css.visible);

        value = this.getLabelValue(value);

        if (gapBetweenLabel + 10 < label1.o[0].offsetWidth+label2.o[0].offsetWidth) {
          anotherLabel.o.css(this.css.hidden);

          anotherLabel.value.html(value);
          prc = (anotherPtr.value.prc - prc) / 2 + prc;
          if(anotherPtr.value.prc != pointer.value.prc){
            value = this.nice(this.o.pointers[0].value.origin);
            var value1 = this.nice(this.o.pointers[1].value.origin);
            value = this.getLabelValue(value);
            value1 = this.getLabelValue(value1);

            label.value.html(value + " – " + value1);
            sizes.label = label.o[0].offsetWidth;
            sizes.border = (prc * domSize) / 100;
          }
        }
        else {
          anotherLabel.value.html(value);
          anotherLabel.o.css(this.css.visible);
        }
      }

      sizes = setPosition(label, sizes, prc);

      var domSize = !self.settings.vertical ? self.sizes.domWidth : self.sizes.domHeight;

      /* draw second label */
      if(anotherLabel){
        // case hidden
        var labelWidthSize2 = label.o[0].offsetWidth === 0 ? (label.o[0].textContent.length/2)*7 : label.o[0].offsetWidth,
            sizes2 = {
          label: !self.settings.vertical ? labelWidthSize2: anotherLabel.o[0].offsetHeight,
          right: false,
          border: (anotherPtr.value.prc * this.sizes.domWidth) / 100
        };
        sizes = setPosition(anotherLabel, sizes2, anotherPtr.value.prc);
      }

      this.redrawLimits();
    };

    Slider.prototype.redrawLimits = function() {
      if (this.settings.limits) {

        var limits = [true, true],
            i = 0;

        for(var key in this.o.pointers){

          if(!this.settings.single || key === 0){

            var pointer = this.o.pointers[key],
                label = this.o.labels[pointer.uid],
                label_left = label.o[0].offsetLeft - this.sizes.domOffset.left,
                limit = this.o.limits[0];

            if(label_left < limit[0].clientWidth) {
              limits[0] = false;
            }

            limit = this.o.limits[1];
            if(label_left + label.o[0].clientWidth > this.sizes.domWidth - limit[0].clientWidth){
              limits[1] = false;
            }

          }
        }

        for(; i < limits.length; i++){
          if(limits[i]){ // TODO animate
            angular.element(this.o.limits[i]).addClass("animate-show");
          }
          else{
            angular.element(this.o.limits[i]).addClass("animate-hidde");
          }
        }
      }
    };

    Slider.prototype.setValue = function(){
      var value = this.getValue();
      this.inputNode.attr("value", value);
      this.onstatechange.call(this, value, this.inputNode);
    };

    Slider.prototype.getValue = function(){
      if(!this.is.init) return false;
      var $this = this;

      var value = "";
      angular.forEach(this.o.pointers, function(pointer, key){
        if(pointer.value.prc !== undefined && !isNaN(pointer.value.prc))
          value += (key > 0 ? ";" : "") + $this.prcToValue(pointer.value.prc);
      });
      return value;
    };

    Slider.prototype.getLabelValue = function(value){
      if (this.settings.modelLabels) {
        if (angular.isFunction(this.settings.modelLabels)) {
          return this.settings.modelLabels(value);
        }
        else {
          return this.settings.modelLabels[value] !== undefined ? this.settings.modelLabels[value] : value;
        }
      }

      return value;
    };

    Slider.prototype.getPrcValue = function(){
      if(!this.is.init) return false;
      var $this = this;

      var value = "";
      // TODO remove jquery and see if % value is nice feature
      /*$.each(this.o.pointers, function(i){
        if(this.value.prc !== undefined && !isNaN(this.value.prc)) value += (i > 0 ? ";" : "") + this.value.prc;
      });*/
      return value;
    };

    Slider.prototype.prcToValue = function( prc ){
      var value;
      if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0){
        var h = this.settings.heterogeneity,
            _start = 0,
            _from = this.settings.round ? parseFloat(this.settings.from) : parseInt(this.settings.from, 10),
            _to = this.settings.round ? parseFloat(this.settings.to) : parseInt(this.settings.to, 10),
            i = 0;

        for (; i <= h.length; i++){
          var v;
          if(h[i])
            v = h[i].split('/');
          else
            v = [100, _to];

          var v1 = this.settings.round ? parseFloat(v[0]) : parseInt(v[0], 10);
          var v2 = this.settings.round ? parseFloat(v[1]) : parseInt(v[1], 10);

          if (prc >= _start && prc <= v1) {
            value = _from + ((prc-_start) * (v2-_from)) / (v1-_start);
          }

          _start = v1;
          _from = v2;
        }
      }
      else {
        value = this.settings.from + (prc * this.settings.interval) / 100;
      }

      return this.round(value);
    };

    Slider.prototype.valueToPrc = function( value, pointer ){
      var prc,
          _from = this.settings.round ? parseFloat(this.settings.from) : parseInt(this.settings.from, 10);

      if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0){
        var h = this.settings.heterogeneity,
            _start = 0,
            i = 0;

        for (; i <= h.length; i++) {
          var v;
          if(h[i])
            v = h[i].split('/');
          else
            v = [100, this.settings.to];

          var v1 = this.settings.round ? parseFloat(v[0]) : parseInt(v[0], 10);
          var v2 = this.settings.round ? parseFloat(v[1]) : parseInt(v[1], 10);

          if(value >= _from && value <= v2){
            if (pointer) {
              prc = pointer.limits(_start + (value-_from)*(v1-_start)/(v2-_from));
            } else {
              prc = this.limits(_start + (value-_from)*(v1-_start)/(v2-_from));
            }
          }

          _start = v1; _from = v2;
        }

      } else {
        if (pointer) {
          prc = pointer.limits((value-_from)*100/this.settings.interval);
        } else {
          prc = this.limits((value-_from)*100/this.settings.interval);
        }
      }

      return prc;
    };

    Slider.prototype.round = function( value ){
      value = Math.round(value / this.settings.step) * this.settings.step;

      if(this.settings.round)
        value = Math.round(value * Math.pow(10, this.settings.round)) / Math.pow(10, this.settings.round);
      else
        value = Math.round(value);
      return value;
    };

    return Slider;

  }]);
}(angular));;(function(angular, undefined) {
'use strict';

  angular.module('angularAwesomeSlider')
  .run(['$templateCache', function ($templateCache) {
    $templateCache.put('ng-slider/slider-bar.tmpl.html',
    '<span ng-class="mainSliderClass" id="{{sliderTmplId}}">' +
      '<table><tr><td>' +
        '<div class="jslider-bg">' +
          '<i class="left"></i>'+
          '<i class="right"></i>'+
          '<i class="range"></i>'+
          '<i class="before"></i>'+
          '<i class="default"></i>'+
          '<i class="default"></i>'+
          '<i class="after"></i>'+
        '</div>' +
        '<div class="jslider-pointer"></div>' +
        '<div class="jslider-pointer jslider-pointer-to"></div>' +
        '<div class="jslider-label" ng-show="options.limits"><span ng-bind="limitValue(options.from)"></span>{{options.dimension}}</div>' +
        '<div class="jslider-label jslider-label-to" ng-show="options.limits"><span ng-bind="limitValue(options.to)"></span>{{options.dimension}}</div>' +
        '<div class="jslider-value"><span></span>{{options.dimension}}</div>' +
        '<div class="jslider-value jslider-value-to"><span></span>{{options.dimension}}</div>' +
        '<div class="jslider-scale" id="{{sliderScaleDivTmplId}}"></div>' +
      '</td></tr></table>' +
    '</span>');
  }]);

})(window.angular);


text:
{% extends "layout.html" %} {% block page_title %} Contact HM Land Registry{% endblock %} {% block content %}

            BETA
            This is a new service – your feedback will help us to improve it.

Contact HM Land Registry

            Warning

            You can't add a charge unless you know the category.

Email HM Land Registry to get a category for this charge:
                    LocalLandCharges@landregistry.gov.uk.

Back

                Why can't I add this charge without a category?

If someone takes a dispute to court that involves this charge, they will need to know what category of charge it is.

The category tells us the type of legal right or restriction on land. Without this information, we don't know what the charge does or which law makes it actionable in a court of law.

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @module fontpainter
 */ /** */

import IRenderBounds from "./interfaces/IRenderBounds";
import WrapMode from "./enum/WrapMode";
import Disposable from 'seng-disposable';
import IFontParser from "./interfaces/IFontParser";
import FontLoader from "./utils/FontLoader";
import FontParserSVG from "./parsers/FontParserSVG";
import {FontParserConstructor} from "./utils/FontLoader";
import AbstractRenderEngine from "./engines/AbstractRenderEngine";
import IRenderOptions from "./interfaces/IRenderOptions";
import TextAlign from "./enum/TextAlign";
import GlyphMap from "./types/GlyphMap";
import ICopyProps from "./interfaces/ICopyProps";

export default class FontPainter extends Disposable implements IRenderOptions {
	public bounds:IRenderBounds|null = null;
	public wrapMode:WrapMode = WrapMode.BREAK_WHITESPACE;
	public align:TextAlign = TextAlign.NONE;
	public letterSpacing:number = 0;
	public lineHeight:number = 1.2;
	public fontLoader:FontLoader;
	public exactFit:boolean = false;
	public fontSize:number = 16;

	private _fontPromise:Promise<IFontParser>|null = null;
	private _engine:AbstractRenderEngine|null = null;
	private _fontParser:IFontParser|null = null;

	constructor() {
		super();

		this.fontLoader = new FontLoader();
		this.fontLoader.setDefaultParser('svg', FontParserSVG);
	}

	public setEngine(engine:AbstractRenderEngine):void {
		this._engine = engine;
	}

	public paint(copy:string):any {
		if (this._engine === null) {
			throw new ReferenceError('Please use setEngine() to set a rendering engine before calling paint()');
		}

		this._engine.render(
			this.getCopyProps(copy.replace(/\s+$/, '')),
			<IFontParser> this._fontParser,
			this
		);
	}

	public getCopyProps(copy:string):ICopyProps {
		if (this._fontParser === null) {
			throw new ReferenceError('Font is undefined or has not yet completed loading');
		}

		const parser = <IFontParser> this._fontParser;
		const characters = copy.split('');
		const charCodes = characters.map(glyph => glyph.charCodeAt(0));

		const glyphs:GlyphMap = charCodes.reduce((glyphMap, charCode, index) => {
			if(!glyphMap[charCode]) {
				glyphMap[charCode] = parser.getGlyph(characters[index]);
			}

			return glyphMap;
		}, {});

		const kernings = charCodes.map((charCode, index) => {
			if (index === charCodes.length - 1) {
				return 0;
			}
			return parser.getKerning(charCode, charCodes[index + 1]);
		});

		return { copy, characters, charCodes, kernings, glyphs };
	}

	public setFontParser(parser:IFontParser):void {
		this._fontParser = parser;
		this._fontPromise = Promise.resolve(parser);
	}

	public loadFont(url:string, parser?:FontParserConstructor):Promise<IFontParser> {
		this._fontPromise = this.fontLoader.load(url, parser).then((parser) => {
			this._fontParser = parser;
			return parser;
		});
		return this._fontPromise;
	}

	public getFont():Promise<IFontParser>|null {
		return this._fontPromise;
	}

	public dispose():void {

		super.dispose();
	}
}


text:
package de.bbcdaas.disambiguation.core.configs;

import de.bbcdaas.disambiguation.core.connector.AbstractConnector;
import java.util.Set;
import java.util.TreeSet;

/**
 * Configuration for a sax contentHandler for parsing a XML files.
 * @author Robert Illers
 */
public abstract class AbstractContentHandlerConfig<T extends AbstractConnector> extends AbstractConfiguration<T> {

	private int limitedDocsCount;
	private Set<String> startElements = new TreeSet<String>();

	/**
	 * Constructor with persistence layer connector as parameter.
	 * @param connector
	 */
    public AbstractContentHandlerConfig(T connector) {
        super(connector);
    }

	/**
	 * Start elements (Token) used in xml file to separate data areas
	 * @return list of start elements
	 */
	public Set<String> getStartElements() {
		return startElements;
	}

	/**
	 * Start elements (Token) used in xml file to separate data areas
	 * @param startElements
	 */
	public void setStartElements(Set<String> startElements) {
		this.startElements = startElements;
	}

	/**
	 * Max number of documents to read
	 * @return limitedDocsCount
	 */
	public int getLimitedDocsCount() {
		return limitedDocsCount;
	}

	/**
	 * Max number of documents to read
	 * @param limitedDocsCount
	 */
	public void setLimitedDocsCount(int limitedDocsCount) {
		this.limitedDocsCount = limitedDocsCount;
	}
}


text:
require 'json'

module Firehose
  module Rack
    # Handles a subscription request over HTTP or WebSockets depeding on its abilities and
    # binds that to the Firehose::Server::Subscription class, which is bound to a channel that
    # gets published to.
    class Consumer
      class BasicHandler
        def last_message_sequence(subscription)
          # this is for backwards compatibility
          # prefer consistent :last_message_sequence from now on
          lms = subscription[:last_message_sequence] || subscription[:message_sequence]

          if subscription[:message_sequence]
            Firehose.logger.warn "Client used deprecated :message_sequence subscription format: #{subscription.inspect}"
          end

          lms.to_i
        end
      end

      # Rack consumer transports
      autoload :HttpLongPoll, 'firehose/rack/consumer/http_long_poll'
      autoload :WebSocket,    'firehose/rack/consumer/web_socket'

      MULTIPLEX_CHANNEL = "channels@firehose"

      def self.multiplexing_request?(env)
        env["PATH_INFO"].include? MULTIPLEX_CHANNEL
      end

      def self.multiplex_subscriptions(request)
        if request.get?
          query_string_subscriptions(request.env)
        elsif request.post?
          post_subscriptions(request)
        end
      end

      def self.query_string_subscriptions(env)
        query_params = ::Rack::Utils.parse_query(env["QUERY_STRING"])

        query_params["subscribe"].to_s.split(",").map do |sub|
          chan, last_sequence = sub.split("!")
          last_sequence = last_sequence.to_i
          last_sequence = 0 if last_sequence < 0
          {
            channel: chan,
            last_message_sequence: last_sequence
          }
        end
      end

      def self.post_subscriptions(request)
        body = request.body.read
        subs = JSON.parse(body).map do |chan, val|
          # Hash is the newer format subscription message that supports
          # params
          if val.is_a? Hash
            {
              channel: chan,
              last_message_sequence: val["last_message_sequence"],
              params: val["params"]
            }
          # Otherwise the value of the JSON hash is implicitly the message
          # sequence
          else
            {
              channel: chan,
              last_message_sequence: val
            }
          end
        end

        if subs.empty?
          Firehose.logger.warn "Consumer.post_subscriptions: Empty / Invalid subscriptions POST body: #{body.inspect}"
        end

        subs
      rescue JSON::ParserError => e
        handle_parse_error(request, body, e)
        []
      end

      def self.handle_parse_error(request, body, error)
        Firehose.logger.warn "JSON::ParserError for request body: #{body.inspect}"
      end

      # Let the client configure the consumer on initialization.
      def initialize
        yield self if block_given?
      end

      def call(env)
        websocket_request?(env) ? websocket.call(env) : http_long_poll.call(env)
      end

      # Memoized instance of web socket that can be configured from the rack app.
      def websocket
        @web_socket ||= WebSocket.new
      end

      # Memoized instance of http long poll handler that can be configured from the rack app.
      def http_long_poll
        @http_long_poll ||= HttpLongPoll.new
      end

      private
      # Determine if the incoming request is a websocket request.
      def websocket_request?(env)
        Firehose::Rack::Consumer::WebSocket.request?(env)
      end
    end
  end
end


text:
package io.lineage;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;

/**
 * roulette-wheel selection via stochastic acceptance
 *
 * Roulette Wheel selection algorithem https://en.wikipedia.org/wiki/Fitness_proportionate_selection
 *
 * @ref http://geneticalgorithms.ai-depot.com/Tutorial/Overview.html
 *
 *      Roulette-wheel selection via stochastic acceptance http://arxiv.org/pdf/1109.3627.pdf
 *
 *      https://www.researchgate.net/publication/51962025_Roulette-wheel_selection_via_stochastic_acceptance
 *
 */
public class RouletteChromosomeSelector implements ChromosomeSelector
{

    public Pair<Chromosome, Chromosome> select000(final Population population)
    {
        double sum = 0d;

        for (final Chromosome c : population)
        {
            sum += c.fitness;
        }

        return new Pair<Chromosome, Chromosome>(choose(population,sum),choose(population,sum));
    }

    @Override
    public Pair<Chromosome, Chromosome> selectPair(final Population population)
    {
        final Population clone = population.clone();
        final Chromosome p1 = select(clone);
        clone.removeAll(Arrays.asList(p1));
        Chromosome p2 = null;
        p2 = select(clone);
        return new Pair<Chromosome, Chromosome>(p1,p2);
    }

    @Override
    public Chromosome select(final Population population)
    {
        final Random rand = new SecureRandom();
        double maxFitness = Integer.MIN_VALUE; //Double.MIN_VALUE;

        for (final Chromosome c : population)
        {
            /*
                 if (c.fitness < 0)
                throw new IllegalStateException("Fittness score should be in [0, 1] range but got " + c.fitness );
             */
            System.out.println(c.fitness + " :: " + maxFitness);
            if (c.fitness > maxFitness)
                maxFitness = c.fitness;
        }

        final int size = population.size();
        int spins = 0;

        if (maxFitness == 0)
        {
            return population.get(rand.nextInt(size));
        }

        // esimated average spin t = fmax / avg(f)
        Chromosome candidate = null;
        for (;;)
        {
            ++spins;
            // Select randomly one of the individuals
            candidate = population.get(rand.nextInt(size));
            final double r = rand.nextDouble();
            final double p = candidate.fitness / maxFitness;

            if (r < p)
            {
                return candidate;
            }
        }
    }

    private Chromosome choose(final Population population, final double fitnessSum)
    {
        while (true)
        {
            final float rnd = (float)(Math.random() * fitnessSum);
            double running = 0d;
            for (final Chromosome c : population)
            {
                if (rnd >= running && rnd <= (running + c.fitness))
                {
                    return c;
                }
                running += c.fitness;
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using BuildAProject.BuildManagement.BuildManagers.Definitions;
using BuildAProject.BuildManagement.CsProjects;
using BuildAProject.BuildManagement.CsProjects.Compilers;
using BuildAProject.BuildManagement.NUnit.Runners;

namespace BuildAProject.BuildManagement.NUnit
{
  public class NUnitTestTask : IBuildTask, IEquatable<NUnitTestTask>
  {
    private readonly ITestRunner testRunner;
    private readonly CsProject csProject;
    private readonly BuildEngineParameters parameters;

    public NUnitTestTask(ITestRunner testRunner, CsProject csProject, BuildEngineParameters parameters)
    {
      if (testRunner == null)
      {
        throw new ArgumentNullException("testRunner");
      }

      if (csProject == null)
      {
        throw new ArgumentNullException("csProject");
      }

      if (parameters == null)
      {
        throw new ArgumentNullException("parameters");
      }

      this.testRunner = testRunner;
      this.csProject = csProject;
      this.parameters = parameters;
    }

    public IEnumerable<Dependency> Dependencies { get { return new[] { new Dependency(csProject.Name) }; } }

    public string Name { get { return "Test" + csProject.Name; } }

    public void Execute()
    {
      var testFilePath = Path.Combine(parameters.GetProjectCompilationDirectory(csProject), parameters.GetProjectCompilationFile(csProject));
      testRunner.Test(testFilePath);
    }

    public bool Equals(NUnitTestTask other)
    {
      return
        other != null &&
        csProject.Equals(other.csProject);
    }

    public override bool Equals(object obj)
    {
      var castedObj = obj as NUnitTestTask;
      return Equals(castedObj);
    }

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

    public override string ToString()
    {
      return String.Format("NUnit Name: {0}", csProject.Name);
    }
  }
}


text:
from io import BytesIO
import xml.etree.ElementTree as ET

from indra.statements import Statement

from indra.util import unicode_strs
from indra.util import UnicodeXMLTreeBuilder as UTB
from indra.util.statement_presentation import _get_relation_keyed_stmts

def test_unicode_tree_builder():
    xml = u'<html><bar>asdf</bar></html>'.encode('utf-8')
    xml_io = BytesIO(xml)
    tree = ET.parse(xml_io, parser=UTB())
    bar = tree.find('.//bar')
    assert unicode_strs(bar)

def test_conversion_keying():
    stmt_json = {"type": "Conversion",
                 "subj": {"name": "inflammatory response", "db_refs": {}},
                 "obj_from": [{"name": "KNG1",
                               "db_refs": {"HGNC": "6383", "UP": "P01042"}}],
                 "obj_to": [{"name": "Kallidin",
                             "db_refs": {"SCHEM": "Kallidin"}}],
                 "id": "d2361669-dfe5-45e0-914a-c96a82ad25fb"}
    stmt_list = [Statement._from_json(stmt_json)]
    stmt_list[0].agent_list()
    list(_get_relation_keyed_stmts(stmt_list))
    return


text:
<?php

namespace RKD\Banklink\Protocol\Helper;

/**
 * Protocol helper.
 *
 * Adds methdods used by multiple protocols. Such as calculating reference etc.
 *
 * @author Rene Korss <rene.korss@gmail.com>
 */
class ProtocolHelper
{
    /**
     * Calculate reference number with 7-3-1 method.
     *
     * See ENG: http://www.pangaliit.ee/en/settlements-and-standards/reference-number-of-the-invoice
     *     EST: http://www.pangaliit.ee/et/arveldused/7-3-1meetod
     *
     * @param int $orderId Order ID
     *
     * @return string Calculated reference
     */
    public static function calculateReference(int $orderId) : string
    {
        $length = strlen($orderId);

        $orderId = (string) $orderId;
        $multipliers = [7, 3, 1];
        $total = 0;
        $multiplierKey = 0;

        for ($i = $length - 1; $i >= 0; --$i) {
            $total += (int) $orderId[$i] * $multipliers[$multiplierKey];
            $multiplierKey = $multiplierKey < 2 ? ++$multiplierKey : 0;
        };

        $closestTen = ceil($total / 10) * 10;
        $checkNum = $closestTen - $total;

        return $orderId.$checkNum;
    }

    /**
     * Convert ISO-639-2 language code to ISO-639-1
     *
     * @param string $language ISO-639-2 language code
     *
     * @return string ISO-639-1 language code
     */
    public static function langToISO6391(string $language) : string
    {
        $languages = [
            'eng' => 'en',
            'est' => 'et',
            'rus' => 'ru',
            'lat' => 'lv',
            'lit' => 'lt',
            'fin' => 'fi',
            // Germany has two possible values
            'ger' => 'de',
            'deu' => 'de',
        ];

        $language = strtolower($language);

        if (array_key_exists($language, $languages)) {
            return $languages[$language];
        }

        return 'en'; // @codeCoverageIgnore
    }

    /**
     * Generates transaction number for ECommerce protocol
     *
     * Format: YYYYMM + rand between 100 000 - 999 999
     *
     * @return string Random ecuno
     */
    public static function generateEcuno() : string
    {
        $rnd   = rand(100000, 999999);
        $date  = date("Ym");
        $ecuno = $date . $rnd;

        return $ecuno;
    }

    /**
     * Multibyte str_pad
     *
     * @param mixed $input Input value
     * @param int $padLength Desired length
     * @param string $padString Pad with
     * @param int $padType Pad direction
     * @param string $encoding Encoding
     *
     * @return string Padded string
     */

    public static function mbStrPad($input, int $padLength, string $padString = ' ', int $padType = STR_PAD_RIGHT, ?string $encoding = null) : string
    {
        if (is_null($input) || strlen($input) === 0) {
            $input = '';
        }

        $diff = strlen($input) - mb_strlen($input);

        if ($encoding) {
            $diff = strlen($input) - mb_strlen($input, $encoding);
        }

        return str_pad($input, $padLength + $diff, $padString, $padType);
    }
}


text:
var types = require("hap-nodejs/accessories/types.js");
var TellduAPI = require("telldus-live");

function TelldusLivePlatform(log, config) {
    var that = this;
    that.log = log;

    that.isLoggedIn = false;

    // Login to Telldus Live!
    that.cloud = new TellduAPI.TelldusAPI({publicKey: config["public_key"], privateKey: config["private_key"]})
        .login(config["token"], config["token_secret"], function(err, user) {
            if (!!err) that.log("Login error: " + err.message);
            that.log("User logged in: " + user.firstname + " " + user.lastname + ", " + user.email);
            that.isLoggedIn = true;
        }
    );
}

TelldusLivePlatform.prototype = {

    accessories: function(callback) {
        var that = this;

        that.log("Fetching devices...");

        that.cloud.getDevices(function(err, devices) {

            if (!!err) return that.log('getDevices: ' + err.message);

            var foundAccessories = [];

            // Clean non device
            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type != 'device') {
                    devices.splice(i, 1);
                }
            }

            for (var i = 0; i < devices.length; i++) {
                if (devices[i].type === 'device') {
                    TelldusLiveAccessory.create(that.log, devices[i], that.cloud, function(err, accessory) {
                        if (!!err) that.log("Couldn't load device info");
                        foundAccessories.push(accessory);
                        if (foundAccessories.length >= devices.length) {
                            callback(foundAccessories);
                        }
                    });
                }
            }

        });
    }
};

var TelldusLiveAccessory = function TelldusLiveAccessory(log, cloud, device) {

    this.log   = log;
    this.cloud = cloud;

    var m = device.model ? device.model.split(':') : ['unknown', 'unknown'] ;

    // Set accessory info
    this.device         = device;
    this.id             = device.id;
    this.name           = device.name;
    this.manufacturer   = m[1];
    this.model          = m[0];
    this.state          = device.state;
    this.stateValue     = device.stateValue;
    this.status         = device.status;
};

TelldusLiveAccessory.create = function (log, device, cloud, callback) {

    cloud.getDeviceInfo(device, function(err, device) {

        if (!!err) that.log("Couldn't load device info");

        callback(err, new TelldusLiveAccessory(log, cloud, device));
    });
};

TelldusLiveAccessory.prototype = {

    dimmerValue: function() {

        if (this.state === 1) {
            return 100;
        }

        if (this.state === 16 && this.stateValue != "unde") {
            return parseInt(this.stateValue * 100 / 255);
        }

        return 0;
    },

    informationCharacteristics: function() {
        var that = this;

        informationCharacteristics = [
            {
                cType: types.NAME_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.name,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Name of the accessory",
                designedMaxLength: 255
            },{
                cType: types.MANUFACTURER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.manufacturer,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Manufacturer",
                designedMaxLength: 255
            },{
                cType: types.MODEL_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: that.model,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Model",
                designedMaxLength: 255
            },{
                cType: types.SERIAL_NUMBER_CTYPE,
                onUpdate: null,
                perms: ["pr"],
                format: "string",
                initialValue: "A1S2NASF88EW",
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "SN",
                designedMaxLength: 255
            },{
                cType: types.IDENTIFY_CTYPE,
                onUpdate: function () {
                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                        if (!!err) that.log("Error: " + err.message);
                        that.cloud.onOffDevice(that.device, false, function(err, result) {
                            if (!!err) that.log("Error: " + err.message);
                            that.cloud.onOffDevice(that.device, true, function(err, result) {
                                if (!!err) that.log("Error: " + err.message);
                                that.cloud.onOffDevice(that.device, false, function(err, result) {
                                    if (!!err) that.log("Error: " + err.message);
                                    that.cloud.onOffDevice(that.device, true, function(err, result) {
                                        if (!!err) that.log("Error: " + err.message);
                                    })
                                })
                            })
                        })
                    })
                },
                perms: ["pw"],
                format: "bool",
                initialValue: false,
                supportEvents: false,
                supportBonjour: false,
                manfDescription: "Identify Accessory",
                designedMaxLength: 1
            }
        ];
        return informationCharacteristics;
    },

    controlCharacteristics: function() {
        var that = this;

        cTypes = [{
            cType: types.NAME_CTYPE,
            onUpdate: null,
            perms: ["pr"],
            format: "string",
            initialValue: that.name,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Name of service",
            designedMaxLength: 255
        }]

        cTypes.push({
            cType: types.POWER_STATE_CTYPE,
            onUpdate: function(value) {
                if (value == 1) {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                } else {
                    that.cloud.onOffDevice(that.device, value, function(err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message)
                        } else {
                            that.log(that.name + " - Updated power state: " + (value === true ? 'ON' : 'OFF'));
                        }
                    });
                }
            },
            perms: ["pw","pr","ev"],
            format: "bool",
            initialValue: (that.state != 2 && (that.state === 16 && that.stateValue != "0")) ? 1 : 0,
            supportEvents: true,
            supportBonjour: false,
            manfDescription: "Change the power state",
            designedMaxLength: 1
        })

        if (that.model === "selflearning-dimmer") {
            cTypes.push({
                cType: types.BRIGHTNESS_CTYPE,
                onUpdate: function (value) {
                    that.cloud.dimDevice(that.device, (255 * (value / 100)), function (err, result) {
                        if (!!err) {
                            that.log("Error: " + err.message);
                        } else {
                            that.log(that.name + " - Updated brightness: " + value);
                        }
                    });
                },
                perms: ["pw", "pr", "ev"],
                format: "int",
                initialValue: that.dimmerValue(),
                supportEvents: true,
                supportBonjour: false,
                manfDescription: "Adjust Brightness of Light",
                designedMinValue: 0,
                designedMaxValue: 100,
                designedMinStep: 1,
                unit: "%"
            })
        }

        return cTypes
    },

    getServices: function() {

        var services = [
            {
                sType: types.ACCESSORY_INFORMATION_STYPE,
                characteristics: this.informationCharacteristics()
            },
            {
                sType: types.LIGHTBULB_STYPE,
                characteristics: this.controlCharacteristics()
            }
        ];

        return services;
    }
};

module.exports.platform = TelldusLivePlatform;
module.exports.accessory = TelldusLiveAccessory;


text:
require "minitest_helper"

module Thincloud::Authentication
  describe PasswordsMailer do

    describe "#password_reset" do
      let(:identity) do
        attrs = { email: "email@example.com", password_reset_token: "abc123" }
        Identity.new(attrs).tap{ |i| i.id = 999 }
      end

      let(:mail) { PasswordsMailer.password_reset(identity.id) }

      before do
        Identity.stubs(:find).with(999).returns(identity)
      end

      it { mail.subject.must_equal "Password Reset" }
      it { mail.to.must_equal ["email@example.com"] }
      it { mail.from.must_equal ["app@example.com"] }
      it { mail.body.encoded.must_match "To reset your password, click the URL below." }
      it { mail.body.encoded.must_match "/passwords/abc123/edit" }
    end
  end
end


text:
package com.example.tests;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import com.example.fw.ApplicationManager;
import com.example.fw.JdbcHelper;

public class Sample {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		Properties properties = new Properties();
		properties.load(new FileReader(new File("application.properties")));
		ApplicationManager app = new ApplicationManager(properties);
		System.out.println(app.getHibernateHelper().listGroups());
		System.out.println(app.getHibernateHelper().listContacts());
	}

}


text:
import HeaderSection from './section';

export default HeaderSection;

export { HeaderSection }


text:
from __future__ import absolute_import
from .bed import bed
import os
import logging
logger = logging.getLogger(__name__)

class bedSP(bed):

    _fileType = "bedSP"

    def _validateFilename(self, filePath):
        assert os.path.basename(filePath[0]).startswith(
            "nonGENIE_%s-" % self.center) and \
               os.path.basename(filePath[0]).endswith(".bed")


text:
package org.apache.nifi.cluster.coordination.http.replication;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.nifi.cluster.protocol.NodeIdentifier;

public class ResponseUtils {

    /**
     * Finds the Node Identifier for all nodes that had a 'slow' response time. A 'slow' response time
     * is defined as being more than X standard deviations from the mean response time, where X is the
     * given Standard Deviation Multiple
     *
     * @param response the AsyncClusterResponse to base the calculations off of
     * @param stdDeviationMultiple the number of standard deviations that a response time must be away from the mean in order
     *            to be considered 'slow'
     *
     * @return a Set of all Node Identifiers that took a long time to respond
     */
    public static Set<NodeIdentifier> findLongResponseTimes(final AsyncClusterResponse response, final double stdDeviationMultiple) {
        final Set<NodeIdentifier> slowResponses = new HashSet<>();

        if (response.isOlderThan(1, TimeUnit.SECONDS)) {
            // If the response is older than 2 seconds, determines if any node took a long time to respond.
            final Set<NodeIdentifier> completedIds = response.getCompletedNodeIdentifiers();

            if (completedIds.size() < 2) {
                return slowResponses;
            }

            long requestMillisSum = 0L;
            int numNodes = 0;
            for (final NodeIdentifier nodeId : completedIds) {
                final long requestMillis = response.getNodeResponse(nodeId).getRequestDuration(TimeUnit.NANOSECONDS);
                if (requestMillis < 0) {
                    continue;
                }

                requestMillisSum += requestMillis;
                numNodes++;
            }

            if (numNodes < 2) {
                return slowResponses;
            }

            final double mean = requestMillisSum / numNodes;
            double differenceSquaredSum = 0D;
            for (final NodeIdentifier nodeId : completedIds) {
                final long requestMillis = response.getNodeResponse(nodeId).getRequestDuration(TimeUnit.NANOSECONDS);
                final double differenceSquared = Math.pow(mean - requestMillis, 2);
                differenceSquaredSum += differenceSquared;
            }

            final double meanOfDifferenceSquared = differenceSquaredSum / numNodes;
            final double stdDev = Math.pow(meanOfDifferenceSquared, 0.5D);
            final double longTimeThreshold = mean + stdDev * stdDeviationMultiple;

            for (final NodeIdentifier nodeId : completedIds) {
                final long requestMillis = response.getNodeResponse(nodeId).getRequestDuration(TimeUnit.NANOSECONDS);
                if (requestMillis > longTimeThreshold) {
                    slowResponses.add(nodeId);
                }
            }
        }

        return slowResponses;
    }
}


text:
package org.apache.kylin.storage.hbase.steps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.kylin.engine.mr.HadoopUtil;
import org.apache.kylin.engine.mr.JobBuilderSupport;
import org.apache.kylin.job.engine.JobEngineConfig;
import org.apache.kylin.job.exception.ExecuteException;
import org.apache.kylin.job.execution.AbstractExecutable;
import org.apache.kylin.job.execution.ExecutableContext;
import org.apache.kylin.job.execution.ExecuteResult;
import org.apache.kylin.storage.hbase.HBaseConnection;

import com.google.common.collect.Lists;

/**
 * Created by sunyerui on 15/9/17.
 */
public class HDFSPathGarbageCollectionStep extends AbstractExecutable {

    public static final String TO_DELETE_PATHS = "toDeletePaths";
    private StringBuffer output;
    private JobEngineConfig config;

    public HDFSPathGarbageCollectionStep() {
        super();
        output = new StringBuffer();
    }

    @Override
    protected ExecuteResult doWork(ExecutableContext context) throws ExecuteException {
        try {
            config = new JobEngineConfig(context.getConfig());
            List<String> toDeletePaths = getDeletePaths();
            dropHdfsPathOnCluster(toDeletePaths, FileSystem.get(HadoopUtil.getCurrentConfiguration()));

            if (StringUtils.isNotEmpty(context.getConfig().getHBaseClusterFs())) {
                dropHdfsPathOnCluster(toDeletePaths, FileSystem.get(HBaseConnection.getCurrentHBaseConfiguration()));
            }
        } catch (IOException e) {
            logger.error("job:" + getId() + " execute finished with exception", e);
            output.append("\n").append(e.getLocalizedMessage());
            return new ExecuteResult(ExecuteResult.State.ERROR, output.toString());
        }

        return new ExecuteResult(ExecuteResult.State.SUCCEED, output.toString());
    }

    private void dropHdfsPathOnCluster(List<String> oldHdfsPaths, FileSystem fileSystem) throws IOException {
        if (oldHdfsPaths != null && oldHdfsPaths.size() > 0) {
            logger.debug("Drop HDFS path on FileSystem: " + fileSystem.getUri());
            output.append("Drop HDFS path on FileSystem: \"" + fileSystem.getUri() + "\" \n");
            for (String path : oldHdfsPaths) {
                if (path.endsWith("*"))
                    path = path.substring(0, path.length() - 1);

                Path oldPath = new Path(path);
                if (fileSystem.exists(oldPath)) {
                    fileSystem.delete(oldPath, true);
                    logger.debug("HDFS path " + path + " is dropped.");
                    output.append("HDFS path " + path + " is dropped.\n");
                } else {
                    logger.debug("HDFS path " + path + " not exists.");
                    output.append("HDFS path " + path + " not exists.\n");
                }
                // If hbase was deployed on another cluster, the job dir is empty and should be dropped,
                // because of rowkey_stats and hfile dirs are both dropped.
                if (fileSystem.listStatus(oldPath.getParent()).length == 0) {
                    Path emptyJobPath = new Path(JobBuilderSupport.getJobWorkingDir(config, getJobId()));
                    if (fileSystem.exists(emptyJobPath)) {
                        fileSystem.delete(emptyJobPath, true);
                        logger.debug("HDFS path " + emptyJobPath + " is empty and dropped.");
                        output.append("HDFS path " + emptyJobPath + " is empty and dropped.\n");
                    }
                }
            }
        }
    }

    public void setDeletePaths(List<String> deletePaths) {
        setArrayParam(TO_DELETE_PATHS, deletePaths);
    }

    public void setJobId(String jobId) {
        setParam("jobId", jobId);
    }

    public List<String> getDeletePaths() {
        return getArrayParam(TO_DELETE_PATHS);
    }

    public String getJobId() {
        return getParam("jobId");
    }

    private void setArrayParam(String paramKey, List<String> paramValues) {
        setParam(paramKey, StringUtils.join(paramValues, ","));
    }

    private List<String> getArrayParam(String paramKey) {
        final String ids = getParam(paramKey);
        if (ids != null) {
            final String[] splitted = StringUtils.split(ids, ",");
            ArrayList<String> result = Lists.newArrayListWithExpectedSize(splitted.length);
            for (String id : splitted) {
                result.add(id);
            }
            return result;
        } else {
            return Collections.emptyList();
        }
    }
}


text: Machine Learning home work assignment number 2


text:
var React = require('react');
var ReactDOM = require('react-dom');

var QuoteMaker = React.createClass({
  render: function () {
    return (

          What is important now is to recover our senses.

            Susan Sontag

    );
  }
});

ReactDOM.render(
  <QuoteMaker />,
  document.getElementById('app')
);


text:
#ifndef RL_WINDOWS_HPP
#define RL_WINDOWS_HPP
#ifdef _MSC_VER
#   pragma once
#endif

#include "mutex.hpp"
#include "condition_variable.hpp"
#include "semaphore.hpp"
#include "event.hpp"

namespace rl
{

typedef win_object* rl_HANDLE;
unsigned long const rl_INFINITE = (unsigned long)-1;

unsigned long const rl_WAIT_FAILED                = (unsigned long)-1;
unsigned long const rl_WAIT_OBJECT_0              = 100;
unsigned long const rl_WAIT_TIMEOUT               = 1;
unsigned long const rl_WAIT_IO_COMPLETION         = 2;
unsigned long const rl_MAXIMUM_WAIT_OBJECTS       = wfmo_max_objects;

inline int rl_SwitchToThread(debug_info_param info)
{
    yield(1, info);
    return 1;
}

inline void rl_Sleep(unsigned long milliseconds, debug_info_param info)
{
    yield(milliseconds ? milliseconds : 1, info);
}

inline unsigned long rl_WaitForSingleObjectEx(rl_HANDLE obj, unsigned long timeout, int alertable, debug_info_param info)
{
    (void)alertable; //!!! not yet supported – support it!
    //!!! support WAIT_IO_COMPLETION
    RL_VERIFY(false == alertable && "Alertable wait is not supported in WaitForSingleObject() yet");

    bool try_wait = (timeout == 0);
    bool is_timed = (timeout != rl_INFINITE);
    sema_wakeup_reason reason = static_cast<win_waitable_object*>(obj)->wait(try_wait, is_timed, info);
    if (reason == sema_wakeup_reason_success)
        return rl_WAIT_OBJECT_0;
    else if (reason == sema_wakeup_reason_timeout)
        return rl_WAIT_TIMEOUT;
    else if (reason == sema_wakeup_reason_failed)
        return rl_WAIT_TIMEOUT;
    RL_VERIFY(false);
    return rl_WAIT_FAILED;
}

inline unsigned long rl_WaitForSingleObject(rl_HANDLE obj, unsigned long timeout, debug_info_param info)
{
    return rl_WaitForSingleObjectEx(obj, timeout, 0, info);
}

inline unsigned long rl_WaitForMultipleObjectsEx(unsigned long count, rl_HANDLE* objects, int wait_all, unsigned long timeout, int alertable, debug_info_param info)
{
    (void)alertable; //!!!
    //!!! support WAIT_IO_COMPLETION
    RL_VERIFY(false == alertable && "Alertable wait is not supported in WaitForMultipleObjects() yet");

    bool try_wait = (timeout == 0);
    bool is_timed = (timeout != rl_INFINITE);
    win_waitable_object** obj = reinterpret_cast<win_waitable_object**>(objects);
    size_t signaled = 0;
    sema_wakeup_reason reason = wait_for_multiple_objects(signaled, count, obj, !!wait_all, try_wait, is_timed, info);
    if (reason == sema_wakeup_reason_success)
        return rl_WAIT_OBJECT_0 + (int)signaled;
    else if (reason == sema_wakeup_reason_timeout)
        return rl_WAIT_TIMEOUT;
    RL_VERIFY(false);
    return rl_WAIT_FAILED;
}

inline unsigned long rl_WaitForMultipleObjects(unsigned long count, rl_HANDLE* objects, int wait_all, unsigned long timeout, debug_info_param info)
{
    return rl_WaitForMultipleObjectsEx(count, objects, wait_all, timeout, 0, info);
}

inline unsigned long rl_SignalObjectAndWait(rl_HANDLE obj_to_signal,
                                            rl_HANDLE obj_to_wait,
                                            unsigned long timeout,
                                            int alertable,
                                            debug_info_param info)
{
    bool result = static_cast<win_waitable_object*>(obj_to_signal)->signal(info);
    if (false == result)
        return result ? 1 : 0;
    preemption_disabler pd (ctx());
    return rl_WaitForSingleObjectEx(obj_to_wait, timeout, alertable, info);
}

struct sem_tag_win;

inline rl_HANDLE rl_CreateSemaphore(void* /*security*/, long initial_count, long max_count, void const* /*name*/, debug_info_param info)
{
    void* mem = ctx().alloc(sizeof(semaphore<sem_tag_win>), false, info);
    semaphore<sem_tag_win>* sema = new (mem) semaphore<sem_tag_win>;
    sema->init(false, initial_count, max_count, info);
    return sema;
}

inline int rl_CloseHandle(rl_HANDLE h, debug_info_param info)
{
    h->deinit(info);
    h->~win_object();
    (ctx().free)(h, false, info); //!!! rename free because of the define
    return 1;
}

inline int rl_ReleaseSemaphore(rl_HANDLE sema, long count, long* prev_count, debug_info_param info)
{
    unsigned prev = 0;
    bool result = static_cast<semaphore<sem_tag_win>*>(sema)->post(count, prev, info);
    if (prev_count)
        prev_count[0] = prev;
    return result ? 1 : 0;
}

inline rl_HANDLE rl_CreateEvent(void* /*security*/, int manual_reset, int initial_state, void const* /*name*/, debug_info_param info)
{
    void* mem = ctx().alloc(sizeof(generic_event), false, info);
    generic_event* ev = new (mem) generic_event;
    ev->init(!!manual_reset, !!initial_state, info);
    return ev;
}

inline int rl_SetEvent(rl_HANDLE ev, debug_info_param info)
{
    static_cast<generic_event*>(ev)->set(info);
    return 1;
}

inline int rl_ResetEvent(rl_HANDLE ev, debug_info_param info)
{
    static_cast<generic_event*>(ev)->reset(info);
    return 1;
}

inline int rl_PulseEvent(rl_HANDLE ev, debug_info_param info)
{
    static_cast<generic_event*>(ev)->pulse(info);
    return 1;
}

struct mutex_tag_win_cs;
typedef generic_mutex<mutex_tag_win_cs> rl_CRITICAL_SECTION;

inline void rl_InitializeCriticalSection(rl_CRITICAL_SECTION* m, debug_info_param info)
{
    m->init(false, true, false, false, info);
}

inline int rl_InitializeCriticalSectionAndSpinCount(rl_CRITICAL_SECTION* m, unsigned long spin_count, debug_info_param info)
{
    (void)spin_count;
    m->init(false, true, false, false, info);
    return 1;
}

inline int rl_InitializeCriticalSectionEx(rl_CRITICAL_SECTION* m, unsigned long spin_count, unsigned long flags, debug_info_param info)
{
    (void)spin_count;
    (void)flags;
    m->init(false, true, false, false, info);
    return 1;
}

inline void rl_DeleteCriticalSection(rl_CRITICAL_SECTION* m, debug_info_param info)
{
    m->deinit(info);
}

inline void rl_EnterCriticalSection(rl_CRITICAL_SECTION* m, debug_info_param info)
{
    m->lock_exclusive(info);
}

inline int rl_TryEnterCriticalSection(rl_CRITICAL_SECTION* m, debug_info_param info)
{
    return m->try_lock_exclusive(info) ? 1 : 0;
}

inline void rl_LeaveCriticalSection(rl_CRITICAL_SECTION* m, debug_info_param info)
{
    m->unlock_exclusive(info);
}

struct mutex_tag_win_srwl;
typedef generic_mutex<mutex_tag_win_srwl> rl_SRWLOCK;

inline void rl_InitializeSRWLock(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->init(true, false, false, false, info);
}

inline void rl_AcquireSRWLockExclusive(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->lock_exclusive(info);
}

inline void rl_AcquireSRWLockShared(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->lock_shared(info);
}

inline void rl_ReleaseSRWLockExclusive(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->unlock_exclusive(info);
}

inline void rl_ReleaseSRWLockShared(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->unlock_shared(info);
}

//!!!
inline void rl_DeleteSRWLock(rl_SRWLOCK* lock, debug_info_param info)
{
    lock->deinit(info);
}

struct mutex_tag_win_mutex;
typedef generic_mutex<mutex_tag_win_mutex> rl_win_mutex;

inline rl_HANDLE rl_CreateMutex(void* /*security*/, int initial_owner, void const* /*name*/, debug_info_param info)
{
    void* mem = ctx().alloc(sizeof(rl_win_mutex), false, info);
    rl_win_mutex* mtx = new (mem) rl_win_mutex ();
    mtx->init(false, true, false, false, info);
    if (initial_owner)
        mtx->lock_exclusive(info);
    return mtx;
}

inline int rl_ReleaseMutex(rl_HANDLE mtx, debug_info_param info)
{
    static_cast<rl_win_mutex*>(mtx)->unlock_exclusive(info);
    return 1;

}

struct condvar_tag_win;
typedef condvar<condvar_tag_win> rl_CONDITION_VARIABLE;
unsigned long const rl_CONDITION_VARIABLE_LOCKMODE_SHARED = 1;

inline void rl_InitializeConditionVariable(rl_CONDITION_VARIABLE* cv, debug_info_param info)
{
    cv->init(false, info);
}

inline int rl_SleepConditionVariableCS(rl_CONDITION_VARIABLE* cv, rl_CRITICAL_SECTION* cs, unsigned long ms, debug_info_param info)
{
    cv->wait(*cs, ms != rl_INFINITE, info);
    return 0;
}

inline int rl_SleepConditionVariableSRW(rl_CONDITION_VARIABLE* cv, rl_SRWLOCK* lock, unsigned long ms, unsigned long flags, debug_info_param info)
{
    //!!! CONDITION_VARIABLE_LOCKMODE_SHARED
    (void)flags;
    cv->wait(*lock, ms != rl_INFINITE, info);
    return 0;
}

inline void rl_WakeAllConditionVariable(rl_CONDITION_VARIABLE* cv, debug_info_param info)
{
    cv->notify_all(info);
}

inline void rl_WakeConditionVariable(rl_CONDITION_VARIABLE* cv, debug_info_param info)
{
    cv->notify_one(info);
}

inline void rl_DeleteConditionVariable(rl_CONDITION_VARIABLE* cv, debug_info_param info)
{
    cv->deinit(info);
}

typedef unsigned long (RL_STDCALL *rl_WIN_START_ROUTINE)(void* param);
typedef unsigned (RL_STDCALL *rl_MSVCR_THREAD_ROUTINE)(void* param);

template<typename thread_fn_t>
struct win32_thread_helper
{
    thread_fn_t fn;
    void* param;

    static void* thread(void* p)
    {
        win32_thread_helper* self = (win32_thread_helper*)p;
        void* result = (void*)(uintptr_t)(self->fn(self->param));
        delete_impl(self, $);
        return result;
    }
};

inline rl_HANDLE rl_CreateThread(void* security, unsigned stack_size, rl_WIN_START_ROUTINE fn, void* param, unsigned long creation_flags, unsigned long* thread_id, debug_info_param info)
{
    (void)security;
    (void)stack_size;
    (void)creation_flags;
    (void)thread_id;

    void* mem =
        ctx().alloc(sizeof(win32_thread_helper<rl_WIN_START_ROUTINE>), false, info);
    win32_thread_helper<rl_WIN_START_ROUTINE>* arg =
        new (mem) win32_thread_helper<rl_WIN_START_ROUTINE>;
    arg->fn = fn;
    arg->param = param;
    win_waitable_object* handle = ctx().create_thread(&win32_thread_helper<rl_WIN_START_ROUTINE>::thread, arg);
    return handle;
}

inline uintptr_t rl_beginthreadex(void *security, unsigned stack_size, rl_MSVCR_THREAD_ROUTINE start_address, void *arglist, unsigned initflag, unsigned* thrdaddr, debug_info_param info)
{
    (void)security;
    (void)stack_size;
    (void)initflag;
    (void)thrdaddr;

    void* mem = ctx().alloc(sizeof(win32_thread_helper<rl_MSVCR_THREAD_ROUTINE>), false, info);
    win32_thread_helper<rl_MSVCR_THREAD_ROUTINE>* arg =
        new (mem) win32_thread_helper<rl_MSVCR_THREAD_ROUTINE>;
    arg->fn = start_address;
    arg->param = arglist;
    win_waitable_object* handle = ctx().create_thread(&win32_thread_helper<rl_MSVCR_THREAD_ROUTINE>::thread, arg);
    return (uintptr_t)handle;
}

inline unsigned long rl_SetThreadAffinityMask(rl_HANDLE th, unsigned long affinity_mask, debug_info_param info)
{
    (void)(th);
    (void)(affinity_mask);
    (void)info;
    return 0;
}

inline int rl_SuspendThread(rl_HANDLE th, debug_info_param info)
{
    (void)th;
    (void)info;
    return 1;
}

inline int rl_ResumeThread(rl_HANDLE th, debug_info_param info)
{
    (void)th;
    (void)info;
    return 1;
}

inline unsigned long GetLastError()
{
    return (unsigned long)get_errno();
}

inline void SetLastError(unsigned long value)
{
    set_errno((int)value);
}

inline void rl_FlushProcessWriteBuffers(debug_info_param info)
{
    systemwide_fence(info);
}

}

#ifdef HANDLE
#   undef HANDLE
#endif
#define HANDLE rl::rl_HANDLE

#ifdef INFINITE
#   undef INFINITE
#endif
#define INFINITE rl::rl_INFINITE

#ifdef WAIT_FAILED
#   undef WAIT_FAILED
#endif
#define WAIT_FAILED rl::rl_WAIT_FAILED

#ifdef WAIT_OBJECT_0
#   undef WAIT_OBJECT_0
#endif
#define WAIT_OBJECT_0 rl::rl_WAIT_OBJECT_0

#ifdef WAIT_TIMEOUT
#   undef WAIT_TIMEOUT
#endif
#define WAIT_TIMEOUT rl::rl_WAIT_TIMEOUT

#ifdef WAIT_IO_COMPLETION
#   undef WAIT_IO_COMPLETION
#endif
#define WAIT_IO_COMPLETION rl::rl_WAIT_IO_COMPLETION

#ifdef MAXIMUM_WAIT_OBJECTS
#   undef MAXIMUM_WAIT_OBJECTS
#endif
#define MAXIMUM_WAIT_OBJECTS rl::rl_MAXIMUM_WAIT_OBJECTS

#define SwitchToThread() \
 rl::rl_SwitchToThread($)

#define Sleep(milliseconds) \
 rl::rl_Sleep(milliseconds, $)

#define CloseHandle(obj) \
 rl::rl_CloseHandle(obj, $)

#define WaitForSingleObject(obj, timeout) \
 rl::rl_WaitForSingleObject(obj, timeout, $)

#define WaitForMultipleObjects(count, objects, wait_all, timeout) \
 rl::rl_WaitForMultipleObjects(count, objects, wait_all, timeout, $)

#define WaitForMultipleObjectsEx(count, objects, wait_all, timeout, alertable)] \
 rl::rl_WaitForMultipleObjectsEx(count, objects, wait_all, timeout, alertable, $)

#define SignalObjectAndWait(obj_to_signal, obj_to_wait, timeout, alertable) \
 rl::rl_SignalObjectAndWait(obj_to_signal, obj_to_wait, timeout, alertable, $)

#ifdef CreateSemaphore
#   undef CreateSemaphore
#endif

#ifdef CreateSemaphore
#   undef ReleaseSemaphore
#endif

#define CreateSemaphoreA rl_CreateSemaphore
#define CreateSemaphoreW rl_CreateSemaphore
#define CreateSemaphore rl_CreateSemaphore
#define rl_CreateSemaphore(security, initial_count, max_count, name) \
    rl::rl_CreateSemaphore(security, initial_count, max_count, name, $)\

#define ReleaseSemaphore(sema, count, prev_count) \
 rl::rl_ReleaseSemaphore(sema, count, prev_count, $)

#ifdef CreateEvent
#   undef CreateEvent
#endif
#define CreateEventA rl_CreateEvent
#define CreateEventW rl_CreateEvent
#define CreateEvent rl_CreateEvent
#define rl_CreateEvent(security, manual_reset, initial_state, name)\
    rl::rl_CreateEvent(security, manual_reset, initial_state, name, $)

#define SetEvent(ev)\
 rl::rl_SetEvent(ev, $)

#define ResetEvent(ev)\
 rl::rl_ResetEvent(ev, $)

#define PulseEvent(ev)\
 rl::rl_PulseEvent(ev, $)

#ifdef CreateMutex
#   undef CreateMutex
#endif
#define CreateMutexA rl_CreateMutex
#define CreateMutexW rl_CreateMutex
#define CreateMutex rl_CreateMutex
#define rl_CreateMutex(security, initial_owner, name)\
    rl::rl_CreateMutex(security, initial_owner, name, $)

#define ReleaseMutex(mtx)\
 rl::rl_ReleaseMutex(mtx, $)

#define CRITICAL_SECTION rl::rl_CRITICAL_SECTION

#define InitializeCriticalSection(cs) \
 rl::rl_InitializeCriticalSection(cs, $)

#define InitializeCriticalSectionAndSpinCount(cs, spin) \
 rl::rl_InitializeCriticalSectionAndSpinCount(cs, spin, $)

#define InitializeCriticalSectionEx(cs, spin, flags) \
 rl::rl_InitializeCriticalSectionEx(cs, spin, flags, $)

#define DeleteCriticalSection(cs) \
 rl::rl_DeleteCriticalSection(cs, $)

#define EnterCriticalSection(cs) \
 rl::rl_EnterCriticalSection(cs, $)

#define TryEnterCriticalSection(cs) \
 rl::rl_TryEnterCriticalSection(cs, $)

#define LeaveCriticalSection(cs) \
 rl::rl_LeaveCriticalSection(cs, $)

#define SRWLOCK rl::rl_SRWLOCK

#define InitializeSRWLock(lock) \
 rl::rl_InitializeSRWLock(lock, $)

#define AcquireSRWLockExclusive(lock) \
 rl::rl_AcquireSRWLockExclusive(lock, $)

#define AcquireSRWLockShared(lock) \
 rl::rl_AcquireSRWLockShared(lock, $)

#define ReleaseSRWLockExclusive(lock) \
 rl::rl_ReleaseSRWLockExclusive(lock, $)

#define ReleaseSRWLockShared(lock) \
 rl::rl_ReleaseSRWLockShared(lock, $)

//!!! no such function in WIN API
#define DeleteSRWLock(lock) \
 rl::rl_DeleteSRWLock(lock, $)

#define CONDITION_VARIABLE rl::rl_CONDITION_VARIABLE

#ifdef CONDITION_VARIABLE_LOCKMODE_SHARED
#   undef CONDITION_VARIABLE_LOCKMODE_SHARED
#endif
#define CONDITION_VARIABLE_LOCKMODE_SHARED rl::rl_CONDITION_VARIABLE_LOCKMODE_SHARED

#define InitializeConditionVariable(cv) \
 rl::rl_InitializeConditionVariable(cv, $)

#define SleepConditionVariableCS(cv, cs, ms) \
 rl::rl_SleepConditionVariableCS(cv, cs, ms, $)

#define SleepConditionVariableSRW(cv, lock, ms, flags) \
 rl::rl_SleepConditionVariableSRW(cv, lock, ms, flags, $)

#define WakeAllConditionVariable(cv) \
 rl::rl_WakeAllConditionVariable(cv, $)

#define WakeConditionVariable(cv) \
 rl::rl_WakeConditionVariable(cv, $)

//!!! no such function in WIN API
#define DeleteConditionVariable(cv) \
 rl::rl_DeleteConditionVariable(cv, $)

#define CreateThread(security, stack_size, fn, param, creation_flags, thread_id) \
 rl::rl_CreateThread(security, stack_size, fn, param, creation_flags, thread_id, $)

#define _beginthreadex(security, stack_size, start_address, arglist, initflag, thrdaddr) \
  rl::rl_beginthreadex(security, stack_size, start_address, arglist, initflag, thrdaddr, $)

#define SetThreadAffinityMask(th, affinity_mask) \
 rl::rl_SetThreadAffinityMask(th, affinity_mask, $)

#define SuspendThread(th) \
 rl::rl_SuspendThread(th, $)

#define ResumeThread(th) \
 rl::rl_ResumeThread(th, $)

#define FlushProcessWriteBuffers() \
 rl::rl_FlushProcessWriteBuffers($)

#endif


text:
from __future__ import print_function
import sys
import pmagpy.pmag as pmag
#
#

def main():
    """
    NAME
        parse_measurements.py

    DESCRIPTION
        takes measurments file and creates specimen and instrument files

    SYNTAX
        parse_measurements.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE magic_measurements input file, default is "magic_measurements.txt"
        -fsi FILE er_sites input file, default is none
        -Fsp  FILE specimen output er_specimens format file, default is "er_specimens.txt"
        -Fin FILE instrument output  magic_instruments format file, default is "magic_instruments.txt"
    OUPUT
        writes er_specimens and magic_instruments formatted files

    """
    infile = 'magic_measurements.txt'
    sitefile = ""
    specout = "er_specimens.txt"
    instout = "magic_instruments.txt"
# get command line stuff
    if "-h" in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        infile = sys.argv[ind + 1]
    if '-fsi' in sys.argv:
        ind = sys.argv.index("-fsi")
        sitefile = sys.argv[ind + 1]
    if '-Fsp' in sys.argv:
        ind = sys.argv.index("-Fsp")
        specout = sys.argv[ind + 1]
    if '-Fin' in sys.argv:
        ind = sys.argv.index("-Fin")
        instout = sys.argv[ind + 1]
    if '-WD' in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
        infile = dir_path + '/' + infile
        if sitefile != "":
            sitefile = dir_path + '/' + sitefile
        specout = dir_path + '/' + specout
        instout = dir_path + '/' + instout
# now do re-ordering
    pmag.ParseMeasFile(infile, sitefile, instout, specout)

if __name__ == "__main__":
    main()


text:
package org.codelibs.fess.suggest.analysis;

import java.util.List;

import org.opensearch.action.admin.indices.analyze.AnalyzeAction.AnalyzeToken;

public interface SuggestAnalyzer {
    List<AnalyzeToken> analyze(String text, String field, String lang);

    List<AnalyzeToken> analyzeAndReading(String text, String field, String lang);
}