<commit_before>
// Make JsGlobal alert: 'something' work out of the box
// Not really needed... !? TODO this object should be accessible through a js-keyword or something, parse it directly instead of JsGlobal
var JsGlobal = this;

// Each function can be instantiated like a Squeak-object. This feels kind of like a hack... TODO Is there a cleaner way?
Function.prototype._new = function(){
 var obj = {};
 this.apply(obj, arguments);
 return obj;
};

// Function called when a method with an unimplemented primitive declaration is called
var primitiveDeclaration = function(){ alert("Primitive has been called!!! The code is: \n\n" + arguments.callee.caller) };

// instead of bool(true) and bool(false) (which would be the equivalent to string(""), number(2) etc.)
var _true = True._newInstance();
var _false = False._newInstance();
var nil = null; //UndefinedObject._newInstance();

//
// Each object can convert itself into a js-only version. Used to unpack primitive values like Strings and Numbers from
// their Squeak-wrapper-objects. As short as possible, as it is called on every argument of js-library-calls.
// A js-function is also added to the prototype of the js-primitive Object (but at the very end of all our scripts).
//
_Object._addInstanceMethods( { js: function() {
	alert("Trying to pass a Squeak-object into a javascript-library-call! " + this); } } );
False._addInstanceMethods( { js: function() { return false; } } );
True._addInstanceMethods( { js: function() { return true; } } );
ByteString._addInstanceMethods( { js: function() { return this.string$; } } );
_Number._addInstanceMethods( { js: function() { return this.num$; } } );
Character._addInstanceMethods( { js: function() { return this.character$; } } );
_Array._addInstanceMethods( { js: function() { return this.arr$; } } );
BlockClosure._addInstanceMethods( { js: function() {
	return this.func$; } } );

//
// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
//

// the compiled code does not use this (uses _true/_false) directly. Can use this in kernel_primitives.js etc.
var bool = function(aBool) {
  if (aBool) {
	return _true;
  } else {
	return _false;
  }
}

var character = function(aString) {
  var resultCharacter = Character._newInstance();
  resultCharacter.character$ = aString;
  return resultCharacter;
}

var string = function(aString) {
  var resultString = ByteString._newInstance();
  resultString.string$ = aString;
  return resultString;
}

var number = function(number) {
  var resultNumber = Float._newInstance();
  resultNumber.num$ = number;
  return resultNumber;
}

var array = function(anArray) {
  var resultArray = _Array._newInstance();
  resultArray.arr$ = anArray;
  return resultArray;
}

var block = function(func, that) {
	var b = BlockClosure._newInstance();
	b.creationContext$ = arguments.callee.caller;

	b.func$ = function() {
		try {
			ret = func.apply(that, arguments);
			if (ret != undefined) {
			  if(ret.creationContext$ == func) {
				  ret.creationContext$ = this.creationContext$;
			  }
		  }
			return ret;
		}
		catch(e) {
			if(e == func) {
				this.creationContext$.nonLocalReturnValue = e.nonLocalReturnValue;
				throw this.creationContext$;
			}
			else {
				throw e;
			}
		}
	}
	b.func$.creationContext$ = arguments.callee.caller;

	return b;
};<commit_msg>activated using UndefinedObject<commit_after>
// Make JsGlobal alert: 'something' work out of the box
// Not really needed... !? TODO this object should be accessible through a js-keyword or something, parse it directly instead of JsGlobal
var JsGlobal = this;

// Each function can be instantiated like a Squeak-object. This feels kind of like a hack... TODO Is there a cleaner way?
Function.prototype._new = function(){
 var obj = {};
 this.apply(obj, arguments);
 return obj;
};

// Function called when a method with an unimplemented primitive declaration is called
var primitiveDeclaration = function(){ alert("Primitive has been called!!! The code is: \n\n" + arguments.callee.caller) };

// instead of bool(true) and bool(false) (which would be the equivalent to string(""), number(2) etc.)
var _true = True._newInstance();
var _false = False._newInstance();
var nil = UndefinedObject._newInstance();

//
// Each object can convert itself into a js-only version. Used to unpack primitive values like Strings and Numbers from
// their Squeak-wrapper-objects. As short as possible, as it is called on every argument of js-library-calls.
// A js-function is also added to the prototype of the js-primitive Object (but at the very end of all our scripts).
//
_Object._addInstanceMethods( { js: function() {
	alert("Trying to pass a Squeak-object into a javascript-library-call! " + this); } } );
False._addInstanceMethods( { js: function() { return false; } } );
True._addInstanceMethods( { js: function() { return true; } } );
ByteString._addInstanceMethods( { js: function() { return this.string$; } } );
_Number._addInstanceMethods( { js: function() { return this.num$; } } );
Character._addInstanceMethods( { js: function() { return this.character$; } } );
_Array._addInstanceMethods( { js: function() { return this.arr$; } } );
BlockClosure._addInstanceMethods( { js: function() {
	return this.func$; } } );

//
// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
//

// the compiled code does not use this (uses _true/_false) directly. Can use this in kernel_primitives.js etc.
var bool = function(aBool) {
  if (aBool) {
	return _true;
  } else {
	return _false;
  }
}

var character = function(aString) {
  var resultCharacter = Character._newInstance();
  resultCharacter.character$ = aString;
  return resultCharacter;
}

var string = function(aString) {
  var resultString = ByteString._newInstance();
  resultString.string$ = aString;
  return resultString;
}

var number = function(number) {
  var resultNumber = Float._newInstance();
  resultNumber.num$ = number;
  return resultNumber;
}

var array = function(anArray) {
  var resultArray = _Array._newInstance();
  resultArray.arr$ = anArray;
  return resultArray;
}

var block = function(func, that) {
	var b = BlockClosure._newInstance();
	b.creationContext$ = arguments.callee.caller;

	b.func$ = function() {
		try {
			ret = func.apply(that, arguments);
			if (ret != undefined) {
			  if(ret.creationContext$ == func) {
				  ret.creationContext$ = this.creationContext$;
			  }
		  }
			return ret;
		}
		catch(e) {
			if(e == func) {
				this.creationContext$.nonLocalReturnValue = e.nonLocalReturnValue;
				throw this.creationContext$;
			}
			else {
				throw e;
			}
		}
	}
	b.func$.creationContext$ = arguments.callee.caller;

	return b;
};<|endoftext|>


