<commit_before>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 )) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ), x.value.length -  Math.ceil(x.value.length / 2)) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = this;
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var deg = Math.floor(x_length / 2);

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]);
	var a_powed = a.timesTenToThe(2 * deg);
	var c = karatsuba(xSplit[1], ySplit[1]);

	var x_sum = xSplit[0].plus(xSplit[1]);
	var y_sum = ySplit[0].plus(ySplit[1]);

	var b = karatsuba(x_sum, y_sum);

	var b_minus_a = b.minus(a);
	var b_minus_a_minus_c = b_minus_a.minus(c);
	var b_powed = b_minus_a_minus_c.timesTenToThe(deg);

	return a_powed.plus(c).plus(b_powed);
}

<commit_msg>Update number.js<commit_after>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 )) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ), x.value.length -  Math.ceil(x.value.length / 2)) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = new number(this.positive, this.value);
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var deg = Math.floor(x_length / 2);

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]);
	var a_powed = a.timesTenToThe(2 * deg);
	var c = karatsuba(xSplit[1], ySplit[1]);

	var x_sum = xSplit[0].plus(xSplit[1]);
	var y_sum = ySplit[0].plus(ySplit[1]);

	var b = karatsuba(x_sum, y_sum);

	var b_minus_a = b.minus(a);
	var b_minus_a_minus_c = b_minus_a.minus(c);
	var b_powed = b_minus_a_minus_c.timesTenToThe(deg);

	return a_powed.plus(c).plus(b_powed);
}

<|endoftext|>


<commit_before>var TCM = TCM || {};

(function($) {

    TCM.addLoading = function(trigger, context) {
        $(context).find(trigger).click(function() {
            var $container = $(this).closest(context),
                addLoadingCSS = function() {
                    var vertHeight = (parseInt($container.css('height'), 10) - parseInt($container.css('line-height'), 10)) / 2 + 'px',
                        style = '';
                    $('head').append(style);
                };
            $container.addClass('loading');
            addLoadingCSS();
        });
    };

    var filtering = function() {
        var button = $('#filter .visual .content button[type="submit"]').hide(),
            input = $('#filter .visual .filter-group input[type="checkbox"]').each(function() {
                $(this).data('originallyChecked', $(this).is(':checked'));
            }),
            filterOptions = $('#filter .visual .filter-group li'),
            textbox = $('#filter .textual #text-filter'),
            typedText = textbox.val(),
            suggestionList = $('#filter .textual ul.suggest').hide(),
            updateButton = function() {
                if ($('#filter .visual .filter-group input[type="checkbox"]').filter(function() {
                    return $(this).data('state') === 'changed';
                }).length) {
                    button.fadeIn('fast');
                } else {
                    button.fadeOut('fast');
                }
            };

        input.change(function() {
            if ($(this).data('originallyChecked') !== $(this).is(':checked')) {
                $(this).data('state', 'changed');
            } else {
                $(this).data('state', null);
            }
            updateButton();
        });

        textbox.keyup(function() {
            if ($(this).val() !== typedText) {
                typedText = $(this).val();
                var relevantFilters = filterOptions.filter(function() {
                        return $(this).children('label').html().toLowerCase().substring(0, typedText.length) === typedText.toLowerCase();
                    });
                $('#filter .textual ul.suggest').empty();
                relevantFilters.each(function() {
                    var remainingText = $(this).children('label').html().substring(typedText.length),
                        type = $(this).children('input').attr('name'),
                        id = $(this).children('input').attr('id'),
                        newHTML = '
' + typedText + ''+ remainingText + ' [' + type + ']
';
                    suggestionList.append(newHTML);
                });
            }
        });

        textbox.focus(function() {
            suggestionList.show();
            textbox.data('clicked', false);
        });

        textbox.blur(function() {
            function hideList() {
                if (textbox.data('clicked') !== true) {
                    suggestionList.hide();
                }
            }
            window.setTimeout(hideList, 150);
        });

        suggestionList.find('a').live('mousedown', function() {
            textbox.data('clicked', true);
        });

        suggestionList.find('a').live('click', function() {
            var thisFilter = $('#filter .visual .filter-group input#' + $(this).data('id'));
            thisFilter.attr('checked', 'checked');
            if (thisFilter.data('originallyChecked') !== thisFilter.is(':checked')) {
                thisFilter.data('state', 'changed');
            }
            updateButton();
            textbox.data('clicked', false);
            suggestionList.hide();
            return false;
        });
    };

    $(function() {
        filtering();
        $('input[placeholder], textarea[placeholder]').placeholder();
        $('input, textarea').blur(
            function() {
                $(this).addClass('hadfocus');
            }
        );
        $('#filter .toggle a').click(
            function() {
                $('#filter .visual').toggleClass('compact').toggleClass('expanded');
                return false;
            }
        );
        if ($('html').hasClass('no-details')) {
            $('details').html5accordion('summary');
        }
        $('.details:not(html)').html5accordion('.summary');
        $('#sandbox .findertoggle').click(function() {
            $(this).add('#sandbox .finder').toggleClass('expanded').toggleClass('compact');
            return false;
        });
        $('#sandbox').html5finder( {
            loading: true,
            horizontalScroll: true,
            scrollContainer: '.finder.expanded',
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs',
                'cases',
                'results'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]',
                'input[name="case"]',
                'input[name="result"]'
            ]
        });
        $('.subnav .findertoggle').click(function() {
            $(this).add('.subnav .finder').toggleClass('expanded').toggleClass('compact');
            return false;
        });
        $('.subnav').html5finder( {
            loading: true,
            horizontalScroll: true,
            scrollContainer: '.finder.expanded',
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs',
                'cases',
                'results'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]',
                'input[name="case"]',
                'input[name="result"]'
            ]
        });
        $('#selectruns').html5finder( {
            loading: true,
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]'
            ],
            callback: function() {
                $('#selectruns + #environment').slideUp();
            },
            lastChildCallback: function() {
                $('#selectruns + #environment').slideDown();
            }
        });
        $('#selectruns + #environment').hide();
    });

})(jQuery);<commit_msg>js filter autocomplete hide selected, clear textbox on select, never display full list<commit_after>var TCM = TCM || {};