<commit_before>/* =========================================================
 * MomentDatepicker
 * Based on http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Andres Moschini
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function ($, moment) {

    // Picker object

    var Datepicker = function (element, options) {
        this.element = $(element);
        this.autoHide = true && (options.autoHide !== false) && (this.element.data('datepicker-autohide') !== false);
        this.format = options.format || this.element.data('datepicker-format') || moment.longDateFormat.L;
        this.picker = $(DPGlobal.template)
							.appendTo('body')
							.on({
							    click: $.proxy(this.click, this),
							    mousedown: $.proxy(this.mousedown, this)
							});
        this.isInput = this.element.is('input');
        this.component = !this.isInput && this.element.is('.date') ? this.element.find('.add-on') : false;

        if (this.isInput) {
            this.element.on({
                focus: $.proxy(this.show, this),
                blur: $.proxy(function (e) {
                    this.hide();
                    this.triggerChangeDate();
                }, this),
                input: $.proxy(function (e) {
                    this.updateFromValue(true);
                }, this),
                keyup: $.proxy(function (e) {
                    if (e.keyCode == 13)
                        this.updateFromValue();
                }, this),
                click: $.proxy(this.show, this)
            });
        } else {
            if (this.component) {
                this.component.on('click', $.proxy(this.show, this));
            } else {
                this.element.on('click', $.proxy(this.show, this));
            }
        }
        this.minViewMode = options.minViewMode || this.element.data('datepicker-minviewmode') || 0;
        if (typeof this.minViewMode === 'string') {
            switch (this.minViewMode) {
                case 'months':
                    this.minViewMode = 1;
                    break;
                case 'years':
                    this.minViewMode = 2;
                    break;
                default:
                    this.minViewMode = 0;
                    break;
            }
        }
        this.viewMode = options.viewMode || this.element.data('datepicker-viewmode') || 0;
        if (typeof this.viewMode === 'string') {
            switch (this.viewMode) {
                case 'months':
                    this.viewMode = 1;
                    break;
                case 'years':
                    this.viewMode = 2;
                    break;
                default:
                    this.viewMode = 0;
                    break;
            }
        }
        this.startViewMode = this.viewMode;
        this.weekStart = options.weekStart || this.element.data('datepicker-weekstart') || 0;
        this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
        this.fillDow();
        this.fillMonths();
        this.updateFromValue();
        this.showMode();
        this.refresh();
    };

    Datepicker.prototype = {
        constructor: Datepicker,
        get: function () {
            return (this.moment && this.moment.clone());
        },
        getAsText: function (format) {
            return (this.moment && this.moment.format(format || this.format));
        },
        show: function (e) {
            this.picker.show();
            this.height = (this.component && this.component.outerHeight()) || this.element.outerHeight();
            this.place();
            $(window).on('resize', $.proxy(this.place, this));
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }
            if (!this.isInput) {
                $(document).on('mousedown', $.proxy(this.hide, this));
            }
            this.element.trigger({
                type: 'show'
            });
        },

        hide: function () {
            this.picker.hide();
            $(window).off('resize', this.place);
            this.viewMode = this.startViewMode;
            this.showMode();
            if (!this.isInput) {
                $(document).off('mousedown', this.hide);
            }
            this.refresh();
            this.element.trigger({
                type: 'hide'
            });
        },

        refresh: function () {
            var formated = this.getAsText();

            if (!this.isInput) {
                if (this.component) {
                    this.element.find('input').prop('value', formated).change();
                }
                this.element.data('date', formated).change();
            } else {
                this.element.prop('value', formated).change();
            }
        },

        set: function (newDate, ommitEvent) {
            this.update(newDate, ommitEvent);
            this.refresh();
        },

        place: function () {
            var offset = this.component ? this.component.offset() : this.element.offset();
            this.picker.css({
                top: offset.top + this.height,
                left: offset.left
            });
        },
        lastValue: null,
        triggerChangeDate: function () {
            var newValue = this.moment ? this.moment.valueOf() : null;
            if (newValue != this.lastValue) {
                this.lastValue = newValue;
                this.element.trigger({
                    type: 'changeDate'
                });
            }
            if (this.autoHide)
                this.hide();
        },
        updateFromValue: function (ommitEvent) {
            this.update(this.isInput ? this.element.prop('value') : this.element.data('date'), ommitEvent);
        },

        update: function (newDate, ommitEvent) {
            var originalValue = this.moment ? this.moment.valueOf() : null;

            this.moment = DPGlobal.parseDate(newDate, this.format);

            var newValue = this.moment ? this.moment.valueOf() : null;

            if (!this.viewDate || originalValue != newValue) {
                this.viewDate = this.get() || moment().hours(0).minutes(0).seconds(0).milliseconds(0);
                this.fill();
                this.element.trigger({
                    type: 'changeDateInstant'
                });
            }
            if (!ommitEvent)
                this.triggerChangeDate();
        },

        fillDow: function () {
            var dowCnt = this.weekStart;
            var html = '
';
            var daysMin = moment.weekdaysMin;
            while (dowCnt < this.weekStart + 7) {
                html += '' + daysMin[(dowCnt++) % 7] + '	';
            }
            html += '
';
            this.picker.find('.datepicker-days thead').append(html);
        },

        fillMonths: function () {
            var html = '';
            var i = 0
            var monthsShort = moment.monthsShort;
            while (i < 12) {
                html += '' + monthsShort[i++] + '';
            }
            this.picker.find('.datepicker-months td').append(html);
        },

        fill: function () {
            var year = this.viewDate.year();
            var month = this.viewDate.month();
            var currentMoment = this.get();
            var currentDate = currentMoment ? currentMoment.valueOf() : null; //TODO: use diff
            var currentYear = currentMoment ? currentMoment.year() : null;
            var currentMonth = currentMoment ? currentMoment.month() : null;

            this.picker.find('.datepicker-days th:eq(1)')
						.text(moment.months[month] + ' ' + year);

            var prevMonth = moment([year, month, 0]);
            prevMonth.day(prevMonth.day() - (prevMonth.day() - this.weekStart + 7) % 7);

            //TODO: use diff
            var nextMonthVal = moment(prevMonth).add('days', 42).valueOf();

            html = [];
            var clsName;
            //TODO: use diff
            while (prevMonth.valueOf() < nextMonthVal) {
                if (prevMonth.day() === this.weekStart) {
                    html.push('
');
                }
                clsName = '';
                //TODO: use diff
                if (prevMonth.year() < year || (prevMonth.year() == year && prevMonth.month() < month)) {
                    clsName += ' old';
                } else if (prevMonth.year() > year || (prevMonth.year() == year && prevMonth.month() > month)) {
                    clsName += ' new';
                }
                //TODO: use diff
                if (prevMonth.valueOf() === currentDate) {
                    clsName += ' active';
                }
                html.push('' + prevMonth.date() + '	');
                if (prevMonth.day() === this.weekEnd) {
                    html.push('
');
                }
                prevMonth.add('days', 1);
            }
            this.picker.find('.datepicker-days tbody').empty().append(html.join(''));

            var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');
            if (currentYear === year) {
                months.eq(currentMonth).addClass('active');
            }

            html = '';
            year = parseInt(year / 10, 10) * 10;
            var yearCont = this.picker.find('.datepicker-years')
								.find('th:eq(1)')
									.text(year + '-' + (year + 9))
									.end()
								.find('td');
            year -= 1;
            for (var i = -1; i < 11; i++) {
                html += '' + year + '';
                year += 1;
            }
            yearCont.html(html);
        },

        click: function (e) {
            e.stopPropagation();
            e.preventDefault();
            var target = $(e.target).closest('span, td, th');
            if (target.length === 1) {
                switch (target[0].nodeName.toLowerCase()) {
                    case 'th':
                        switch (target[0].className) {
                            case 'switch':
                                this.showMode(1);
                                break;
                            case 'prev':
                            case 'next':
                                var nav = DPGlobal.modes[this.viewMode];
                                this.viewDate.add(nav.navFnc, nav.navStep * (target[0].className === 'prev' ? -1 : 1));
                                this.fill();
                                this.refresh();
                                break;
                        }
                        break;
                    case 'span':
                        if (target.is('.month')) {

                            var newMonth = target.parent().find('span').index(target);
                            //this.viewDate.month(newMonth); I do not like how it works when the new month have less days
                            this.viewDate.add('months', newMonth - this.viewDate.month());

                        } else {
                            var year = parseInt(target.text(), 10) || 0;
                            this.viewDate.year(year);
                        }

                        if (this.viewMode !== this.minViewMode) {
                            this.showMode(-1);
                            this.set(this.viewDate, true);
                        } else {
                            this.set(this.viewDate);
                        }

                        break;
                    case 'td':
                        if (target.is('.day')) {
                            var day = parseInt(target.text(), 10) || 1;
                            var month = this.viewDate.month();
                            if (target.is('.old')) {
                                month -= 1;
                            } else if (target.is('.new')) {
                                month += 1;
                            }
                            var year = this.viewDate.year();
                            this.set(moment([year, month, day]));
                        }
                        break;
                }
            }
        },

        mousedown: function (e) {
            e.stopPropagation();
            e.preventDefault();
        },

        showMode: function (dir) {
            if (dir) {
                this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
            }
            this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).show();
        }
    };

    $.fn.datepicker = function (option, val) {
        var results = [];
        var chain = this.each(function () {
            var $this = $(this),
				data = $this.data('datepicker'),
				options = typeof option === 'object' && option;
            if (typeof option === 'string') {
                if (data) {
                    var result = data[option](val);
                    if (typeof result !== 'undefined')
                        results.push(result);
                }
            } else if (!data) {
                $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults, options))));
            }
        });
        return results.length == 1 ? results[0]
            : results.length ? results
            : chain;
    };

    $.fn.datepicker.defaults = {
    };
    $.fn.datepicker.Constructor = Datepicker;

    var DPGlobal = {
        modes: [
			{
			    clsName: 'days',
			    navFnc: 'months',
			    navStep: 1
			},
			{
			    clsName: 'months',
			    navFnc: 'years',
			    navStep: 1
			},
			{
			    clsName: 'years',
			    navFnc: 'years',
			    navStep: 10
			}],
        parseDate: function (value, format) {
            var mmnt = null;
            if (typeof value === "string") {
                mmnt = moment(value, format);
            }
            if (!mmnt || !mmnt.isValid()) {
                mmnt = moment(value);
            }
            if (!mmnt || !mmnt.isValid()) {
                return null;
            }
            return mmnt.hours(0).minutes(0).seconds(0).milliseconds(0);
        },
        headTemplate: '
' +
							'
' +
								'‹	' +
								'	' +
								'›	' +
							'
' +
						'
',
        contTemplate: '

'
    };
    DPGlobal.template = '
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									'

' +
								'
' +
							'
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									DPGlobal.contTemplate +
								'
' +
							'
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									DPGlobal.contTemplate +
								'
' +
							'
' +
						'
';

}(this.jQuery, this.moment)
<commit_msg>Update moment-datepicker/moment-datepicker.js<commit_after>/* =========================================================
 * MomentDatepicker
 * Based on http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Andres Moschini
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function ($, moment) {

    // Picker object

    var Datepicker = function (element, options) {
        this.element = $(element);
        this.autoHide = true && (options.autoHide !== false) && (this.element.data('datepicker-autohide') !== false);
        this.format = options.format || this.element.data('datepicker-format') || moment.longDateFormat.L;
        this.picker = $(DPGlobal.template)
							.appendTo('body')
							.on({
							    click: $.proxy(this.click, this),
							    mousedown: $.proxy(this.mousedown, this)
							});
        this.isInput = this.element.is('input');
        this.component = !this.isInput && this.element.is('.date') ? this.element.find('.add-on') : false;

        if (this.isInput) {
            this.element.on({
                focus: $.proxy(this.show, this),
                blur: $.proxy(function (e) {
                    this.hide();
                    this.triggerChangeDate();
                }, this),
                input: $.proxy(function (e) {
                    this.updateFromValue(true);
                }, this),
                keyup: $.proxy(function (e) {
                    if (e.keyCode == 13)
                        this.updateFromValue();
                }, this),
                click: $.proxy(this.show, this)
            });
        } else {
            if (this.component) {
                this.component.on('click', $.proxy(this.show, this));
            } else {
                this.element.on('click', $.proxy(this.show, this));
            }
        }
        this.minViewMode = options.minViewMode || this.element.data('datepicker-minviewmode') || 0;
        if (typeof this.minViewMode === 'string') {
            switch (this.minViewMode) {
                case 'months':
                    this.minViewMode = 1;
                    break;
                case 'years':
                    this.minViewMode = 2;
                    break;
                default:
                    this.minViewMode = 0;
                    break;
            }
        }
        this.viewMode = options.viewMode || this.element.data('datepicker-viewmode') || 0;
        if (typeof this.viewMode === 'string') {
            switch (this.viewMode) {
                case 'months':
                    this.viewMode = 1;
                    break;
                case 'years':
                    this.viewMode = 2;
                    break;
                default:
                    this.viewMode = 0;
                    break;
            }
        }
        this.startViewMode = this.viewMode;
        this.weekStart = options.weekStart || this.element.data('datepicker-weekstart') || 0;
        this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
        this.fillDow();
        this.fillMonths();
        this.updateFromValue();
        this.showMode();
        this.refresh();
    };

    Datepicker.prototype = {
        constructor: Datepicker,
        get: function () {
            return (this.moment && this.moment.clone());
        },
        getAsText: function (format) {
            return (this.moment && this.moment.format(format || this.format)) || '';
        },
        show: function (e) {
            this.picker.show();
            this.height = (this.component && this.component.outerHeight()) || this.element.outerHeight();
            this.place();
            $(window).on('resize', $.proxy(this.place, this));
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }
            if (!this.isInput) {
                $(document).on('mousedown', $.proxy(this.hide, this));
            }
            this.element.trigger({
                type: 'show'
            });
        },

        hide: function () {
            this.picker.hide();
            $(window).off('resize', this.place);
            this.viewMode = this.startViewMode;
            this.showMode();
            if (!this.isInput) {
                $(document).off('mousedown', this.hide);
            }
            this.refresh();
            this.element.trigger({
                type: 'hide'
            });
        },

        refresh: function () {
            var formated = this.getAsText();

            if (!this.isInput) {
                if (this.component) {
                    this.element.find('input').prop('value', formated).change();
                }
                this.element.data('date', formated).change();
            } else {
                this.element.prop('value', formated).change();
            }
        },

        set: function (newDate, ommitEvent) {
            this.update(newDate, ommitEvent);
            this.refresh();
        },

        place: function () {
            var offset = this.component ? this.component.offset() : this.element.offset();
            this.picker.css({
                top: offset.top + this.height,
                left: offset.left
            });
        },
        lastValue: null,
        triggerChangeDate: function () {
            var newValue = this.moment ? this.moment.valueOf() : null;
            if (newValue != this.lastValue) {
                this.lastValue = newValue;
                this.element.trigger({
                    type: 'changeDate'
                });
            }
            if (this.autoHide)
                this.hide();
        },
        updateFromValue: function (ommitEvent) {
            this.update(this.isInput ? this.element.prop('value') : this.element.data('date'), ommitEvent);
        },

        update: function (newDate, ommitEvent) {
            var originalValue = this.moment ? this.moment.valueOf() : null;

            this.moment = DPGlobal.parseDate(newDate, this.format);

            var newValue = this.moment ? this.moment.valueOf() : null;

            if (!this.viewDate || originalValue != newValue) {
                this.viewDate = this.get() || moment().hours(0).minutes(0).seconds(0).milliseconds(0);
                this.fill();
                this.element.trigger({
                    type: 'changeDateInstant'
                });
            }
            if (!ommitEvent)
                this.triggerChangeDate();
        },

        fillDow: function () {
            var dowCnt = this.weekStart;
            var html = '
';
            var daysMin = moment.weekdaysMin;
            while (dowCnt < this.weekStart + 7) {
                html += '' + daysMin[(dowCnt++) % 7] + '	';
            }
            html += '
';
            this.picker.find('.datepicker-days thead').append(html);
        },

        fillMonths: function () {
            var html = '';
            var i = 0
            var monthsShort = moment.monthsShort;
            while (i < 12) {
                html += '' + monthsShort[i++] + '';
            }
            this.picker.find('.datepicker-months td').append(html);
        },

        fill: function () {
            var year = this.viewDate.year();
            var month = this.viewDate.month();
            var currentMoment = this.get();
            var currentDate = currentMoment ? currentMoment.valueOf() : null; //TODO: use diff
            var currentYear = currentMoment ? currentMoment.year() : null;
            var currentMonth = currentMoment ? currentMoment.month() : null;

            this.picker.find('.datepicker-days th:eq(1)')
						.text(moment.months[month] + ' ' + year);

            var prevMonth = moment([year, month, 0]);
            prevMonth.day(prevMonth.day() - (prevMonth.day() - this.weekStart + 7) % 7);

            //TODO: use diff
            var nextMonthVal = moment(prevMonth).add('days', 42).valueOf();

            html = [];
            var clsName;
            //TODO: use diff
            while (prevMonth.valueOf() < nextMonthVal) {
                if (prevMonth.day() === this.weekStart) {
                    html.push('
');
                }
                clsName = '';
                //TODO: use diff
                if (prevMonth.year() < year || (prevMonth.year() == year && prevMonth.month() < month)) {
                    clsName += ' old';
                } else if (prevMonth.year() > year || (prevMonth.year() == year && prevMonth.month() > month)) {
                    clsName += ' new';
                }
                //TODO: use diff
                if (prevMonth.valueOf() === currentDate) {
                    clsName += ' active';
                }
                html.push('' + prevMonth.date() + '	');
                if (prevMonth.day() === this.weekEnd) {
                    html.push('
');
                }
                prevMonth.add('days', 1);
            }
            this.picker.find('.datepicker-days tbody').empty().append(html.join(''));

            var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');
            if (currentYear === year) {
                months.eq(currentMonth).addClass('active');
            }

            html = '';
            year = parseInt(year / 10, 10) * 10;
            var yearCont = this.picker.find('.datepicker-years')
								.find('th:eq(1)')
									.text(year + '-' + (year + 9))
									.end()
								.find('td');
            year -= 1;
            for (var i = -1; i < 11; i++) {
                html += '' + year + '';
                year += 1;
            }
            yearCont.html(html);
        },

        click: function (e) {
            e.stopPropagation();
            e.preventDefault();
            var target = $(e.target).closest('span, td, th');
            if (target.length === 1) {
                switch (target[0].nodeName.toLowerCase()) {
                    case 'th':
                        switch (target[0].className) {
                            case 'switch':
                                this.showMode(1);
                                break;
                            case 'prev':
                            case 'next':
                                var nav = DPGlobal.modes[this.viewMode];
                                this.viewDate.add(nav.navFnc, nav.navStep * (target[0].className === 'prev' ? -1 : 1));
                                this.fill();
                                this.refresh();
                                break;
                        }
                        break;
                    case 'span':
                        if (target.is('.month')) {

                            var newMonth = target.parent().find('span').index(target);
                            //this.viewDate.month(newMonth); I do not like how it works when the new month have less days
                            this.viewDate.add('months', newMonth - this.viewDate.month());

                        } else {
                            var year = parseInt(target.text(), 10) || 0;
                            this.viewDate.year(year);
                        }

                        if (this.viewMode !== this.minViewMode) {
                            this.showMode(-1);
                            this.set(this.viewDate, true);
                        } else {
                            this.set(this.viewDate);
                        }

                        break;
                    case 'td':
                        if (target.is('.day')) {
                            var day = parseInt(target.text(), 10) || 1;
                            var month = this.viewDate.month();
                            if (target.is('.old')) {
                                month -= 1;
                            } else if (target.is('.new')) {
                                month += 1;
                            }
                            var year = this.viewDate.year();
                            this.set(moment([year, month, day]));
                        }
                        break;
                }
            }
        },

        mousedown: function (e) {
            e.stopPropagation();
            e.preventDefault();
        },

        showMode: function (dir) {
            if (dir) {
                this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
            }
            this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).show();
        }
    };

    $.fn.datepicker = function (option, val) {
        var results = [];
        var chain = this.each(function () {
            var $this = $(this),
				data = $this.data('datepicker'),
				options = typeof option === 'object' && option;
            if (typeof option === 'string') {
                if (data) {
                    var result = data[option](val);
                    if (typeof result !== 'undefined')
                        results.push(result);
                }
            } else if (!data) {
                $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults, options))));
            }
        });
        return results.length == 1 ? results[0]
            : results.length ? results
            : chain;
    };

    $.fn.datepicker.defaults = {
    };
    $.fn.datepicker.Constructor = Datepicker;

    var DPGlobal = {
        modes: [
			{
			    clsName: 'days',
			    navFnc: 'months',
			    navStep: 1
			},
			{
			    clsName: 'months',
			    navFnc: 'years',
			    navStep: 1
			},
			{
			    clsName: 'years',
			    navFnc: 'years',
			    navStep: 10
			}],
        parseDate: function (value, format) {
            var mmnt = null;
            if (typeof value === "string") {
                mmnt = moment(value, format);
            }
            if (!mmnt || !mmnt.isValid()) {
                mmnt = moment(value);
            }
            if (!mmnt || !mmnt.isValid()) {
                return null;
            }
            return mmnt.hours(0).minutes(0).seconds(0).milliseconds(0);
        },
        headTemplate: '
' +
							'
' +
								'‹	' +
								'	' +
								'›	' +
							'
' +
						'
',
        contTemplate: '

'
    };
    DPGlobal.template = '
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									'

' +
								'
' +
							'
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									DPGlobal.contTemplate +
								'
' +
							'
' +
							'
' +
								'
' +
									DPGlobal.headTemplate +
									DPGlobal.contTemplate +
								'
' +
							'
' +
						'
';

}(this.jQuery, this.moment)
<|endoftext|>


<commit_before>module.exports = function createLocalAPI(data, inspectBasis){
  var inspectBasisTemplate = inspectBasis.require('basis.template');
  var inspectBasisGroupingNode = inspectBasis.require('basis.dom.wrapper').GroupingNode;
  var fileAPI = require('../../api/file.js');

  function up(upNode){
    if (upNode && upNode.element)
      data.input.set(upNode.element);
  }

  return {
    init: function(){
      // nothing to do
    },
    openFile: function(loc){
      fileAPI.openFile(loc);
    },
    select: function(id){
      var selectNodeById = data.output.value.selectNodeById;
      if (typeof selectNodeById == 'function')
        selectNodeById(id);
    },
    upParent: function(){
      var object = data.output.value.object;
      if (object && object.parentNode)
      {
        var upNode = object.parentNode;

        if (upNode instanceof inspectBasisGroupingNode)
          upNode = upNode.owner;

        up(upNode);
      }
    },
    upOwner: function(){
      var object = data.output.value.object;
      if (object && object.owner)
        up(object.owner);
    },
    upGroup: function(){
      var object = data.output.value.object;
      if (object && object.groupNode)
        up(object.groupNode);
    },
    dropTarget: function(){
      data.input.set();
    },
    logInfo: function(){
      var object = data.output.value.object;
      var debugInfo = null;
      var values = null;

      if (data.input.value)
      {
        var info = inspectBasisTemplate.resolveInfoByNode(data.input.value);
        var objectBinding = object ? object.binding : {};

        debugInfo = info.debug || null;

        if (debugInfo)
          values = debugInfo.values || null;

        if (values)
          values = basis.object.slice(values, basis.object.keys(objectBinding));
      }

      global.$basisjsInfo = {
        object: object,
        template: {
          debugInfo: debugInfo,
          declaration: data.output.value.decl || '<no info>',
          values: values
        }
      };
      console.log(global.$basisjsInfo);
    }
  };
};
<commit_msg>devpanel: typo<commit_after>module.exports = function createLocalAPI(data, inspectBasis){
  var inspectBasisTemplate = inspectBasis.require('basis.template');
  var inspectBasisGroupingNode = inspectBasis.require('basis.dom.wrapper').GroupingNode;
  var fileAPI = require('../../api/file.js');

  function up(upNode){
    if (upNode && upNode.element)
      data.input.set(upNode.element);
  }

  return {
    init: function(){
      // nothing to do
    },
    openFile: function(loc){
      fileAPI.openFile(loc);
    },
    select: function(id){
      var selectNodeById = data.output.value.selectNodeById;
      if (typeof selectNodeById == 'function')
        selectNodeById(id);
    },
    upParent: function(){
      var object = data.output.value.object;
      if (object && object.parentNode)
      {
        var upNode = object.parentNode;

        if (upNode instanceof inspectBasisGroupingNode)
          upNode = upNode.owner;

        up(upNode);
      }
    },
    upOwner: function(){
      var object = data.output.value.object;
      if (object && object.owner)
        up(object.owner);
    },
    upGroup: function(){
      var object = data.output.value.object;
      if (object && object.groupNode)
        up(object.groupNode);
    },
    dropTarget: function(){
      data.input.set();
    },
    logInfo: function(){
      var object = data.output.value.object;
      var debugInfo = null;
      var values = null;

      if (data.input.value)
      {
        var info = inspectBasisTemplate.resolveTemplateInfoByNode(data.input.value);
        var objectBinding = object ? object.binding : {};

        debugInfo = info.debug || null;

        if (debugInfo)
          values = debugInfo.values || null;

        if (values)
          values = basis.object.slice(values, basis.object.keys(objectBinding));
      }

      global.$basisjsInfo = {
        object: object,
        template: {
          debugInfo: debugInfo,
          declaration: data.output.value.decl || '<no info>',
          values: values
        }
      };
      console.log(global.$basisjsInfo);
    }
  };
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name           Add Google site search
// @namespace      curipha
// @description    Add site search form to all pages.
// @include        http://*
// @include        https://*
// @exclude        http://*.google.tld/*
// @exclude        https://*.google.tld/*
// @version        0.1.2
// @grant          GM_addStyle
// @noframes
// ==/UserScript==

(function(){
  if (document.contentType !== 'text/html') return;

  var css =
  // "z-index" should be less than 255 because an indicator of Autopagerize is at 256.
    '#userjs-add_google { background: #ddd; padding: 10px; line-height: 1; min-width: 200px; border: 2px solid #ccc; position: fixed; top: 0; right: 0; z-index: 255; } '+
    '#userjs-add_google form { margin: 0 !important; padding: 0 !important; } '+
    '#userjs-add_google input { font: 18px monospace !important; margin: 0 !important; padding: 0.3em !important; display: inline !important; width: 14em !important; height: auto !important; } '+
    '#userjs-add_google input[type="submit"] { display: none !important; } '+
    '#userjs-add_google_del { color: #000 !important; font: bold 24px sans-serif !important; margin-right: 8px !important; cursor: pointer !important; }';
  GM_addStyle(css);

  var form = document.createElement('div');
  form.id = 'userjs-add_google';
  form.style.opacity = 0;
  form.innerHTML =
    '<form action="https://www.google.com/search" method="get" accept-charset="UTF-8" target="_top">'+
    '×'+
    '<input type="text" name="q" placeholder="' + document.domain + ' を検索" /><input type="submit" value="Search" />'+
    '<input type="hidden" name="as_sitesearch" value="' + document.domain + '" />'+
    '<input type="hidden" name="safe" value="off" />'+
    '</form>';
  document.body.appendChild(form);

  form.addEventListener('mouseover', (function(){ this.style.opacity = 1 }), false);
  form.addEventListener('mouseout',  (function(){ this.style.opacity = 0 }), false);

  document.getElementById('userjs-add_google_del').addEventListener('click', (function(){ document.body.removeChild(form) }), false);
})();
<commit_msg>Stop to insert search form in amazon.co.jp<commit_after>// ==UserScript==
// @name           Add Google site search
// @namespace      curipha
// @description    Add site search form to all pages.
// @include        http://*
// @include        https://*
// @exclude        http://*.google.tld/*
// @exclude        https://*.google.tld/*
// @exclude        http://*.amazon.co.jp/*
// @exclude        https://*.amazon.co.jp/*
// @version        0.1.2
// @grant          GM_addStyle
// @noframes
// ==/UserScript==

(function(){
  if (document.contentType !== 'text/html') return;

  var css =
  // "z-index" should be less than 255 because an indicator of Autopagerize is at 256.
    '#userjs-add_google { background: #ddd; padding: 10px; line-height: 1; min-width: 200px; border: 2px solid #ccc; position: fixed; top: 0; right: 0; z-index: 255; } '+
    '#userjs-add_google form { margin: 0 !important; padding: 0 !important; } '+
    '#userjs-add_google input { font: 18px monospace !important; margin: 0 !important; padding: 0.3em !important; display: inline !important; width: 14em !important; height: auto !important; } '+
    '#userjs-add_google input[type="submit"] { display: none !important; } '+
    '#userjs-add_google_del { color: #000 !important; font: bold 24px sans-serif !important; margin-right: 8px !important; cursor: pointer !important; }';
  GM_addStyle(css);

  var form = document.createElement('div');
  form.id = 'userjs-add_google';
  form.style.opacity = 0;
  form.innerHTML =
    '<form action="https://www.google.com/search" method="get" accept-charset="UTF-8" target="_top">'+
    '×'+
    '<input type="text" name="q" placeholder="' + document.domain + ' を検索" /><input type="submit" value="Search" />'+
    '<input type="hidden" name="as_sitesearch" value="' + document.domain + '" />'+
    '<input type="hidden" name="safe" value="off" />'+
    '</form>';
  document.body.appendChild(form);

  form.addEventListener('mouseover', (function(){ this.style.opacity = 1 }), false);
  form.addEventListener('mouseout',  (function(){ this.style.opacity = 0 }), false);

  document.getElementById('userjs-add_google_del').addEventListener('click', (function(){ document.body.removeChild(form) }), false);
})();
<|endoftext|>


<commit_before>const
	_test = require('tape-promise').default
	tape = require('tape'),
	test = _test(tape),
	paramsCielo = {
        'MerchantId': 'e60c1e21cf8743d1bc1fbd760fe0aba4',
        'MerchantKey': 'LVYLUTLJYYIXXRUQMXLIMYEDLRVCRWHNGYQFIVIG',
        'sandbox': true,
        'debug': false
	},
	cielo = require('./cielo')(paramsCielo),
	regexCardToken = RegExp('\w{8}\D{1}\w{4}\D\w{4}\D\w{4}\D\w{12}$');

test('cielo', async (t) => {
	const tokenParams = {
		"CustomerName": "Comprador Teste Cielo",
		"CardNumber": "4532117080573700",
		"Holder": "Comprador T Cielo",
		"ExpirationDate": "12/2021",
		"Brand": "Visa"
	};
	const token = await cielo.cards.createTokenizedCard(tokenParams);

	const vendaParams = {
		"MerchantOrderId":"2014111706",
		"Customer":{
		   "Name":"Comprador Teste"
		},
		"Payment":{
		  "Type":"CreditCard",
		  "Amount":100,
		  "Installments":1,
		  "SoftDescriptor":"123456789ABCD",
		  "CreditCard":{
			  "CardToken": token.CardToken,
			  "SecurityCode":"262",
			  "Brand":"Visa"
		  }
		}
	}
	const venda = await cielo.creditCard.simpleTransaction(vendaParams).catch((err) => {console.log('ERRO', err)});

	const capturaParams = {
		paymentId: venda.Payment.PaymentId,
		amount: 70
	}
	const captura = await cielo.creditCard.captureSaleTransaction(capturaParams).catch((err) => {console.log('ERRO', err)});

	t.assert('CardToken' in token, 'retorno cardToken correto');
	t.assert(regexCardToken.test(token.CardToken), 'CardToken válido'); // TODO verificar
	t.assert(venda.Payment.Status === 1, 'Status correto');
	t.assert(venda.Payment.Status === 1, 'Status correto');

	t.end();
})<commit_msg>Atualização dos testes<commit_after>const
	_test = require('tape-promise').default
	tape = require('tape'),
	test = _test(tape),
	paramsCielo = {
        'MerchantId': 'e60c1e21cf8743d1bc1fbd760fe0aba4',
        'MerchantKey': 'LVYLUTLJYYIXXRUQMXLIMYEDLRVCRWHNGYQFIVIG',
        'sandbox': true,
        'debug': true
	},
	cielo = require('./cielo')(paramsCielo),
	regexToken = new RegExp(/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/);

test('Cielo', async (t) => {
	const tokenParams = {
		"CustomerName": "Comprador Teste Cielo",
		"CardNumber": "4532117080573700",
		"Holder": "Comprador T Cielo",
		"ExpirationDate": "12/2021",
		"Brand": "Visa"
	};
	const token = await cielo.cards.createTokenizedCard(tokenParams);

	const vendaParams = {
		"MerchantOrderId":"2014111706",
		"Customer":{
		   "Name":"Comprador Teste"
		},
		"Payment":{
		  "Type":"CreditCard",
		  "Amount":100,
		  "Installments":1,
		  "SoftDescriptor":"123456789ABCD",
		  "CreditCard":{
			  "CardToken": token.CardToken,
			  "SecurityCode":"262",
			  "Brand":"Visa"
		  }
		}
	}
	const venda = await cielo.creditCard.simpleTransaction(vendaParams);

	const capturaParams = {
		paymentId: venda.Payment.PaymentId,
		amount: 70
	}
	const captura = await cielo.creditCard.captureSaleTransaction(capturaParams);

	const consultaParams = {
		paymentId: venda.Payment.PaymentId
	}
	const consultaPaymentId = await cielo.consulting.sale(consultaParams);

	t.assert('CardToken' in token, 'retorno cardToken correto');
	t.assert(regexToken.test(token.CardToken), 'CardToken válido');
	t.assert(venda.Payment.Status === 1, 'Status da Venda Correto');
	t.assert(regexToken.test(venda.Payment.PaymentId), 'venda.Payment.PaymentId válido');
	t.assert(consultaPaymentId.PaymentId == venda.Payment.PaymentId, 'consulta de venda via PaymentID')

	t.end();
})<|endoftext|>


<commit_before>/* global artifacts, contract, it, before, assert, web3 */
/* eslint-disable prefer-reflect, no-loop-func */

let constants = require('./helpers/FormulaConstants.js');
let TestBancorFormula = artifacts.require('./helpers/TestBancorFormula.sol');
const utils = require('./helpers/Utils');

let formula;

contract('BancorFormula', () => {
    before(async () => {
        formula = await TestBancorFormula.new();
    });

    let ILLEGAL_VALUE = web3.toBigNumber(2).toPower(256);
    let MAX_NUMERATOR = web3.toBigNumber(2).toPower(256 - constants.MAX_PRECISION).minus(1);
    let MIN_DENOMINATOR = web3.toBigNumber(1);

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MAX_NUMERATOR.minus(1);
        let expN  = ratio;
        let expD  = 100;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 99, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 100, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MAX_NUMERATOR.minus(1);
        let expN  = 100;
        let expD  = ratio;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 99, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 100, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MIN_DENOMINATOR;
        let expN  = ratio;
        let expD  = 100;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 63, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 64, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MIN_DENOMINATOR;
        let expN  = 100;
        let expD  = ratio;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 0, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 1, `${test} failed when it should have passed`);
            }
        });
    }

    for (let dummy = 1; dummy <= 1; dummy++) {
        let numerator = MAX_NUMERATOR;
        let denominator = MIN_DENOMINATOR;
        let test = `Function ln(${numerator.toString(16)}, ${denominator.toString(16)})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testLn.call(numerator, denominator);
                assert(retVal.times(255).lessThan(ILLEGAL_VALUE), `${test}: output is too large`);
            }
            catch (error) {
                assert(false, `${test} failed when it should have passed`);
            }
        });
    }

    for (let dummy = 1; dummy <= 1; dummy++) {
        let numerator = MAX_NUMERATOR.plus(1);
        let denominator = MIN_DENOMINATOR;
        let test = `Function ln(${numerator.toString(16)}, ${denominator.toString(16)})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testLn.call(numerator, denominator);
                assert(false, `${test} passed when it should have failed`);
            }
            catch (error) {
                return utils.ensureException(error);
            }
        });
    }

    for (let precision = constants.MIN_PRECISION; precision <= constants.MAX_PRECISION; precision++) {
        let maxExp = web3.toBigNumber(constants.maxExpArray[precision]);
        let tuples = [
            {'input' : maxExp.plus(0).times(web3.toBigNumber(2).toPower(constants.MAX_PRECISION - precision)).minus(1), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(0).times(web3.toBigNumber(2).toPower(constants.MAX_PRECISION - precision)).minus(0), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(1).times(web3.toBigNumber(2).toPower(constants.MAX_PRECISION - precision)).minus(1), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(1).times(web3.toBigNumber(2).toPower(constants.MAX_PRECISION - precision)).minus(0), 'output' : web3.toBigNumber(precision-1)},
        ];

        for (let index = 0; index < tuples.length; index++) {
            let input = tuples[index]['input'];
            let output = tuples[index]['output'];
            let test = `Function findPositionInMaxExpArray(${input.toString(16)})`;
            it(`${test}:`, async () => {
                try {
                    let retVal = await formula.testFindPositionInMaxExpArray.call(input);
                    assert(retVal.equals(output), `${test}: output should be ${output.toString(10)} but it is ${retVal.toString(10)}`);
                    assert(precision > constants.MIN_PRECISION || !output.lessThan(web3.toBigNumber(precision)), `${test} passed when it should have failed`);
                }
                catch (error) {
                    assert(precision == constants.MIN_PRECISION && output.lessThan(web3.toBigNumber(precision)), `${test} failed when it should have passed`);
                }
            });
        }
    }

    for (let precision = constants.MIN_PRECISION; precision <= constants.MAX_PRECISION; precision++) {
        let maxExp = web3.toBigNumber(constants.maxExpArray[precision]);
        let maxVal = web3.toBigNumber(constants.maxValArray[precision]);
        let errExp = maxExp.plus(1);

        let test1 = `Function fixedExp(${maxExp.toString(16)}, ${precision})`;
        it(`${test1}:`, async () => {
            let retVal = await formula.testFixedExp.call(maxExp, precision);
            assert(retVal.equals(maxVal), `${test1}: output is wrong`);
        });

        let test2 = `Function fixedExp(${errExp.toString(16)}, ${precision})`;
        it(`${test2}:`, async () => {
            let retVal = await formula.testFixedExp.call(errExp, precision);
            assert(retVal.lessThan(maxVal), `${test2}:  output indicates that maxExpArray[${precision}] is wrong`);
        });
    }

    for (let n = 1; n <= 255; n++) {
        let tuples = [
            {'input' : web3.toBigNumber(2).toPower(n)           , 'output' : web3.toBigNumber(n)},
            {'input' : web3.toBigNumber(2).toPower(n).plus(1)   , 'output' : web3.toBigNumber(n)},
            {'input' : web3.toBigNumber(2).toPower(n+1).minus(1), 'output' : web3.toBigNumber(n)},
        ];

        for (let index = 0; index < tuples.length; index++) {
            let input = tuples[index]['input'];
            let output = tuples[index]['output'];
            let test = `Function floorLog2(${input.toString(16)})`;
            it(`${test}:`, async () => {
                let retVal = await formula.testFloorLog2.call(input);
                    assert(retVal.equals(output), `${test}: output should be ${output.toString(10)} but it is ${retVal.toString(10)}`);
            });
        }
    }
});
<commit_msg>Minor improvement in JS test.<commit_after>/* global artifacts, contract, it, before, assert, web3 */
/* eslint-disable prefer-reflect, no-loop-func */