(function($) {

    TCM.addLoading = function(trigger, context) {
        $(context).find(trigger).click(function() {
            var $container = $(this).closest(context),
                addLoadingCSS = function() {
                    var vertHeight = (parseInt($container.css('height'), 10) - parseInt($container.css('line-height'), 10)) / 2 + 'px',
                        style = '';
                    $('head').append(style);
                };
            $container.addClass('loading');
            addLoadingCSS();
        });
    };

    var filtering = function() {
        var button = $('#filter .visual .content button[type="submit"]').hide(),
            input = $('#filter .visual .filter-group input[type="checkbox"]').each(function() {
                $(this).data('originallyChecked', $(this).is(':checked'));
            }),
            filterOptions = $('#filter .visual .filter-group li'),
            textbox = $('#filter .textual #text-filter'),
            typedText = textbox.val(),
            suggestionList = $('#filter .textual ul.suggest').hide(),
            updateButton = function() {
                if ($('#filter .visual .filter-group input[type="checkbox"]').filter(function() {
                    return $(this).data('state') === 'changed';
                }).length) {
                    button.fadeIn('fast');
                } else {
                    button.fadeOut('fast');
                }
            };

        input.change(function() {
            if ($(this).data('originallyChecked') !== $(this).is(':checked')) {
                $(this).data('state', 'changed');
            } else {
                $(this).data('state', null);
            }
            updateButton();
        });

        textbox.keyup(function() {
            if ($(this).val() !== typedText) {
                if ($(this).val().length) {
                    typedText = $(this).val();
                    var relevantFilters = input.not(':checked').parent('li').filter(function() {
                            return $(this).children('label').html().toLowerCase().substring(0, typedText.length) === typedText.toLowerCase();
                        });
                    suggestionList.empty();
                    relevantFilters.each(function() {
                        var remainingText = $(this).children('label').html().substring(typedText.length),
                            type = $(this).children('input').attr('name'),
                            id = $(this).children('input').attr('id'),
                            newHTML = '
' + typedText + ''+ remainingText + ' [' + type + ']
';
                        suggestionList.append(newHTML);
                    });
                } else {
                    typedText = $(this).val();
                    suggestionList.empty();
                }
            }
        });

        textbox.focus(function() {
            suggestionList.show();
            textbox.data('clicked', false);
        });

        textbox.blur(function() {
            function hideList() {
                if (textbox.data('clicked') !== true) {
                    suggestionList.hide();
                }
            }
            window.setTimeout(hideList, 150);
        });

        suggestionList.find('a').live('mousedown', function() {
            textbox.data('clicked', true);
        });

        suggestionList.find('a').live('click', function() {
            var thisFilter = $('#filter .visual .filter-group input#' + $(this).data('id')).attr('checked', 'checked');
            if (thisFilter.data('originallyChecked') !== thisFilter.is(':checked')) {
                thisFilter.data('state', 'changed');
            }
            updateButton();
            textbox.data('clicked', false).val(null);
            typedText = textbox.val();
            suggestionList.empty().hide();
            return false;
        });
    };

    $(function() {
        filtering();
        $('input[placeholder], textarea[placeholder]').placeholder();
        $('input, textarea').blur(
            function() {
                $(this).addClass('hadfocus');
            }
        );
        $('#filter .toggle a').click(
            function() {
                $('#filter .visual').toggleClass('compact').toggleClass('expanded');
                return false;
            }
        );
        if ($('html').hasClass('no-details')) {
            $('details').html5accordion('summary');
        }
        $('.details:not(html)').html5accordion('.summary');
        $('#sandbox .findertoggle').click(function() {
            $(this).add('#sandbox .finder').toggleClass('expanded').toggleClass('compact');
            return false;
        });
        $('#sandbox').html5finder( {
            loading: true,
            horizontalScroll: true,
            scrollContainer: '.finder.expanded',
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs',
                'cases',
                'results'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]',
                'input[name="case"]',
                'input[name="result"]'
            ]
        });
        $('.subnav .findertoggle').click(function() {
            $(this).add('.subnav .finder').toggleClass('expanded').toggleClass('compact');
            return false;
        });
        $('.subnav').html5finder( {
            loading: true,
            horizontalScroll: true,
            scrollContainer: '.finder.expanded',
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs',
                'cases',
                'results'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]',
                'input[name="case"]',
                'input[name="result"]'
            ]
        });
        $('#selectruns').html5finder( {
            loading: true,
            headerSelector: 'header.listordering',
            sectionSelector: 'section.col',
            sectionContentSelector: 'ul.colcontent',
            sectionClasses: [
                'products',
                'cycles',
                'runs'
            ],
            sectionItemSelectors: [
                'input[name="product"]',
                'input[name="cycle"]',
                'input[name="run"]'
            ],
            callback: function() {
                $('#selectruns + #environment').slideUp();
            },
            lastChildCallback: function() {
                $('#selectruns + #environment').slideDown();
            }
        });
        $('#selectruns + #environment').hide();
    });

})(jQuery);<|endoftext|>


<commit_before>const assert = require('chai').assert;
const Lingo = require('../lib/game');
const Score = require('../lib/score');

describe('Lingo', function(){
  it('should be an object', function(){
    var lingo = new Lingo();
    assert.isObject(lingo);
  });
   it('should select a mystery word from the pool of possible words', function(){
     var lingo = new Lingo();
     var array = ['sport','mulch','foams','phone','grunt'];
     var mysteryWord = lingo.generateMysteryWord(array);
     assert.include(array, mysteryWord);
   });
   it('should split a word into an array', function() {
     var lingo = new Lingo();
     var array = lingo.generateWordArray('grunt');
     assert.equal(array[0], 'g');
   });
   it('should be able to check if a word includes a given letter', function() {
     var lingo = new Lingo();
     var answer = lingo.checkWordArrayForLetter('alex', 'x');
     assert.isTrue(answer);
     // yellow
   });
   it('should return an array of five orange tiles when a player guesses a correct word.', function () {
  var arrayOne = ['a', 'p', 'p', 'l', 'e'];
  var arrayTwo = ['a', 'p', 'p', 'l', 'e'];
  var colorArray = checkUserGuess(arrayOne, arrayTwo);
  assert.equal(colorArray, ['orange', 'orange', 'orange', 'orange', 'orange']);
  });
  it('should not return an array of five orange tiles when a player guesses a correct word.', function () {
    var arrayOne = ['a', 'p', 'p', 'x', 'e'];
    var arrayTwo = ['a', 'p', 'p', 'l', 'e'];
    var colorArray = checkUserGuess(arrayOne, arrayTwo);
    assert.notEqual(colorArray, ['orange', 'orange', 'orange', 'orange', 'orange']);
  });

  it('should return false if the letter has already been found.', function () {
    var mysteryarray = ['a', 'p', 'p', 'l', 'e'];
    var userArray = ['p', 'p', 'p', 'l', 'e'];
    var character = 'p';
    assert.equal(letterFound(mysteryarray, userArray, character), false);
  });
  it('should return false if the letter has already been found.', function () {
    var mysteryarray = ['a', 'p', 'p', 'l', 'e'];
    var userArray = ['p', 'p', 'p', 'l', 'e'];
    var character = 'p';
    assert.equal(letterFound(mysteryarray, userArray, character), true);
  });

  it('should return a yellow tile if a player guesses a correct letter but in the incorrect position and that letter has not already been found.', function () {

  });
   it('should iterate the score up one on update score', function(){

   });
   it('should update the high score if the current score is greater', function(){

   });
   it('should NOT update the high score if the current score is not greater', function(){

   });
   it('should check whether the user guessed a word from the dictionary', function(){

   });
   it('should not accept characters that are not letters using the RegExp', function(){

   });
   it('should accept characters that are letters using the RegExp', function(){

   });
   it('isWord should be a function', function(){

   });
   it('checkUserGuess should be a function', function(){

   });
   it('checkUserGuess should return an array', function(){

   });
   it('should return an array of none if none of the letters are guessed', function(){

   });
   it('letterFound should be a function', function(){

   });
   it('letterFound should take three arguments', function(){

   });
   it('isGameOver should be a function', function(){

   });
   it('isLetter should be a function', function(){

   });
   it('isLetter should return true on a letter keypress', function(){

   });
   it('getUserWordArray should be a function', function(){

   });
   it('getUserWordArray should return an array', function() {

   });
   it('newWordRow should be a function', function(){

   });
   it('should return true when orangeArray.length is 5', function(){

   });
   it('isRowFilled should be a function', function(){

   });
   it('should toggleClass when the user guessed a correct word', function(){

   });
   it('retrieveHighScore should be a function', function(){

   });
   it('should return a high score when the user retrieveHighScore', function(){

   });
   it('retrieveCurrentScore should be a function', function(){

   });
   it('should return a user score when the user retrieveCurrentScore', function(){

   });
   it('clearStorage should be a function', function(){

   });
   it('storeMysteryWord should be a function', function(){

   });
   it('storeCurrentScore should be a function', function(){

   });
   it('storeHighScore should be a function', function(){

   });
   it('renderScore should be a function', function(){

   });
   it('endGame should be a function', function(){

   });
   it('localStorage getItem mysteryWord should return a word', function(){

   });
 });
<commit_msg>asserts score is object<commit_after>const assert = require('chai').assert;
const Lingo = require('../lib/game');
const Score = require('../lib/score');