let constants = require('./helpers/FormulaConstants.js');
let TestBancorFormula = artifacts.require('./helpers/TestBancorFormula.sol');
const utils = require('./helpers/Utils');

let formula;

contract('BancorFormula', () => {
    before(async () => {
        formula = await TestBancorFormula.new();
    });

    let ILLEGAL_VALUE = web3.toBigNumber(2).toPower(256);
    let MAX_NUMERATOR = web3.toBigNumber(2).toPower(256 - constants.MAX_PRECISION).minus(1);
    let MIN_DENOMINATOR = web3.toBigNumber(1);

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MAX_NUMERATOR.minus(1);
        let expN  = ratio;
        let expD  = 100;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 99, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 100, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MAX_NUMERATOR.minus(1);
        let expN  = 100;
        let expD  = ratio;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 99, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 100, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MIN_DENOMINATOR;
        let expN  = ratio;
        let expD  = 100;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 63, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 64, `${test} failed when it should have passed`);
            }
        });
    }

    for (let ratio = 1; ratio <= 99; ratio++) {
        let baseN = MAX_NUMERATOR;
        let baseD = MIN_DENOMINATOR;
        let expN  = 100;
        let expD  = ratio;
        let test  = `Function power(${baseN.toString(16)}, ${baseD.toString(16)}, ${expN}, ${expD})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testPower.call(baseN, baseD, expN, expD);
                assert(ratio <= 0, `${test} passed when it should have failed`);
            }
            catch (error) {
                assert(ratio >= 1, `${test} failed when it should have passed`);
            }
        });
    }

    for (let dummy = 1; dummy <= 1; dummy++) {
        let numerator = MAX_NUMERATOR;
        let denominator = MIN_DENOMINATOR;
        let test = `Function ln(${numerator.toString(16)}, ${denominator.toString(16)})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testLn.call(numerator, denominator);
                assert(retVal.times(255).lessThan(ILLEGAL_VALUE), `${test}: output is too large`);
            }
            catch (error) {
                assert(false, `${test} failed when it should have passed`);
            }
        });
    }

    for (let dummy = 1; dummy <= 1; dummy++) {
        let numerator = MAX_NUMERATOR.plus(1);
        let denominator = MIN_DENOMINATOR;
        let test = `Function ln(${numerator.toString(16)}, ${denominator.toString(16)})`;
        it(`${test}:`, async () => {
            try {
                let retVal = await formula.testLn.call(numerator, denominator);
                assert(false, `${test} passed when it should have failed`);
            }
            catch (error) {
                return utils.ensureException(error);
            }
        });
    }

    for (let precision = constants.MIN_PRECISION; precision <= constants.MAX_PRECISION; precision++) {
        let maxExp = web3.toBigNumber(constants.maxExpArray[precision]);
        let shlVal = web3.toBigNumber(2).toPower(constants.MAX_PRECISION - precision);
        let tuples = [
            {'input' : maxExp.plus(0).times(shlVal).minus(1), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(0).times(shlVal).minus(0), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(1).times(shlVal).minus(1), 'output' : web3.toBigNumber(precision-0)},
            {'input' : maxExp.plus(1).times(shlVal).minus(0), 'output' : web3.toBigNumber(precision-1)},
        ];

        for (let index = 0; index < tuples.length; index++) {
            let input = tuples[index]['input'];
            let output = tuples[index]['output'];
            let test = `Function findPositionInMaxExpArray(${input.toString(16)})`;
            it(`${test}:`, async () => {
                try {
                    let retVal = await formula.testFindPositionInMaxExpArray.call(input);
                    assert(retVal.equals(output), `${test}: output should be ${output.toString(10)} but it is ${retVal.toString(10)}`);
                    assert(precision > constants.MIN_PRECISION || !output.lessThan(web3.toBigNumber(precision)), `${test} passed when it should have failed`);
                }
                catch (error) {
                    assert(precision == constants.MIN_PRECISION && output.lessThan(web3.toBigNumber(precision)), `${test} failed when it should have passed`);
                }
            });
        }
    }

    for (let precision = constants.MIN_PRECISION; precision <= constants.MAX_PRECISION; precision++) {
        let maxExp = web3.toBigNumber(constants.maxExpArray[precision]);
        let maxVal = web3.toBigNumber(constants.maxValArray[precision]);
        let errExp = maxExp.plus(1);

        let test1 = `Function fixedExp(${maxExp.toString(16)}, ${precision})`;
        it(`${test1}:`, async () => {
            let retVal = await formula.testFixedExp.call(maxExp, precision);
            assert(retVal.equals(maxVal), `${test1}: output is wrong`);
        });

        let test2 = `Function fixedExp(${errExp.toString(16)}, ${precision})`;
        it(`${test2}:`, async () => {
            let retVal = await formula.testFixedExp.call(errExp, precision);
            assert(retVal.lessThan(maxVal), `${test2}:  output indicates that maxExpArray[${precision}] is wrong`);
        });
    }

    for (let n = 1; n <= 255; n++) {
        let tuples = [
            {'input' : web3.toBigNumber(2).toPower(n)           , 'output' : web3.toBigNumber(n)},
            {'input' : web3.toBigNumber(2).toPower(n).plus(1)   , 'output' : web3.toBigNumber(n)},
            {'input' : web3.toBigNumber(2).toPower(n+1).minus(1), 'output' : web3.toBigNumber(n)},
        ];

        for (let index = 0; index < tuples.length; index++) {
            let input = tuples[index]['input'];
            let output = tuples[index]['output'];
            let test = `Function floorLog2(${input.toString(16)})`;
            it(`${test}:`, async () => {
                let retVal = await formula.testFloorLog2.call(input);
                    assert(retVal.equals(output), `${test}: output should be ${output.toString(10)} but it is ${retVal.toString(10)}`);
            });
        }
    }
});
<|endoftext|>