describe('Lingo', function(){
  it('should be an object', function(){
    var lingo = new Lingo();
    assert.isObject(lingo);
  });
  it('should select a mystery word from the pool of possible words', function(){
     var lingo = new Lingo();
     var array = ['sport','mulch','foams','phone','grunt'];
     var mysteryWord = lingo.generateMysteryWord(array);
     assert.include(array, mysteryWord);
  });
  it('should split a word into an array', function() {
     var lingo = new Lingo();
     var array = lingo.generateWordArray('grunt');
     assert.equal(array[0], 'g');
  });
  it('should be able to check if a word includes a given letter', function() {
     var lingo = new Lingo();
     var answer = lingo.checkWordArrayForLetter('alex', 'x');
     assert.isTrue(answer);
     // yellow
  });
  it('should return an array of five orange tiles when a player guesses a correct word.', function () {
    var arrayOne = ['a', 'p', 'p', 'l', 'e'];
    var arrayTwo = ['a', 'p', 'p', 'l', 'e'];
    var colorArray = checkUserGuess(arrayOne, arrayTwo);
    assert.equal(colorArray, ['orange', 'orange', 'orange', 'orange', 'orange']);
  });
  it('should not return an array of five orange tiles when a player guesses a correct word.', function () {
    var arrayOne = ['a', 'p', 'p', 'x', 'e'];
    var arrayTwo = ['a', 'p', 'p', 'l', 'e'];
    var colorArray = checkUserGuess(arrayOne, arrayTwo);
    assert.notEqual(colorArray, ['orange', 'orange', 'orange', 'orange', 'orange']);
  });

  it('should return false if the letter has already been found.', function () {
    var mysteryarray = ['a', 'p', 'p', 'l', 'e'];
    var userArray = ['p', 'p', 'p', 'l', 'e'];
    var character = 'p';
    assert.equal(letterFound(mysteryarray, userArray, character), false);
  });
  it('should return false if the letter has already been found.', function () {
    var mysteryarray = ['a', 'p', 'p', 'l', 'e'];
    var userArray = ['p', 'p', 'p', 'l', 'e'];
    var character = 'p';
    assert.equal(letterFound(mysteryarray, userArray, character), true);
  });
  it('should return a yellow tile if a player guesses a correct letter but in the incorrect position and that letter has not already been found.', function () {

  });
  it('should iterate the score up one on update score', function(){

  });
  it('should update the high score if the current score is greater', function(){

  });
  it('should NOT update the high score if the current score is not greater', function(){

  });
  it('should check whether the user guessed a word from the dictionary', function(){

  });
  it('should not accept characters that are not letters using the RegExp', function(){

  });
  it('should accept characters that are letters using the RegExp', function(){

  });
  it('isWord should be a function', function(){

  });
  it('checkUserGuess should be a function', function(){

  });
  it('checkUserGuess should return an array', function(){

  });
  it('should return an array of none if none of the letters are guessed', function(){

  });
  it('letterFound should be a function', function(){

  });
  it('letterFound should take three arguments', function(){

  });
  it('isGameOver should be a function', function(){

  });
  it('isLetter should be a function', function(){

  });
  it('isLetter should return true on a letter keypress', function(){

  });
  it('getUserWordArray should be a function', function(){

  });
  it('getUserWordArray should return an array', function() {

  });
  it('newWordRow should be a function', function(){

  });
  it('should return true when orangeArray.length is 5', function(){

  });
  it('isRowFilled should be a function', function(){

  });
  it('should toggleClass when the user guessed a correct word', function(){

  });
  it('Score should be an object', function(){
    assert.isObject(Score);
  });
  it('retrieveHighScore should be a function', function(){

  });
  it('should return a high score when the user retrieveHighScore', function(){

  });
  it('retrieveCurrentScore should be a function', function(){

  });
  it('should return a user score when the user retrieveCurrentScore', function(){

  });
  it('clearStorage should be a function', function(){

  });
  it('storeMysteryWord should be a function', function(){

  });
  it('storeCurrentScore should be a function', function(){

  });
  it('storeHighScore should be a function', function(){

  });
  it('renderScore should be a function', function(){

  });
  it('endGame should be a function', function(){

  });
  it('localStorage getItem mysteryWord should return a word', function(){

  });
});
<|endoftext|>


<commit_before>const chai     = require('chai');
const assert   = chai.assert;
const Game     = require('../lib/game.js').Game;
const Cycle    = require('../lib/cycle.js');

describe('Game Start', function () {
  it('Creates a new game', function() {
    var game = new Game();
    assert(game);
  });

  it('Two cycles are created', function () {
    var game = new Game();

    assert(game.cycle);
    assert(game.cycle2);
  });
});

describe('Canvas boundries', function () {

  it('moves off the screen from left to right', function () {
    var cycle = new Cycle(0, 0, 10, 10);

    cycle.move("left");
    assert.equal(cycle.x, 800);
  });

  it('moves off the screen from right to left', function () {
    var cycle = new Cycle(800, 0, 10, 10);

    cycle.move("right");
    assert.equal(cycle.x, 0);
  });

  it('moves off the screen from top to bottom', function () {
    var cycle = new Cycle(0, 0, 10, 10);

    cycle.move("up");
    assert.equal(cycle.y, 450);
  });

  it('moves off the screen from bottom to top', function () {
    var cycle = new Cycle(0, 800, 10, 10);

    cycle.move('down');
    assert.equal(cycle.y, 0);
  });

});