<commit_before>class OfferFormController {
    constructor($http, $q, OfferService, ToastService, NgoService, CategoryService, $state, LanguageService, OfferTranslationService) {
        'ngInject';

        this.$q = $q;
        this.aborter = $q.defer();

        this.categories = [];
        this.translations = [];
        this.$http = $http;
        this.OfferService = OfferService;
        this.ToastService = ToastService;
        this.$state = $state;
        this.$LanguageService = LanguageService;
        this.OfferTranslationService = OfferTranslationService;
        this.OfferTranslationService.fetchAll((list) = > {
            this.translations = list;
    })
        this.NgoService = NgoService;
        if(this.cms){
          this.NgoService.fetchAll().then((list) => {
            this.ngos = list;
          });
        }
        this.CategoryService = CategoryService;
        this.CategoryService.all((list) => {
          this.categories = list;
        })
        this.categoriesOptions = {
          selectionChanged: (items) => {
            this.offer.categories = items;
          }
        }
        if($state.params.id){
          this.OfferService.one($state.params.id, (offer) =>{
            this.offer = offer;
            if(this.offer.valid_from != null) {
               this.valid_from = new Date(this.offer.valid_from);
            }
            if(this.offer.valid_until != null) {
               this.valid_until = new Date(this.offer.valid_until);
            }
         })
        }
        else{
          this.offer = {
            categories:[],
              filters: [],
              translations: []
          };
          this.valid_from = new Date();
          this.NgoService.one().then((ngo) => {
                this.adoptFieldsFromNgo(ngo);
            });
        }

        angular.element(document.querySelector('#addressSearch')).$valid = false;
    }

    querySearch(query) {
        if (this.$http.pendingRequests.length) {
            this.aborter.resolve();
            this.aborter = this.$q.defer();
        }
        return this.$http.get('/api/offer/autocomplete/' + query, {
            timeout: this.aborter.promise
        }).then(function(response) {
            return response.data; // usually response.data
        });

    }

    selectedItemChange(item) {
        if (!item) return;
        this.offer.street = item.street;
        this.offer.streetnumber = item.number;
        this.offer.city = item.city;
        this.offer.zip = item.zip;
    }

    save() {
      if(!this.offer.street || !this.offer.streetnumber || !this.offer.zip ){
        this.ToastService.error('Es ist keine Adresse vorhanden!');
        return false;
      }

      this.offer.valid_until = this.valid_until;
      this.offer.valid_from = this.valid_from;
        if (new Date() > this.offer.valid_until) {
            this.ToastService.error('Enddatum ist in der Vergangenheit!');
            return false;
        }

      this.OfferService.save(this.offer);

    }

    cancel() {
        this.OfferService.cancel(this.cms);
    }

    adoptFieldsFromNgo(ngo) {
        if (ngo) {
            this.offer.email = ngo.contact_email;
            this.offer.phone = ngo.contact_phone;
            this.offer.website = ngo.website;
            this.offer.street = ngo.street;
            this.offer.streetnumber = ngo.street_number;
            this.offer.zip = ngo.zip;
            this.offer.city = ngo.city;
        }
    }

    showTranslation() {
        //TODO
    }

}

export const OfferFormComponent = {
    templateUrl: './views/app/components/offer-form/offer-form.component.html',
    controller: OfferFormController,
    controllerAs: 'vm',
    bindings: {
        cms: '=',
        ngo: '='
    }
}
<commit_msg>corrected auto-reformated code by php storm<commit_after>class OfferFormController {
    constructor($http, $q, OfferService, ToastService, NgoService, CategoryService, $state, LanguageService, OfferTranslationService) {
        'ngInject';

        this.$q = $q;
        this.aborter = $q.defer();

        this.categories = [];
        this.translations = [];
        this.$http = $http;
        this.OfferService = OfferService;
        this.ToastService = ToastService;
        this.$state = $state;
        this.$LanguageService = LanguageService;
        this.OfferTranslationService = OfferTranslationService;
        this.OfferTranslationService.fetchAll((list) => {
            this.translations = list;
    })
        this.NgoService = NgoService;
        if(this.cms){
          this.NgoService.fetchAll().then((list) => {
            this.ngos = list;
          });
        }
        this.CategoryService = CategoryService;
        this.CategoryService.all((list) => {
          this.categories = list;
        })
        this.categoriesOptions = {
          selectionChanged: (items) => {
            this.offer.categories = items;
          }
        }
        if($state.params.id){
          this.OfferService.one($state.params.id, (offer) =>{
            this.offer = offer;
            if(this.offer.valid_from != null) {
               this.valid_from = new Date(this.offer.valid_from);
            }
            if(this.offer.valid_until != null) {
               this.valid_until = new Date(this.offer.valid_until);
            }
         })
        }
        else{
          this.offer = {
            categories:[],
              filters: [],
              translations: []
          };
          this.valid_from = new Date();
          this.NgoService.one().then((ngo) => {
                this.adoptFieldsFromNgo(ngo);
            });
        }

        angular.element(document.querySelector('#addressSearch')).$valid = false;
    }

    querySearch(query) {
        if (this.$http.pendingRequests.length) {
            this.aborter.resolve();
            this.aborter = this.$q.defer();
        }
        return this.$http.get('/api/offer/autocomplete/' + query, {
            timeout: this.aborter.promise
        }).then(function(response) {
            return response.data; // usually response.data
        });

    }

    selectedItemChange(item) {
        if (!item) return;
        this.offer.street = item.street;
        this.offer.streetnumber = item.number;
        this.offer.city = item.city;
        this.offer.zip = item.zip;
    }

    save() {
      if(!this.offer.street || !this.offer.streetnumber || !this.offer.zip ){
        this.ToastService.error('Es ist keine Adresse vorhanden!');
        return false;
      }

      this.offer.valid_until = this.valid_until;
      this.offer.valid_from = this.valid_from;
        if (new Date() > this.offer.valid_until) {
            this.ToastService.error('Enddatum ist in der Vergangenheit!');
            return false;
        }

      this.OfferService.save(this.offer);

    }

    cancel() {
        this.OfferService.cancel(this.cms);
    }

    adoptFieldsFromNgo(ngo) {
        if (ngo) {
            this.offer.email = ngo.contact_email;
            this.offer.phone = ngo.contact_phone;
            this.offer.website = ngo.website;
            this.offer.street = ngo.street;
            this.offer.streetnumber = ngo.street_number;
            this.offer.zip = ngo.zip;
            this.offer.city = ngo.city;
        }
    }

    showTranslation() {
        //TODO
    }

}

export const OfferFormComponent = {
    templateUrl: './views/app/components/offer-form/offer-form.component.html',
    controller: OfferFormController,
    controllerAs: 'vm',
    bindings: {
        cms: '=',
        ngo: '='
    }
}
<|endoftext|>


<commit_before>import Discord from 'discord.js';

import BaseCommand from './BaseCommand';
import { COLOURS, PERMISSIONS } from '../constants';
import * as database from '../db';

/**
 * This will turn message deletion logging off.
 *
 * @class LogOffCommand
 * @extends {BaseCommand}
 */
class LogOffCommand extends BaseCommand {
    /**
     * This event method we should listen for.
     *
     * @type {string}
     * @memberof LogOffCommand
     */
    method = 'message';