describe('Collision Detection', function (){

  it('cannot turn back in original direction', function () {
    var game = new Game();

    game.cycle.move('right');
    game.cycle.move('left');

    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('returns collision when 2 cycles meet', function (){
    var game = new Game();

    game.lightRibbons.push([game.cycle.x, game.cycle.y]);
    game.cycle2.x = game.cycle.x;
    game.cycle2.y = game.cycle.y;

    assert.equal(game.state, "started");

    game.collision(game.cycle2);

    assert.equal(game.state, "game over");
  });

  it('returns collision when using turbo speed', function() {
    var game = new Game();

    game.cycle.speed = 2;
    game.cycle.move("left");
    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('returns collision when both cycles using turbo speed', function() {
    var game = new Game();

    game.cycle.speed = 2;
    game.cycle2.speed = 2;
    game.cycle.move("left");
    game.cycle2.move("left");
    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('does not return a collision when cycles do not cross paths', function() {
    var game = new Game();

    game.updateLightCycleRibbons();

    game.cycle.move("up");
    game.cycle2.move("down");
    game.collision(game.cycle2);

    assert.equal(game.state, "started");
  });

  it('updates light cycles ribbons', function () {
    var game = new Game();

    game.cycle.move("up");
    game.cycle2.move("down");
    game.updateLightCycleRibbons();

    assert.equal(game.lightRibbons.length, 5);
  });

});
<commit_msg>fix test<commit_after>const chai     = require('chai');
const assert   = chai.assert;
const Game     = require('../lib/game.js').Game;
const Cycle    = require('../lib/cycle.js');

describe('Game Start', function () {
  it('Creates a new game', function() {
    var game = new Game();
    assert(game);
  });

  it('Two cycles are created', function () {
    var game = new Game();

    assert(game.cycle);
    assert(game.cycle2);
  });
});

describe('Canvas boundries', function () {

  it('moves off the screen from left to right', function () {
    var cycle = new Cycle(0, 0, 10, 10);

    cycle.move("left");
    assert.equal(cycle.x, 800);
  });

  it('moves off the screen from right to left', function () {
    var cycle = new Cycle(800, 0, 10, 10);

    cycle.move("right");
    assert.equal(cycle.x, 0);
  });

  it('moves off the screen from top to bottom', function () {
    var cycle = new Cycle(0, 0, 10, 10);

    cycle.move("up");
    assert.equal(cycle.y, 450);
  });

  it('moves off the screen from bottom to top', function () {
    var cycle = new Cycle(0, 800, 10, 10);

    cycle.move('down');
    assert.equal(cycle.y, 0);
  });

});

describe('Collision Detection', function (){

  it('cannot turn back in original direction', function () {
    var game = new Game();

    game.cycle.move('right');
    game.cycle.move('left');

    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('returns collision when 2 cycles meet', function (){
    var game = new Game();

    game.lightRibbons.push([game.cycle.x, game.cycle.y]);
    game.cycle2.x = game.cycle.x;
    game.cycle2.y = game.cycle.y;

    assert.equal(game.state, "started");

    game.collision(game.cycle2);

    assert.equal(game.state, "game over");
  });

  it('returns collision when using turbo speed', function() {
    var game = new Game();

    game.cycle.speed = 2;
    game.cycle.move("left");
    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('returns collision when both cycles using turbo speed', function() {
    var game = new Game();

    game.cycle.speed = 2;
    game.cycle2.speed = 2;
    game.cycle.move("left");
    game.cycle2.move("left");
    game.updateLightCycleRibbons();

    assert.equal(game.state, "started");

    game.collision(game.cycle);

    assert.equal(game.state, "game over");
  });

  it('does not return a collision when cycles do not cross paths', function() {
    var game = new Game();

    game.updateLightCycleRibbons();

    game.cycle.move("up");
    game.cycle2.move("down");
    game.collision(game.cycle2);

    assert.equal(game.state, "started");
  });

  it('updates light cycles ribbons', function () {
    var game = new Game();

    game.cycle.move("up");
    game.cycle2.move("down");
    game.updateLightCycleRibbons();

    assert.equal(game.lightRibbons.length, 4);
  });

});
<|endoftext|>


<commit_before>// use prime sieve to generate a list of primes
// up to the limit
const assert = require('assert');
const sieve = limit  => {

  let bools = [];
  let primes = [];

  // create list of booleons
  for (let i = 1; i < limit; i+= 1) { bools.push(true); }

  // loop to limit by setting to false
  for (let i = 2; i < limit; i+= 1) {
    if (bools[i-2]) {
      for (let j = i*2; j<= limit; j += 1) {
        bools[j-2] = false;
      }
    }
  }

  // generate list of primes where there is a
  // true value in booleon array
  for (let p = 0; p < bools.length; p++) {
    if (bools[p]) { primes.push(p+2); }
  }

  return primes;

};

const a1 = '16'// input
const t1 = sieve(a1);
assert(t1);
<commit_msg>wip=test function with primes<commit_after>// use prime sieve to generate a list of primes
// up to the limit
const assert = require('assert');
const PrimeMover = num => {

  // negative numbers cannot be primes
  if (num < 1) { return 'invalid'; }

  // first prime number is 2, the only even prime
  if (num === 1) { return 2; }

  // if greater than 2, start count at 1
  let count = 1;
  let n = 3;

  // loop until the numth prime
  while (count != num) {

    // check if n is divisible by each number in between to see if it is a prime
    for (let i = 2; i < n; i+= 1) {

      // if reach the end, this number is a prime because it was
      // not divisible by any numbers so increase the count by 1
      if (i === n-1) {
        count+= 1;
        n+= 1;
        break;
      }
      // if n is divisible by some number, then it is not a prime
      // and simply move on to the next number
      else if (n % i === 0) {
        n+= 1;
        break;
      }
    }
  }

  return n-1;

};

const a1 = '16'// input
const t1 = PrimeMover(a1);
assert(t1);
<|endoftext|>


<commit_before>'use strict'

const num_instances = process.argv[2] || 42;
const instances = [];
const events = [];
const domain = '<http://doma.in/_i/';
const iri_end = '> ';
const onEnd = domain + 'INSTANCE/onEnd>';
const onError = domain + 'INSTANCE/onError>';

let string = '';
let instance;
let instance_iri;
let step;
let num_events;
let event;
let event_iri;
let first_sequence;
let eStep
let num_sequence;
let sequence;
let handler_type;
let target;
let sStep;

// TODO create ids, then the triples
// TODO select onError and onEnd from cached events

for (step = 0; num_instances > step; ++step) {

    // instance
    instance = UID(8);
    instance_iri = domain + instance + iri_end;
    instances.push(instance_iri);
    //string += createInstance(instance_iri, instance);
    process.stdout.write(createInstance(instance_iri, instance));

    // event
    num_events = random(1, 23);
    for (eStep = 0; num_events > eStep; ++eStep) {
        event = UID(8);
        event_iri = domain + instance + '/' + event + iri_end;
        events.push(event_iri);
        first_sequence = '_:' + UID(8);
        //string += createEvent(instance_iri, event_iri, event, first_sequence);
        process.stdout.write(createEvent(instance_iri, event_iri, event, first_sequence));

        // sequence
        num_sequence = random(1, 23);
        for (sStep = 0; num_sequence > sStep; ++sStep) {

            // first_seq > seq > seq > seq ..
            sequence = sStep === (num_sequence - 1) ? null : '_:' + UID(8);
            handler_type = random(0, 2);

            // select random event
            if (handler_type > 1) {
                target = events[random(0, events.length - 1)];
                //string += createEventHandler(target, first_sequence, sequence);
                process.stdout.write(createEventHandler(target, first_sequence, sequence));

            // select random instance
            } else {
                target = instances[random(0, instances.length - 1)];

                if (handler_type === 0) {
                    //string += createDataHandler(target, first_sequence, sequence);
                    process.stdout.write(createDataHandler(target, first_sequence, sequence));
                } else {
                    //string += createStreamHandler(target, first_sequence, sequence);
                    process.stdout.write(createStreamHandler(target, first_sequence, sequence));
                }
            }

            first_sequence = sequence;
        }
    }
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};

function random (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// create basic instance triples
function createInstance (iri, name) {
    let s = iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/roles> "\\"*\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/ModuleInstanceConfig> .\n' +
            iri + '<http://schema.jillix.net/vocab/module> <https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json> .\n';

    return s;
};

function createEvent (inst, iri, name, sequence) {
    let s = inst + '<http://schema.jillix.net/vocab/event> ' + iri + '.\n' +
            iri + '<http://schema.jillix.net/vocab/onError> ' + onError + ' .\n' +
            iri + '<http://schema.jillix.net/vocab/onEnd> ' + onEnd + ' .\n' +
            iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/FlowEvent> .\n' +
            iri + '<http://schema.jillix.net/vocab/sequence> ' + sequence + ' .\n';

    return s;
};

function createEventHandler(event, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/emit> ' + event + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/EventEmit> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createDataHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/DataHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/dataHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#data> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createStreamHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/StreamHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/streamHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#stream> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};
<commit_msg>Write triples to stdout<commit_after>'use strict'

const num_instances = process.argv[2] || 42;
const instances = [];
const events = [];
const domain = '<http://doma.in/_i/';
const iri_end = '> ';
const onEnd = domain + 'INSTANCE/onEnd>';
const onError = domain + 'INSTANCE/onError>';

let instance;
let instance_iri;
let step;
let num_events;
let event;
let event_iri;
let first_sequence;
let eStep
let num_sequence;
let sequence;
let handler_type;
let target;
let sStep;

// TODO create ids, then the triples
// TODO select onError and onEnd from cached events

for (step = 0; num_instances > step; ++step) {

    // instance
    instance = UID(8);
    instance_iri = domain + instance + iri_end;
    instances.push(instance_iri);
    process.stdout.write(createInstance(instance_iri, instance));

    // event
    num_events = random(1, 23);
    for (eStep = 0; num_events > eStep; ++eStep) {
        event = UID(8);
        event_iri = domain + instance + '/' + event + iri_end;
        events.push(event_iri);
        first_sequence = '_:' + UID(8);
        process.stdout.write(createEvent(instance_iri, event_iri, event, first_sequence));

        // sequence
        num_sequence = random(1, 23);
        for (sStep = 0; num_sequence > sStep; ++sStep) {

            // first_seq > seq > seq > seq ..
            sequence = sStep === (num_sequence - 1) ? null : '_:' + UID(8);
            handler_type = random(0, 2);

            // select random event
            if (handler_type > 1) {
                target = events[random(0, events.length - 1)];
                process.stdout.write(createEventHandler(target, first_sequence, sequence));

            // select random instance
            } else {
                target = instances[random(0, instances.length - 1)];

                if (handler_type === 0) {
                    process.stdout.write(createDataHandler(target, first_sequence, sequence));
                } else {
                    process.stdout.write(createStreamHandler(target, first_sequence, sequence));
                }
            }

            first_sequence = sequence;
        }
    }
}

function UID (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};

function random (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// create basic instance triples
function createInstance (iri, name) {
    let s = iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://schema.jillix.net/vocab/roles> "\\"*\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/ModuleInstanceConfig> .\n' +
            iri + '<http://schema.jillix.net/vocab/module> <https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json> .\n';

    return s;
};

function createEvent (inst, iri, name, sequence) {
    let s = inst + '<http://schema.jillix.net/vocab/event> ' + iri + '.\n' +
            iri + '<http://schema.jillix.net/vocab/onError> ' + onError + ' .\n' +
            iri + '<http://schema.jillix.net/vocab/onEnd> ' + onEnd + ' .\n' +
            iri + '<http://schema.org/name> "\\"' + name + '\\"" .\n' +
            iri + '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/FlowEvent> .\n' +
            iri + '<http://schema.jillix.net/vocab/sequence> ' + sequence + ' .\n';

    return s;
};

function createEventHandler(event, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/emit> ' + event + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/EventEmit> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createDataHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/DataHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/dataHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#data> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};

function createStreamHandler(instance, seq, nextSeq) {
    let s = seq + ' <http://schema.jillix.net/vocab/instance> ' + instance + '.\n' +
            seq + ' <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.jillix.net/vocab/StreamHandler> .\n' +
            seq + ' <http://schema.jillix.net/vocab/streamHandler> ' +
            '<https://raw.githubusercontent.com/adioo/flow-dummy/master/module.json#stream> .\n';

    if (nextSeq) {
        s += seq + ' <http://schema.jillix.net/vocab/sequence> ' + nextSeq + ' .\n';
    }

    return s;
};
<|endoftext|>


<commit_before>const Generator = require('yeoman-generator');
const chalk = require('chalk');
const config = require('../lib/config');
const { validate, find } = require('../lib/schemas');

module.exports = class EgGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this._configuration = null;
    this.eg = this.env.eg;
    this.argv = this.env.argv;
    this.admin = require('../admin')({
      baseUrl: this._getAdminClientBaseURL(),
      verbose: this._getAdminClientVerboseFlag(),
      headers: this.argv ? this.argv.H : null
    });
  }

  configureCommand (configuration) {
    const builder = configuration.builder;
    configuration.builder = yargs => {
      return this._wrapConfig(builder(yargs));
    };

    configuration.handler = argv => {
      this.env.argv = argv;

      const command = this.options.env.commandAliases[0][argv._[0]];
      const subCommand = this.options.env.commandAliases[1][command][argv._[1]];

      this.env.run(`express-gateway:${command}:${subCommand}`);
    };

    this._configuration = configuration;
  }

  stdout (...args) {
    // eslint-disable-next-line no-console
    console.log.apply(console, args);
  }

  createSubCommand (name) {
    const generatorName = `${this.constructor.namespace}:${name}`;
    return this.env.create(generatorName)._configuration;
  }

  // configuration defaults
  _wrapConfig (yargs) {
    return yargs
      .boolean(['no-color', 'q', 'v'])
      .string(['H'])
      .describe('no-color', 'Disable color in prompts')
      .alias('q', 'quiet')
      .describe('q', 'Only show major pieces of output')
      .describe('H', 'Header to send with each request to Express Gateway Admin API KEY:VALUE format')
      .alias('v', 'verbose')
      .describe('v', 'Verbose output, will show request to Admin API')
      .group(['no-color', 'q'], 'Options:')
      .help('h');
  }

  _getAdminClientBaseURL () {
    const gatewayConfig = config.gatewayConfig;
    const systemConfig = config.systemConfig;

    let baseURL = 'http://localhost:9876/'; // fallback default

    if (process.env.EG_ADMIN_URL) {
      baseURL = process.env.EG_ADMIN_URL;
    } else if (systemConfig && systemConfig.cli && systemConfig.cli.url) {
      baseURL = systemConfig.cli.url;
    } else if (gatewayConfig && gatewayConfig.admin) {
      const adminConfig = gatewayConfig.admin;
      const hostname = adminConfig.hostname || 'localhost';
      const port = adminConfig.port || 9876;

      baseURL = `http://${hostname}:${port}/`;
    }

    return baseURL;
  }

  _getAdminClientVerboseFlag () {
    let verbose = false; // default

    if (this.argv && this.argv.v) {
      verbose = this.argv.v;
    } else if (config.systemConfig && config.systemConfig.cli) {
      verbose = !!config.systemConfig.cli.verbose;
    }

    return verbose;
  }

  _promptAndValidate (object, schema, options) {
    options = options || {};
    options.skipPrompt = options.skipPrompt || false;

    let questions = [];

    if (!options.skipPrompt) {
      let shouldPrompt = false;
      const missingProperties = [];
      const modelSchema = find(schema).schema;

      Object.keys(modelSchema.properties).forEach(prop => {
        const descriptor = modelSchema.properties[prop];
        if (!object[prop]) {
          if (!shouldPrompt && modelSchema.required.includes(prop)) {
            shouldPrompt = true;
          }

          missingProperties.push({ name: prop, descriptor: descriptor });
        }
      });

      if (shouldPrompt) {
        questions = missingProperties.map(p => {
          const required = modelSchema.required.includes(p.name)
            ? ' [required]'
            : '';

          return {
            name: p.name,
            message: `Enter ${chalk.yellow(p.name)}${chalk.green(required)}:`,
            default: p.default,
            validate: input => !modelSchema.required.includes(p.name) ||
              (!!input && modelSchema.required.includes(p.name)),
            filter: input => input === '' && !modelSchema.required.includes(p.name) ? undefined : input
          };
        });
      }
    }

    const validateData = data => {
      const { isValid, error } = validate(schema, data);
      if (!isValid) {
        this.stdout(error);
        return this.prompt(questions).then(validateData);
      }
      return data;
    };

    return this.prompt(questions).then(validateData);
  }
};
<commit_msg>Make eg-generator accomodate both stdin and prompt case<commit_after>const Generator = require('yeoman-generator');
const chalk = require('chalk');
const config = require('../lib/config');
const { validate, find } = require('../lib/schemas');

module.exports = class EgGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this._configuration = null;
    this.eg = this.env.eg;
    this.argv = this.env.argv;
    this.admin = require('../admin')({
      baseUrl: this._getAdminClientBaseURL(),
      verbose: this._getAdminClientVerboseFlag(),
      headers: this.argv ? this.argv.H : null
    });
  }

  configureCommand (configuration) {
    const builder = configuration.builder;
    configuration.builder = yargs => {
      return this._wrapConfig(builder(yargs));
    };

    configuration.handler = argv => {
      this.env.argv = argv;

      const command = this.options.env.commandAliases[0][argv._[0]];
      const subCommand = this.options.env.commandAliases[1][command][argv._[1]];

      this.env.run(`express-gateway:${command}:${subCommand}`);
    };

    this._configuration = configuration;
  }

  stdout (...args) {
    // eslint-disable-next-line no-console
    console.log.apply(console, args);
  }

  createSubCommand (name) {
    const generatorName = `${this.constructor.namespace}:${name}`;
    return this.env.create(generatorName)._configuration;
  }

  // configuration defaults
  _wrapConfig (yargs) {
    return yargs
      .boolean(['no-color', 'q', 'v'])
      .string(['H'])
      .describe('no-color', 'Disable color in prompts')
      .alias('q', 'quiet')
      .describe('q', 'Only show major pieces of output')
      .describe('H', 'Header to send with each request to Express Gateway Admin API KEY:VALUE format')
      .alias('v', 'verbose')
      .describe('v', 'Verbose output, will show request to Admin API')
      .group(['no-color', 'q'], 'Options:')
      .help('h');
  }

  _getAdminClientBaseURL () {
    const gatewayConfig = config.gatewayConfig;
    const systemConfig = config.systemConfig;

    let baseURL = 'http://localhost:9876/'; // fallback default

    if (process.env.EG_ADMIN_URL) {
      baseURL = process.env.EG_ADMIN_URL;
    } else if (systemConfig && systemConfig.cli && systemConfig.cli.url) {
      baseURL = systemConfig.cli.url;
    } else if (gatewayConfig && gatewayConfig.admin) {
      const adminConfig = gatewayConfig.admin;
      const hostname = adminConfig.hostname || 'localhost';
      const port = adminConfig.port || 9876;

      baseURL = `http://${hostname}:${port}/`;
    }

    return baseURL;
  }

  _getAdminClientVerboseFlag () {
    let verbose = false; // default

    if (this.argv && this.argv.v) {
      verbose = this.argv.v;
    } else if (config.systemConfig && config.systemConfig.cli) {
      verbose = !!config.systemConfig.cli.verbose;
    }

    return verbose;
  }

  _promptAndValidate (object, schema, options) {
    options = options || {};
    options.skipPrompt = options.skipPrompt || false;

    let questions = [];

    if (!options.skipPrompt) {
      let shouldPrompt = false;
      const missingProperties = [];
      const modelSchema = find(schema).schema;

      Object.keys(modelSchema.properties).forEach(prop => {
        const descriptor = modelSchema.properties[prop];
        if (!object[prop]) {
          if (!shouldPrompt && modelSchema.required.includes(prop)) {
            shouldPrompt = true;
          }

          missingProperties.push({ name: prop, descriptor: descriptor });
        }
      });

      if (shouldPrompt) {
        questions = missingProperties.map(p => {
          const required = modelSchema.required.includes(p.name)
            ? ' [required]'
            : '';

          return {
            name: p.name,
            message: `Enter ${chalk.yellow(p.name)}${chalk.green(required)}:`,
            default: p.default,
            validate: input => !modelSchema.required.includes(p.name) ||
              (!!input && modelSchema.required.includes(p.name)),
            filter: input => input === '' && !modelSchema.required.includes(p.name) ? undefined : input
          };
        });
      }
    }

    const validateData = data => {
      const { isValid, error } = validate(schema, data);
      if (!isValid) {
        this.log.error(error);
        if (!options.skipPrompt) {
          return this.prompt(questions).then(validateData);
        }
        return {};
      }
      return data;
    };

    return this.prompt(questions).then((answers) => {
      Object.assign(object, answers);
      return validateData(object);
    });
  }
};
<|endoftext|>


<commit_before>const parse = require('../src/area-tools/parse-hanson-string').parse
const nom = require('nomnom')
const stringify = require('json-stable-stringify')
const yaml = require('js-yaml')
const util = require('util')
const getStdin = require('get-stdin')

function parseString(args, string) {
	if (string.length === 0) {
		throw new Error('Either --stdin or an argument is required')
	}

	const parsed = parse(string)

	if (args.json) {
		console.log(stringify(parsed, {space: 4}))
	}
	else if (args.yaml) {
		console.log(yaml.safeDump(parsed))
	}
	else {
		console.log(util.inspect(parsed, {depth: null}))
	}
}

exports.cli = function cli() {
	const args = nom
		.option('json', {flag: true, help: 'Print the result as valid JSON'})
		.option('yaml', {flag: true, help: 'Print the result as YAML'})
		.option('stdin', {flag: true, help: 'Take input via STDIN'})
		.option('string', {position: 0})
		.parse()

	if (args.stdin) {
		getStdin().then(string => parseString(args, string))
	}
	else {
		parseString(args, args.string)
	}
}
<commit_msg>catch errors from parse-result<commit_after>const parse = require('../src/area-tools/parse-hanson-string').parse
const nom = require('nomnom')
const stringify = require('json-stable-stringify')
const yaml = require('js-yaml')
const util = require('util')
const getStdin = require('get-stdin')

function parseString(args, string) {
	if (string.length === 0) {
		throw new Error('Either --stdin or an argument is required')
	}

	const parsed = parse(string)

	if (args.json) {
		console.log(stringify(parsed, {space: 4}))
	}
	else if (args.yaml) {
		console.log(yaml.safeDump(parsed))
	}
	else {
		console.log(util.inspect(parsed, {depth: null}))
	}
}

module.exports.cli = function cli() {
	const args = nom
		.option('json', {flag: true, help: 'Print the result as valid JSON'})
		.option('yaml', {flag: true, help: 'Print the result as YAML'})
		.option('stdin', {flag: true, help: 'Take input via STDIN'})
		.option('string', {position: 0})
		.parse()

	if (args.stdin) {
		getStdin()
			.then(string => parseString(args, string))
			.catch(err => {
				throw err
			})
	}
	else {
		parseString(args, args.string)
	}
}

process.on('unhandledRejection', reason => {
	console.error(reason)
})
<|endoftext|>


<commit_before>/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
 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.*/

define.class('$server/composition', function(require, $ui$, screen, view, label){
	this.render = function(){ return [
		screen({name:'default', clearcolor:vec4('black')},
			view({bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fill",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Aspect Fill"})),
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fit",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Aspect Fit"})),
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"stretch",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Stretch"}))
			)
			 ,
			view({bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fill",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Aspect Fill"})),
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fit",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Aspect Fit"})),
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"stretch",
					bgimage:require('$resources/textures/hex_tiles.png')
				}, label({text:"Stretch"}))
			)
			 ,
			view({bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fill",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Aspect Fill"})),
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fit",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Aspect Fit"})),
				view({
					width:200,
					height:300,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"stretch",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Stretch"}))
			)
			 ,
			view({bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fill",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Aspect Fill"})),
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"aspect-fit",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Aspect Fit"})),
				view({
					width:300,
					height:200,
					borderwidth:1,
					bordercolor:"white",
					contentmode:"stretch",
					bgimage:require('$resources/textures/checker.png')
				}, label({text:"Stretch"}))
			)
		)
	]}
})
<commit_msg>fix up image test<commit_after>/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
 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.*/