    /**
     * The pattern to match against. If the message matches this pattern then we will respond to it with the action
     * method.
     *
     * @type {RegExp}
     * @memberof LogOffCommand
     */
    pattern = /^!logoff/;

    /**
     * The permissions the user requires in order to use this command.
     *
     * @type {String[]}
     * @memberof LogOffCommand
     */
    permissions = [PERMISSIONS.MANAGE_MESSAGES];

    /**
     * The function that should be called when the event is fired.
     *
     * @param {string} action
     * @param {Message} message
     * @memberof LogOffCommand
     */
    async action(action, message) {
        await message.delete();
        await database.updateSetting('logMessageDeletions', false);

        let user = 'Unknown';

        if (message.author) {
            user = `${message.author} (${message.author.username}#${message.author.discriminator})`;
        }

        const embed = new Discord.RichEmbed()
            .setTitle('Message deletion logging turned off')
            .setColor(COLOURS.RED)
            .setTimestamp(new Date().toISOString())
            .addField('User', user, true);

        this.sendEmbedToModeratorLogsChannel(embed);
    }
}

export default LogOffCommand;
<commit_msg>feat: add a timeout to !logoff<commit_after>import Discord from 'discord.js';

import BaseCommand from './BaseCommand';
import { COLOURS, PERMISSIONS } from '../constants';
import * as database from '../db';

/**
 * This will turn message deletion logging off.
 *
 * @class LogOffCommand
 * @extends {BaseCommand}
 */
class LogOffCommand extends BaseCommand {
    /**
     * This event method we should listen for.
     *
     * @type {string}
     * @memberof LogOffCommand
     */
    method = 'message';

    /**
     * The pattern to match against. If the message matches this pattern then we will respond to it with the action
     * method.
     *
     * @type {RegExp}
     * @memberof LogOffCommand
     */
    pattern = /^!logoff/;

    /**
     * The permissions the user requires in order to use this command.
     *
     * @type {String[]}
     * @memberof LogOffCommand
     */
    permissions = [PERMISSIONS.MANAGE_MESSAGES];

    /**
     * The function that should be called when the event is fired.
     *
     * @param {string} action
     * @param {Message} message
     * @memberof LogOffCommand
     */
    async action(action, message) {
        await message.delete();
        await database.updateSetting('logMessageDeletions', false);

        const input = message.cleanContent.replace('!logoff', '');
        const timeout = input.length ? parseInt(input, 10) : null;

        let user = 'Unknown';

        if (message.author) {
            user = `${message.author} (${message.author.username}#${message.author.discriminator})`;
        }

        const embed = new Discord.RichEmbed()
            .setTitle('Message deletion logging turned off')
            .setColor(COLOURS.RED)
            .setTimestamp(new Date().toISOString())
            .addField('User', user, true);

        this.sendEmbedToModeratorLogsChannel(embed);

        if (timeout) {
            setTimeout(async () => {
                await database.updateSetting('logMessageDeletions', true);

                const embed = new Discord.RichEmbed()
                    .setTitle('Message deletion logging turned on')
                    .setColor(COLOURS.GREEN)
                    .setTimestamp(new Date().toISOString())
                    .addField('User', user, true);

                this.sendEmbedToModeratorLogsChannel(embed);
            }, timeout * 1000);
        }
    }
}

export default LogOffCommand;
<|endoftext|>


<commit_before>(function (enyo, scope) {
	/**
	* Bubble this event from a contained [control]{@link enyo.Control} to mute tooltips. No data
	* needs be passed with this event.
	*
	* @event moon.TooltipDecorator#onRequestMuteTooltip
	* @type {Object}
	* @public
	*/

	/**
	* Bubble this event from a contained [control]{@link enyo.Control} to unmute tooltips. No data
	* needs be passed with this event.
	*
	* @event moon.TooltipDecorator#onRequestUnmuteTooltip
	* @type {Object}
	* @public
	*/

	/**
	* {@link moon.TooltipDecorator} is a control that activates a {@link moon.Tooltip}. It
	* surrounds a control such as a button and displays the tooltip when the control generates
	* an `onenter` event:
	*
	* ```
	* {kind: 'moon.TooltipDecorator', components: [
	*	{kind: 'moon.Button', content: 'Tooltip'},
	*	{kind: 'moon.Tooltip', content: 'I am a tooltip for a button.'}
	* ]}
	* ```
	*
	* Here is an example with a {@link moon.Input} control and a decorator around the input:
	*
	* ```
	* {kind: 'moon.TooltipDecorator', components: [
	*	{kind: 'moon.InputDecorator', components: [
	*		{kind: 'moon.Input', placeholder: 'Just an input...'}
	*	]},
	*	{kind: 'moon.Tooltip', content: 'I am just a tooltip for an input.'}
	* ]}
	* ```
	*
	* Automatic hiding and showing of tooltips may be disabled by calling
	* [mute()]{@link moon.TooltipDecorator#mute} or by bubbling the
	* [onRequestMuteTooltip]{@link moon.TooltipDecorator#onRequestMuteTooltip} event;
	* it may be re-enabled by calling [unmute()]{@link moon.TooltipDecorator#unmute}
	* or by bubbling the
	* [onRequestUnmuteTooltip]{@link moon.TooltipDecorator#onRequestUnmuteTooltip} event.
	*
	* @class moon.TooltipDecorator
	* @extends enyo.Control
	* @ui
	* @public
	*/
	enyo.kind(
		/** @lends  moon.TooltipDecorator.prototype */ {

		/**
		* @private
		*/
		name: 'moon.TooltipDecorator',

		/**
		* @private
		*/
		defaultKind: 'moon.Button',

		/**
		* @private
		*/
		classes: 'moon-contextual-popup-decorator',

		/**
		* @private
		*/
		handlers: {
			onenter: 'requestShowTooltip',
			onleave: 'requestHideTooltip',
			onSpotlightFocused: 'requestShowTooltip',
			onSpotlightBlur: 'requestHideTooltip',
			onRequestMuteTooltip: 'mute',
			onRequestUnmuteTooltip: 'unmute'
		},

		/**
		* @private
		* @lends moon.TooltipDecorator.prototype
		*/
		published: {
			/**
			* Boolean indicating whether tooltips are automatically shown when the activator is
			* hovered over.
			*
			* @type {Boolean}
			* @default true
			* @public
			*/
			autoShow: true
		},

		/**
		* Disables automatic tooltip showing and hiding.
		*
		* @public
		*/
		mute: function () {
			this.setAutoShow(false);
		},

		/**
		* Re-enables automatic tooltip showing and hiding after being muted.
		*
		* @public
		*/
		unmute: function () {
			this.setAutoShow(true);
		},

		/**
		* @private
		*/
		autoShowChanged: function () {
			if (!this.autoShow) {
				this.requestHideTooltip();
			}
		},

		/**
		* @private
		*/
		tap: function () {
			this.requestHideTooltip();
		},

		/**
		* @private
		*/
		requestShowTooltip: function (inSender, inEvent) {
			if (this.autoShow && !enyo.Spotlight.isFrozen()) {
				if (inEvent.type == 'onSpotlightFocused' || enyo.Spotlight.getPointerMode()) {
					this.waterfallDown('onRequestShowTooltip', {originator: inSender}, this);
				}
			}
		},

		/**
		* @private
		*/
		requestHideTooltip: function () {
			this.waterfallDown('onRequestHideTooltip');
		},

		/**
		* Cancel any pending tooltip showing if the decorator or one of its ancestors is hidden
		*
		* @private
		*/
		showingChangedHandler: enyo.inherit(function (sup) {
			return function (sender, event) {
				if(!event.showing) {
					this.requestHideTooltip();
				}
			};
		}),
	});

})(enyo, this);
<commit_msg>add super call and fix jshint<commit_after>(function (enyo, scope) {
	/**
	* Bubble this event from a contained [control]{@link enyo.Control} to mute tooltips. No data
	* needs be passed with this event.
	*
	* @event moon.TooltipDecorator#onRequestMuteTooltip
	* @type {Object}
	* @public
	*/

	/**
	* Bubble this event from a contained [control]{@link enyo.Control} to unmute tooltips. No data
	* needs be passed with this event.
	*
	* @event moon.TooltipDecorator#onRequestUnmuteTooltip
	* @type {Object}
	* @public
	*/

	/**
	* {@link moon.TooltipDecorator} is a control that activates a {@link moon.Tooltip}. It
	* surrounds a control such as a button and displays the tooltip when the control generates
	* an `onenter` event:
	*
	* ```
	* {kind: 'moon.TooltipDecorator', components: [
	*	{kind: 'moon.Button', content: 'Tooltip'},
	*	{kind: 'moon.Tooltip', content: 'I am a tooltip for a button.'}
	* ]}
	* ```
	*
	* Here is an example with a {@link moon.Input} control and a decorator around the input:
	*
	* ```
	* {kind: 'moon.TooltipDecorator', components: [
	*	{kind: 'moon.InputDecorator', components: [
	*		{kind: 'moon.Input', placeholder: 'Just an input...'}
	*	]},
	*	{kind: 'moon.Tooltip', content: 'I am just a tooltip for an input.'}
	* ]}
	* ```
	*
	* Automatic hiding and showing of tooltips may be disabled by calling
	* [mute()]{@link moon.TooltipDecorator#mute} or by bubbling the
	* [onRequestMuteTooltip]{@link moon.TooltipDecorator#onRequestMuteTooltip} event;
	* it may be re-enabled by calling [unmute()]{@link moon.TooltipDecorator#unmute}
	* or by bubbling the
	* [onRequestUnmuteTooltip]{@link moon.TooltipDecorator#onRequestUnmuteTooltip} event.
	*
	* @class moon.TooltipDecorator
	* @extends enyo.Control
	* @ui
	* @public
	*/
	enyo.kind(
		/** @lends  moon.TooltipDecorator.prototype */ {

		/**
		* @private
		*/
		name: 'moon.TooltipDecorator',

		/**
		* @private
		*/
		defaultKind: 'moon.Button',

		/**
		* @private
		*/
		classes: 'moon-contextual-popup-decorator',

		/**
		* @private
		*/
		handlers: {
			onenter: 'requestShowTooltip',
			onleave: 'requestHideTooltip',
			onSpotlightFocused: 'requestShowTooltip',
			onSpotlightBlur: 'requestHideTooltip',
			onRequestMuteTooltip: 'mute',
			onRequestUnmuteTooltip: 'unmute'
		},

		/**
		* @private
		* @lends moon.TooltipDecorator.prototype
		*/
		published: {
			/**
			* Boolean indicating whether tooltips are automatically shown when the activator is
			* hovered over.
			*
			* @type {Boolean}
			* @default true
			* @public
			*/
			autoShow: true
		},

		/**
		* Disables automatic tooltip showing and hiding.
		*
		* @public
		*/
		mute: function () {
			this.setAutoShow(false);
		},

		/**
		* Re-enables automatic tooltip showing and hiding after being muted.
		*
		* @public
		*/
		unmute: function () {
			this.setAutoShow(true);
		},

		/**
		* @private
		*/
		autoShowChanged: function () {
			if (!this.autoShow) {
				this.requestHideTooltip();
			}
		},

		/**
		* @private
		*/
		tap: function () {
			this.requestHideTooltip();
		},

		/**
		* @private
		*/
		requestShowTooltip: function (inSender, inEvent) {
			if (this.autoShow && !enyo.Spotlight.isFrozen()) {
				if (inEvent.type == 'onSpotlightFocused' || enyo.Spotlight.getPointerMode()) {
					this.waterfallDown('onRequestShowTooltip', {originator: inSender}, this);
				}
			}
		},

		/**
		* @private
		*/
		requestHideTooltip: function () {
			this.waterfallDown('onRequestHideTooltip');
		},

		/**
		* Cancel any pending tooltip showing if the decorator or one of its ancestors is hidden
		*
		* @private
		*/
		showingChangedHandler: enyo.inherit(function (sup) {
			return function (sender, event) {
				sup.apply(this, arguments);
				if (!event.showing) {
					this.requestHideTooltip();
				}
			};
		})
	});

})(enyo, this);
<|endoftext|>