define.class('$server/composition', function(require, $ui$, screen, view, label){
	this.render = function(){ return [
		screen({name:'default', clearcolor:vec4('black')},
			view({flexdirection:"column"},
				view({flex:1, bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fill",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Aspect Fill"})),
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fit",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Aspect Fit"})),
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"stretch",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Stretch"}))
				)
				,
				view({flex:1, bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fill",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Aspect Fill"})),
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fit",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Aspect Fit"})),
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"stretch",
						bgimage:require('$resources/textures/hex_tiles.png')
					}, label({text:"Stretch"}))
				)
				,
				view({flex:1, bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fill",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Aspect Fill"})),
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fit",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Aspect Fit"})),
					view({
						width:200,
						height:300,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"stretch",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Stretch"}))
				)
				,
				view({flex:1, bgcolor:'gray', borderradius:20, flexdirection:'row', justifycontent:"space-around", padding:30},
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fill",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Aspect Fill"})),
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"aspect-fit",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Aspect Fit"})),
					view({
						width:300,
						height:200,
						borderwidth:1,
						bordercolor:"white",
						contentmode:"stretch",
						bgimage:require('$resources/textures/checker.png')
					}, label({text:"Stretch"}))
				)
			)
		)
	]}
})
<|endoftext|>


<commit_before>import expect from './instrument'

import Immutable from 'immutable'
import all from '../build'

var mkPromise = function(val) {
  return Promise.resolve(val);
};

var mapLike = function(name) {
  return [
    'List'
  , 'Set'
  , 'OrderedSet'
  ].indexOf(name) < 0;
};

[
  'List'
, 'Set'
, 'OrderedSet'
, 'Map'
, 'OrderedMap'
// , 'Stack' // todo fix this
// , 'Seq'   // todo fix this
].forEach(function(name) {

  describe(`Immutable.${name}`, function() {
    it(`should return a ${name} of resolved values`, function(done) {

      var mutval  = mapLike(name) ? {a: "a", b: 2, c: "3" } : [1, 2, 3];
      var mutprom = mapLike(name) ? {a: "a", b: 2, c: Promise.resolve("3") } : [1, Promise.resolve(2), 3];

      var value = Immutable[name](mutval);
      var prom = Immutable[name](mutprom);

      expect(all(prom)).to
        .to.be.fulfilled
        .and.eventually.be.an.instanceof(Immutable[name])
        .and.eventually.satisfy(function(res) { return Immutable.is(res, value) })
        .and.notify(done);
    });

    it('should work for empty immutable', function(done) {

      var empty = Immutable[name]();
      expect(all(empty)).to
        .to.be.fulfilled
        .and.eventually.be.an.instanceof(Immutable[name])
        .and.eventually.satisfy(function(res) { return Immutable.is(res, empty) })
        .and.notify(done);
    });

    it('should work for empty immutable', function(done) {
      var imm = mapLike(name) ? {a: Promise.reject('FAIL')} : [Promise.reject('FAIL')];
      expect(all(imm)).to
        .eventually.be.rejectedWith('FAIL')
        .and.notify(done);
    });
  });
});
<commit_msg>correct message<commit_after>import expect from './instrument'

import Immutable from 'immutable'
import all from '../build'

var mkPromise = function(val) {
  return Promise.resolve(val);
};

var mapLike = function(name) {
  return [
    'List'
  , 'Set'
  , 'OrderedSet'
  ].indexOf(name) < 0;
};

[
  'List'
, 'Set'
, 'OrderedSet'
, 'Map'
, 'OrderedMap'
// , 'Stack' // todo fix this
// , 'Seq'   // todo fix this
].forEach(function(name) {

  describe(`Immutable.${name}`, function() {
    it(`should return a ${name} of resolved values`, function(done) {

      var mutval  = mapLike(name) ? {a: "a", b: 2, c: "3" } : [1, 2, 3];
      var mutprom = mapLike(name) ? {a: "a", b: 2, c: Promise.resolve("3") } : [1, Promise.resolve(2), 3];

      var value = Immutable[name](mutval);
      var prom = Immutable[name](mutprom);

      expect(all(prom)).to
        .to.be.fulfilled
        .and.eventually.be.an.instanceof(Immutable[name])
        .and.eventually.satisfy(function(res) { return Immutable.is(res, value) })
        .and.notify(done);
    });

    it('should work for empty immutable', function(done) {

      var empty = Immutable[name]();
      expect(all(empty)).to
        .to.be.fulfilled
        .and.eventually.be.an.instanceof(Immutable[name])
        .and.eventually.satisfy(function(res) { return Immutable.is(res, empty) })
        .and.notify(done);
    });

    it('should reject when something rejects', function(done) {
      var imm = mapLike(name) ? {a: Promise.reject('FAIL')} : [Promise.reject('FAIL')];
      expect(all(imm)).to
        .eventually.be.rejectedWith('FAIL')
        .and.notify(done);
    });
  });
});
<|endoftext|>