<commit_before>// retrieve a JSON from a url
//***************************************
function grabJSON (url) {
  return $.ajax({
    url: url,
  });
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(name));
    });
  $('.selectpicker').selectpicker('refresh');
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownCtxtSelectFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(file));
    });
}
//***************************************

// get preset_pos for McCormick model
//***************************************
// function to set preset_pos for McCormick model
//***************************************
function setPresetPos () {
  grabJSON("static/models/" + prebuilt_model + "/preset_pos.json").then(function (ajax_response) {
    preset_pos = ajax_response;
    preset_pos_static = preset_pos;
  });
}
//***************************************

//download a model
//***************************************
function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
//***************************************

//send text to a reading system, get back stmts
//***************************************
function txtProcess(txt, parser) {
  var input_txt = {'text':txt};
  return $.ajax({
                url: indra_server_addr + "/"+ parser + "/process_text",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(input_txt),
                });
}

// send stmts to grounding mapper, get grounded stmts
//***************************************
function groundingMapper(res) {
  var stmts = res;
  return $.ajax({
                url: indra_server_addr + "/preassembly/map_grounding",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(stmts),
                });
}
//***************************************

function assembleCyJS(res) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  return $.ajax({
      url: indra_server_addr + "/assemblers/cyjs",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function assemblePySB(res, export_format=null) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  if(export_format){
    res_json['export_format'] = export_format;
    }
  return $.ajax({
      url: indra_server_addr + "/assemblers/pysb",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function assembleSBML(res) {
    return assemblePySB(res, 'sbml');
    }

function assembleSBGN(res) {
    return assemblePySB(res, 'sbgn');
    }

function assembleBNGL(res) {
    return assemblePySB(res, 'bngl');
    }

function assembleKappa(res) {
    return assemblePySB(res, 'kappa');
    }

function assembleLoopy(res) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  return $.ajax({
      url: indra_server_addr + "/assemblers/sif/loopy",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

var mrna;
function get_ccle_mrna(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_mrna",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["mrna_amounts"];
                      res = res[cell_line];
                      mrna = res;
                  });
}

var cna;
function get_ccle_cna(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_cna",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["cna"];
                      res = res[cell_line];
                      cna = res;
                  });
}

var mutations;
function get_ccle_mutations(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_mutations",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["mutations"];
                      res = res[cell_line];
                      mutations = res;
                  });
}
<commit_msg>Fixed bug where `assemblePySB` was not producing downloads<commit_after>// retrieve a JSON from a url
//***************************************
function grabJSON (url) {
  return $.ajax({
    url: url,
  });
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(name));
    });
  $('.selectpicker').selectpicker('refresh');
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownCtxtSelectFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(file));
    });
}
//***************************************

// get preset_pos for McCormick model
//***************************************
// function to set preset_pos for McCormick model
//***************************************
function setPresetPos () {
  grabJSON("static/models/" + prebuilt_model + "/preset_pos.json").then(function (ajax_response) {
    preset_pos = ajax_response;
    preset_pos_static = preset_pos;
  });
}
//***************************************

//download a model
//***************************************
function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
//***************************************

//send text to a reading system, get back stmts
//***************************************
function txtProcess(txt, parser) {
  var input_txt = {'text':txt};
  return $.ajax({
                url: indra_server_addr + "/"+ parser + "/process_text",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(input_txt),
                });
}

// send stmts to grounding mapper, get grounded stmts
//***************************************
function groundingMapper(res) {
  var stmts = res;
  return $.ajax({
                url: indra_server_addr + "/preassembly/map_grounding",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(stmts),
                });
}
//***************************************

function assembleCyJS(res) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  return $.ajax({
      url: indra_server_addr + "/assemblers/cyjs",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function requestPySB(res, export_format=null) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  if (export_format){
    res_json['export_format'] = export_format;
    }
  return $.ajax({
      url: indra_server_addr + "/assemblers/pysb",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function assemblePySB(res) {
  return requestPySB(res);
  }

function assembleSBML(res) {
    return requestPySB(res, 'sbml');
    }

function assembleSBGN(res) {
    return requestPySB(res, 'sbgn');
    }

function assembleBNGL(res) {
    return requestPySB(res, 'bngl');
    }

function assembleKappa(res) {
    return requestPySB(res, 'kappa');
    }

function assembleLoopy(res) {
  var res_json = res;
  res_json['line'] = $('#cellSelectDynamic').val().slice(6,-5);
  return $.ajax({
      url: indra_server_addr + "/assemblers/sif/loopy",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

var mrna;
function get_ccle_mrna(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_mrna",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["mrna_amounts"];
                      res = res[cell_line];
                      mrna = res;
                  });
}

var cna;
function get_ccle_cna(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_cna",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["cna"];
                      res = res[cell_line];
                      cna = res;
                  });
}

var mutations;
function get_ccle_mutations(gene_list, cell_line) {
  var input_txt = {'gene_list': gene_list,
                   'cell_lines': [cell_line]};
  return $.ajax({
            url: indra_server_addr + "/databases/cbio/get_ccle_mutations",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(input_txt),
           }).then(function(res){
                      res = res["mutations"];
                      res = res[cell_line];
                      mutations = res;
                  });
}
<|endoftext|>


<commit_before>var fs    = require('fs');
var utils = require('amd-utils');

var task = {
    id      : 'init',
    author  : 'Indigo United',
    name    : 'Init',
    options : {
        name: {
            description: 'The task name',
            'default': 'autofile'
        },
        dst: {
            description: 'Directory where the task will be created',
            'default': process.cwd()
        }
    },
    filter: function (opt, next) {
        if (!utils.string.endsWith(opt.name, '.js')) {
            opt.filename = opt.name + '.js';
        }
        else {
            opt.filename = opt.name;
            opt.name     = opt.name.slice(0, -3);
        }
        next();
    },
    tasks  :
    [
        {
            task: function (opt, next) {
                fs.stat(opt.filename, function (err) {
                    if (!err || err.code !== 'ENOENT') {
                        return next(new Error('Filename ' + opt.filename + ' already exists.'));
                    }

                    next();
                });
            }
        },
        {
            task: 'cp',
            options: {
                src: __dirname + '/../base_autofile.js',
                dst: '{{dst}}/{{filename}}'
            }
        },
        {
            task: 'scaffolding-replace',
            options: {
                file: '{{dst}}/{{filename}}.js',
                data: {
                    name: '{{name}}'
                }
            }
        }
    ]
};

module.exports = task;<commit_msg>Fix init task.<commit_after>var fs    = require('fs');
var utils = require('amd-utils');

var task = {
    id      : 'init',
    author  : 'Indigo United',
    name    : 'Init',
    options : {
        name: {
            description: 'The task name',
            'default': 'autofile'
        },
        dst: {
            description: 'Directory where the task will be created',
            'default': process.cwd()
        }
    },
    filter: function (opt, next) {
        if (utils.string.endsWith(opt.name, '.js')) {
            opt.name = opt.name.slice(0, -3);
        }
        opt.filename = opt.name + '.js';

        next();
    },
    tasks  :
    [
        {
            task: function (opt, next) {
                fs.stat(opt.filename, function (err) {
                    if (!err || err.code !== 'ENOENT') {
                        return next(new Error('Filename ' + opt.filename + ' already exists.'));
                    }

                    next();
                });
            }
        },
        {
            task: 'cp',
            options: {
                src: __dirname + '/../base_autofile.js',
                dst: '{{dst}}/{{filename}}'
            }
        },
        {
            task: 'scaffolding-replace',
            options: {
                file: '{{dst}}/{{filename}}',
                data: {
                    name: '{{name}}'
                }
            }
        }
    ]
};

module.exports = task;<|endoftext|>