<commit_before>const test = require('ava')
const {getInfoFromName, getInfoFromURL, getResultsFromSearch} = require('../src')

const name = 'Sakura Trick'
const url = 'https://myanimelist.net/anime/20047/Sakura_Trick'

test('getInfoFromURL returns an error if invalid url', async t => {
  try {
    await getInfoFromURL('hello')
  } catch (e) {
    e.message.includes('Invalid Url')
      ? t.pass()
      : t.fail()
  }
})

test('getInfoFromURL returns valid information', async t => {
  try {
    const data = await getInfoFromURL(url)

    t.is(typeof data, 'object')
    t.is(data.title, name)
    t.is(data.characters.length, 10)
    t.is(data.staff.length, 4)
    t.is(data.status, 'Finished Airing')
    t.is(data.studios, 'Studio Deen')
  } catch (e) {
    t.fail()
  }
})

test('getInfoFromName returns an error if invalid name', async t => {
  try {
    await getInfoFromName()
  } catch (e) {
    e.message.includes('Invalid name')
      ? t.pass()
      : t.fail()
  }
})

test('getInfoFromName returns valid information', async t => {
  try {
    const data = await getInfoFromName(name)

    t.is(typeof data, 'object')
    t.is(data.title, name)
    t.is(data.characters.length, 10)
    t.is(data.staff.length, 4)
    t.is(data.status, 'Finished Airing')
    t.is(data.studios, 'Studio Deen')
  } catch (e) {
    t.fail()
  }
})

test('getResultsFromSearch returns an error if invalid keyword', async t => {
  try {
    await getResultsFromSearch()
  } catch (e) {
    e.message.includes('[Mal-Scraper]')
      ? t.pass()
      : t.fail()
  }
})

test('getResultsFromSearch returns a valid array', async t => {
  try {
    const data = await getResultsFromSearch(name)

    t.is(typeof data, 'object')
    t.is(data.length, 10)
    t.is(data[0].name, name)
    t.is(data[0].id, 20047)
  } catch (e) {
    t.fail()
  }
})
<commit_msg>Fixed tests<commit_after>const test = require('ava')
const {getInfoFromName, getInfoFromURL, getResultsFromSearch} = require('../src')

const name = 'Sakura Trick'
const url = 'https://myanimelist.net/anime/20047/Sakura_Trick'

test('getInfoFromURL returns an error if invalid url', async t => {
  try {
    await getInfoFromURL('hello')
  } catch (e) {
    e.message.includes('Invalid Url')
      ? t.pass()
      : t.fail()
  }
})

test('getInfoFromURL returns valid information', async t => {
  try {
    const data = await getInfoFromURL(url)

    t.is(typeof data, 'object')
    t.is(data.title, name)
    t.is(data.characters.length, 10)
    t.is(data.staff.length, 4)
    t.is(data.status, 'Finished Airing')
    t.is(data.studios[0], 'Studio Deen')
  } catch (e) {
    t.fail()
  }
})

test('getInfoFromName returns an error if invalid name', async t => {
  try {
    await getInfoFromName()
  } catch (e) {
    e.message.includes('Invalid name')
      ? t.pass()
      : t.fail()
  }
})

test('getInfoFromName returns valid information', async t => {
  try {
    const data = await getInfoFromName(name)

    t.is(typeof data, 'object')
    t.is(data.title, name)
    t.is(data.characters.length, 10)
    t.is(data.staff.length, 4)
    t.is(data.status, 'Finished Airing')
    t.is(data.studios[0], 'Studio Deen')
  } catch (e) {
    t.fail()
  }
})

test('getResultsFromSearch returns an error if invalid keyword', async t => {
  try {
    await getResultsFromSearch()
  } catch (e) {
    e.message.includes('[Mal-Scraper]')
      ? t.pass()
      : t.fail()
  }
})

test('getResultsFromSearch returns a valid array', async t => {
  try {
    const data = await getResultsFromSearch(name)

    t.is(typeof data, 'object')
    t.is(data.length, 10)
    t.is(data[0].name, name)
    t.is(data[0].id, 20047)
  } catch (e) {
    t.fail()
  }
})
<|endoftext|>


<commit_before>/* eslint-env mocha */
const { integrate } = require('../lib/integrate');
const fs = require('fs');
const expect = require('expect.js');

describe('integration', function() {

  describe('init paths', function() {
    it('should init all paths with default value', function() {
      const integration = integrate();
      expect(integration.paths.communesFilePath).to.exist;
      expect(integration.paths.codesPostauxFilePath).to.exist;
      expect(integration.paths.outputFilePath).to.exist;
    });
  });

  describe('getByCodeInsee()', function() {
    describe('set a new communes', function() {
      const integration = integrate();
      const codeInsee = '1234';
      expect(integration.communes.size).to.equal(0);
      it('should return codeInsee and store commune.', function() {
        const result = integration.getByCodeInsee(codeInsee);
        expect(result.codeInsee).to.equal(codeInsee);
        expect(result.codesPostaux).to.empty;
        expect(integration.communes.has(codeInsee)).to.true;
        expect(integration.communes.size).to.equal(1);
      });
    });

    describe('set a same commune twice', function() {
      const integration = integrate();
      const codeInsee = '1234';
      integration.getByCodeInsee(codeInsee);
      expect(integration.communes.size).to.equal(1);
      it('should return codeInsee but not store commune.', function() {
        const result = integration.getByCodeInsee(codeInsee);
        expect(result.codeInsee).to.equal(codeInsee);
        expect(result.codesPostaux).to.empty;
        expect(integration.communes.has(codeInsee)).to.true;
        expect(integration.communes.size).to.equal(1);
      });
    });
  });

  describe('loadCommunes()', function() {
    describe('undefined file path', function() {
      it('should thrown an error', function(done) {
        const options = {communesPath: ''};
        const integration = integrate(options);
        integration.loadCommunes()
          .then(function(data) {
            expect(data).to.be.undefined;
            done();
          }).catch(function(error) {
            expect(error.code).to.equal('ENOENT');
            done();
          });
      });
    });

    describe('good file path', function() {
      it('should return the number of loaded communes.', function(done) {
        const options = {communesFilePath: __dirname + '/integration-data/communes.json'};
        const integration = integrate(options);
        integration.loadCommunes()
          .then(function(data) {
            expect(data).to.equal(1);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });

  describe('loadCodePostaux()', function() {
    describe('undefined file path', function() {
      it('should thrown an error', function(done) {
        const integration = integrate();
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.be.undefined;
            done();
          }, function(error) {
            expect(error.code).to.equal('ENOENT');
            done();
          });
      });
    });

    describe('good file path', function() {
      it('should load 1 correspondances', function(done) {
        const options = { communesFilePath: __dirname + '/integration-data/communes.json',
                          codesPostauxFilePath: __dirname + '/integration-data/cp.json'};
        const integration = integrate(options);
        integration.loadCommunes();
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(1);
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('unknown codeInsee', function() {
      it('should load 0 correspondances', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/unknown-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('MARSEILLE vs MARSEILLETTE', function() {
      it('should not override MARSEILLETTE with MARSEILLE codeInsee', function(done) {
        const options = { communesFilePath: __dirname + '/integration-data/communes.json',
                          codesPostauxFilePath: __dirname + '/integration-data/cp.json'};
        const integration = integrate(options);
        integration.loadCommunes();
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(1);
            expect(integration.communes.has(11220)).to.true;
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('Exclusion', function() {
      it('should exclude Polynesia.', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/polynesie-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
      it('should exclude Monaco.', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/monaco-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });

  describe('serialize()', function() {
    describe('no communes', function() {
      const options = {outputFilePath: __dirname + '/integration-data/serialize-test.json'};
      const integration = integrate(options);
      it('should return an error', function(done) {
        integration.serialize()
        .then(function(data) {
          done(data);
        }).catch(function(error) {
          expect(error).to.equal('No communes');
          done();
        });
      });
      it('should not create file', function(done) {
        fs.stat(options.outputFilePath, function(err) {
          expect(err.code).to.equal('ENOENT');
          done();
        });
      });
    });

    describe('normal way', function() {
      const options = { outputFilePath: __dirname + '/integration-data/serialize-test.json',
                        communesFilePath: __dirname + '/integration-data/communes.json'};
      const integration = integrate(options);
      it('should return 1 and create file', function(done) {
        integration.loadCommunes()
          .then(integration.serialize)
          .then(function(data) {
            expect(data).to.equal(1);
            fs.stat(options.outputFilePath, function(err) {
              expect(err).to.be.undefined;
            });
            const result = require(options.outputFilePath);
            expect(result[0].codeInsee).to.equal('11220');
            expect(result[0].codesPostaux).to.empty;
            expect(result[0].nom).to.equal('Marseillette');
            expect(result[0].contour).to.exist;
            expect(result[0].centre).to.exist;
            expect(result[0].surface).to.equal(801);
            fs.unlink(options.outputFilePath);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });
});
<commit_msg>Fix bad file path loading test<commit_after>/* eslint-env mocha */
const { integrate } = require('../lib/integrate');
const fs = require('fs');
const expect = require('expect.js');

describe('integration', function() {

  describe('init paths', function() {
    it('should init all paths with default value', function() {
      const integration = integrate();
      expect(integration.paths.communesFilePath).to.exist;
      expect(integration.paths.codesPostauxFilePath).to.exist;
      expect(integration.paths.outputFilePath).to.exist;
    });
  });

  describe('getByCodeInsee()', function() {
    describe('set a new communes', function() {
      const integration = integrate();
      const codeInsee = '1234';
      expect(integration.communes.size).to.equal(0);
      it('should return codeInsee and store commune.', function() {
        const result = integration.getByCodeInsee(codeInsee);
        expect(result.codeInsee).to.equal(codeInsee);
        expect(result.codesPostaux).to.empty;
        expect(integration.communes.has(codeInsee)).to.true;
        expect(integration.communes.size).to.equal(1);
      });
    });

    describe('set a same commune twice', function() {
      const integration = integrate();
      const codeInsee = '1234';
      integration.getByCodeInsee(codeInsee);
      expect(integration.communes.size).to.equal(1);
      it('should return codeInsee but not store commune.', function() {
        const result = integration.getByCodeInsee(codeInsee);
        expect(result.codeInsee).to.equal(codeInsee);
        expect(result.codesPostaux).to.empty;
        expect(integration.communes.has(codeInsee)).to.true;
        expect(integration.communes.size).to.equal(1);
      });
    });
  });

  describe('loadCommunes()', function() {
    describe('bad file path', function() {
      it('should thrown an error', function(done) {
        integrate({ communesFilePath: '_' }).loadCommunes()
          .then(function(data) {
            expect(data).to.be.undefined;
            done();
          }).catch(function(error) {
            expect(error.code).to.equal('ENOENT');
            done();
          });
      });
    });

    describe('good file path', function() {
      it('should return the number of loaded communes.', function(done) {
        const options = {communesFilePath: __dirname + '/integration-data/communes.json'};
        const integration = integrate(options);
        integration.loadCommunes()
          .then(function(data) {
            expect(data).to.equal(1);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });

  describe('loadCodePostaux()', function() {
    describe('bad file path', function() {
      it('should thrown an error', function(done) {
        integrate({ codesPostauxFilePath: '_' }).loadCodePostaux()
          .then(function(data) {
            expect(data).to.be.undefined;
            done();
          }, function(error) {
            expect(error.code).to.equal('ENOENT');
            done();
          });
      });
    });

    describe('good file path', function() {
      it('should load 1 correspondances', function(done) {
        const options = { communesFilePath: __dirname + '/integration-data/communes.json',
                          codesPostauxFilePath: __dirname + '/integration-data/cp.json'};
        const integration = integrate(options);
        integration.loadCommunes();
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(1);
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('unknown codeInsee', function() {
      it('should load 0 correspondances', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/unknown-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('MARSEILLE vs MARSEILLETTE', function() {
      it('should not override MARSEILLETTE with MARSEILLE codeInsee', function(done) {
        const options = { communesFilePath: __dirname + '/integration-data/communes.json',
                          codesPostauxFilePath: __dirname + '/integration-data/cp.json'};
        const integration = integrate(options);
        integration.loadCommunes();
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(1);
            expect(integration.communes.has(11220)).to.true;
            done();
          }, function(error) {
            done(error);
          });
      });
    });

    describe('Exclusion', function() {
      it('should exclude Polynesia.', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/polynesie-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
      it('should exclude Monaco.', function(done) {
        const options = {codesPostauxFilePath: __dirname + '/integration-data/monaco-cp.json'};
        const integration = integrate(options);
        integration.loadCodePostaux()
          .then(function(data) {
            expect(data).to.equal(0);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });

  describe('serialize()', function() {
    describe('no communes', function() {
      const options = {outputFilePath: __dirname + '/integration-data/serialize-test.json'};
      const integration = integrate(options);
      it('should return an error', function(done) {
        integration.serialize()
        .then(function(data) {
          done(data);
        }).catch(function(error) {
          expect(error).to.equal('No communes');
          done();
        });
      });
      it('should not create file', function(done) {
        fs.stat(options.outputFilePath, function(err) {
          expect(err.code).to.equal('ENOENT');
          done();
        });
      });
    });

    describe('normal way', function() {
      const options = { outputFilePath: __dirname + '/integration-data/serialize-test.json',
                        communesFilePath: __dirname + '/integration-data/communes.json'};
      const integration = integrate(options);
      it('should return 1 and create file', function(done) {
        integration.loadCommunes()
          .then(integration.serialize)
          .then(function(data) {
            expect(data).to.equal(1);
            fs.stat(options.outputFilePath, function(err) {
              expect(err).to.be.undefined;
            });
            const result = require(options.outputFilePath);
            expect(result[0].codeInsee).to.equal('11220');
            expect(result[0].codesPostaux).to.empty;
            expect(result[0].nom).to.equal('Marseillette');
            expect(result[0].contour).to.exist;
            expect(result[0].centre).to.exist;
            expect(result[0].surface).to.equal(801);
            fs.unlink(options.outputFilePath);
            done();
          }).catch(function(error) {
            done(error);
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var fs = require('fs');
var format = require('util').format;
var resolve = require('path').resolve;

// number of child dirs/files to make
var CHILDREN = 5;

// TODO: if `level===undefined`, do empty

function build(parent, level) {
  // TODO: remove check? do differently?
  if (!fs.existsSync(parent))
    fs.mkdirSync(parent);

  function _build(_parent, level) {
    var child, name, path, file, message;

    for (child = CHILDREN; child > 0; child--) {
      name = format('level-%d-child-%d', level, child);
      path = resolve(_parent, name);
      file = path.concat('.txt');
      message = format('hello %s', name);

      fs.writeFileSync(file, message);

      if (level > 0) {
        fs.mkdirSync(path);
        _build(path, --level);
      }

    }
  }

  _build(parent, level);
  return; // TODO: return the contents array
}

//---- Exports

module.exports.build = build;

// TODO NEXT: test this bare builder
//            then add return array of names etc
//            then add functionality for empty level
//            or, split this last one into a sep sub-fn used by `build`

<commit_msg>Fix test/lib decrement bug<commit_after>/**
 * Module dependencies.
 */

var fs = require('fs');
var format = require('util').format;
var resolve = require('path').resolve;

// number of child dirs/files to make
var CHILDREN = 5;

// TODO: if `level===undefined`, do empty

function build(parent, level) {
  // TODO: remove check? do differently?
  if (!fs.existsSync(parent))
    fs.mkdirSync(parent);

  function _build(_parent, level) {
    var child, name, path, file, message;

    for (child = CHILDREN; child > 0; child--) {
      name = format('level-%d-child-%d', level, child);
      path = resolve(_parent, name);
      file = path.concat('.txt');
      message = format('hello %s', name);

      fs.writeFileSync(file, message);

      if (level > 0) {
        fs.mkdirSync(path);
        _build(path, level - 1);
      }

    }
  }

  _build(parent, level);
  return; // TODO: return the contents array
}

//---- Exports

module.exports.build = build;

// TODO NEXT: test this bare builder
//            then add return array of names etc
//            then add functionality for empty level
//            or, split this last one into a sep sub-fn used by `build`

<|endoftext|>