<commit_before>(function () {
    'use strict';
    var Swiper = require('swiper');
    if (typeof Swiper.default != 'undefined') {
        Swiper = Swiper.default;
    }

    /*===========================
    SwiperHandler
    ===========================*/
    var SwiperHandler = {
        window: null,
        swiperId: 1,
        swipers: {},
        initialized: false,
        initialize: function() {
            var self = this;
            $('.initSwiper').each(function() {
                var $this = $(this);
                if ($this.hasClass('initialized')) {
                    return true;
                }
                var idAttribute = 'swiperId-'+ self.swiperId;
                var selector = '#'+ idAttribute;

                $this.attr('id', idAttribute);
                SwiperHandler.swipers[self.swiperId] = {
                    selector: selector,
                    swiperSelector: selector +' .swiper-container',
                    element: $this,
                    settings: eval('(' + $this.attr('data-swiper-settings') + ')'),
                    instance: null,
                    currentBreakpoint: 0,
                    syncsWith: [],
                    allowAutoplay: true,
                    amountOfSlides: $('.swiper-slide', $this).length,
                };
                self.swiperId++;
            });

            SwiperHandler.findSyncs();

            if (SwiperHandler.initialized === false) {
                SwiperHandler.window = $(window);
                SwiperHandler.window.resize(function() {
                    clearTimeout(SwiperHandler.window.resizedFinished);
                    SwiperHandler.window.resizedFinished = setTimeout(SwiperHandler.rebuildOnResize, 250);
                });
            }

            SwiperHandler.buildAll(true);

            SwiperHandler.initialized = true;
        },
        rebuildOnResize: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                var swiper = SwiperHandler.swipers[swiperId];
                var breakpoint = SwiperHandler.getBreakpoint(swiperId);

                if (swiper.currentBreakpoint != breakpoint) {
                    SwiperHandler.build(swiperId);
                }
            });

            SwiperHandler.onAllSwipersBuilt();
        },
        buildAll: function(dontDestroy) {
            SwiperHandler._each(function(swiperId, swiper) {
                SwiperHandler.build(swiperId, dontDestroy);
            });

            SwiperHandler.onAllSwipersBuilt();
        },
        build: function(id, dontDestroy) {
            var dontDestroy = dontDestroy || false;
            var swiper = SwiperHandler.swipers[id];

            if (dontDestroy === false && swiper.instance != null) {
                SwiperHandler.destroy(id);
            }

            swiper.instance = new Swiper(swiper.swiperSelector, SwiperHandler.getSettings(id));
            SwiperHandler.pauseOnHover(id);
            swiper.element.addClass('initialized');
        },
        findSyncs () {
            SwiperHandler._each(function(swiperId, swiper) {
                var syncGroup = swiper.settings.syncGroup;
                if (syncGroup) {
                    SwiperHandler._each(function(iterationSwiperId, iterationSwiper) {
                        if (swiperId != iterationSwiperId && iterationSwiper.settings.syncGroup == syncGroup) {
                            swiper.syncsWith.push(parseInt(iterationSwiperId));
                        }
                    });
                }
            });
        },
        onAllSwipersBuilt: function() {
            SwiperHandler.syncSwipers();
            SwiperHandler.bindEvents();
        },
        syncSwipers: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                for (var i in swiper.syncsWith) {
                    var syncsWithSwiper = SwiperHandler.swipers[ swiper.syncsWith[i] ];
                    if (syncsWithSwiper.instance.controller) {
                        swiper.instance.controller.control = syncsWithSwiper.instance;
                    }
                }
            });
        },
        bindEvents () {
            SwiperHandler._each(function(swiperId, swiper) {
                swiper.instance.on('click touchEnd', function(e) {
                    SwiperHandler.toggleAutoplay(swiperId, false, true);
                    SwiperHandler.toggleAutoplayOnSynced(swiperId, false, true);
                });

                $(swiper.settings.default.navigation.prevEl +','+ swiper.settings.default.navigation.nextEl).on('click', function() {
                    SwiperHandler.toggleAutoplay(swiperId, false, true);
                    SwiperHandler.toggleAutoplayOnSynced(swiperId, false, true);
                });
            });
        },
        pauseOnHover: function(id) {
            var swiper = SwiperHandler.swipers[id];
            if ( ! swiper.settings.pauseOnHover) {
                return;
            }

            swiper.element.on('mouseover', function() {
                SwiperHandler.toggleAutoplay(id, false);
                SwiperHandler.toggleAutoplayOnSynced(id, false);
            });

            swiper.element.on('mouseleave', function() {
                if (swiper.allowAutoplay) {
                    SwiperHandler.toggleAutoplay(id, true);
                    SwiperHandler.toggleAutoplayOnSynced(id, true);
                }
            })
        },
        toggleAutoplay: function(id, play, removeAutoPlay) {
            var swiper = SwiperHandler.swipers[id];
            var play = play || false;
            var removeAutoPlay = removeAutoPlay || false;

            if (play) {
                swiper.instance.autoplay.start();
            } else {
                swiper.instance.autoplay.stop();
            }

            if (removeAutoPlay) {
                swiper.allowAutoplay = false;
            }
        },
        toggleAutoplayOnSynced (id, play, removeAutoPlay) {
            var swiper = SwiperHandler.swipers[id];
            var play = play || false;
            var removeAutoPlay = removeAutoPlay || false;

            for (var i in swiper.syncsWith) {
                var syncedSwiper = SwiperHandler.swipers[ swiper.syncsWith[i] ];

                if (play) {
                    syncedSwiper.instance.autoplay.start();
                } else {
                    syncedSwiper.instance.autoplay.stop();
                }

                if (removeAutoPlay) {
                    syncedSwiper.allowAutoplay = false;
                }
            }
        },
        getSettings: function(id) {
            var swiper = SwiperHandler.swipers[id];
            //Make sure there is a default navigation config
            var navigation = swiper.settings.default.navigation || {};
            navigation.prevEl = swiper.selector + ' ' + (navigation.prevEl || '.swiper-button-prev'),
            navigation.nextEl = swiper.selector + ' ' + (navigation.nextEl || '.swiper-button-next'),
            SwiperHandler.swipers[id].settings.default.navigation = navigation;

            var settings = swiper.settings || {};

            var breakpointSettings = {};
            swiper.currentBreakpoint = SwiperHandler.getBreakpoint(id);
            if (swiper.currentBreakpoint > 0) {
                breakpointSettings = swiper.settings.breakpoints[swiper.currentBreakpoint];
            }

            var newSettings = settings.default || {};
            newSettings = $.extend({}, newSettings, breakpointSettings);

            if (settings.centerSlidesIfTooFew && swiper.amountOfSlides < newSettings.slidesPerView) {
                newSettings.centeredSlides = true;
            }

            return newSettings;
        },
        getBreakpoint: function(id) {
            var swiper = SwiperHandler.swipers[id];

            for (var width in swiper.settings.breakpoints) {
              if (SwiperHandler.window.width() <= width) {
                return width;
              }
            }

            return 0;
        },
        destroyAll: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                SwiperHandler.destroy(swiperId);
            });
        },
        destroy: function(id) {
            if (SwiperHandler.swipers[id].instance != null) {
                SwiperHandler.swipers[id].instance.destroy(false, true);
            }
        },
        _each: function(callback) {
            if (typeof callback != 'function') {
                return false;
            }
            $.each(SwiperHandler.swipers, function(swiperId, swiper) {
                callback(swiperId, swiper);
            });
        },
    };

    window.SwiperHandler = SwiperHandler;
})();

/*===========================
SwiperHandler AMD Export
===========================*/
if (typeof(module) !== 'undefined')
{
    module.exports = window.SwiperHandler;
}
else if (typeof define === 'function' && define.amd) {
    define([], function () {
        'use strict';
        return window.SwiperHandler;
    });
}
<commit_msg>Fix console error<commit_after>(function () {
    'use strict';
    var Swiper = require('swiper');
    if (typeof Swiper.default != 'undefined') {
        Swiper = Swiper.default;
    }

    /*===========================
    SwiperHandler
    ===========================*/
    var SwiperHandler = {
        window: null,
        swiperId: 1,
        swipers: {},
        initialized: false,
        initialize: function() {
            var self = this;
            $('.initSwiper').each(function() {
                var $this = $(this);
                if ($this.hasClass('initialized')) {
                    return true;
                }
                var idAttribute = 'swiperId-'+ self.swiperId;
                var selector = '#'+ idAttribute;

                $this.attr('id', idAttribute);
                SwiperHandler.swipers[self.swiperId] = {
                    selector: selector,
                    swiperSelector: selector +' .swiper-container',
                    element: $this,
                    settings: eval('(' + $this.attr('data-swiper-settings') + ')'),
                    instance: null,
                    currentBreakpoint: 0,
                    syncsWith: [],
                    allowAutoplay: true,
                    amountOfSlides: $('.swiper-slide', $this).length,
                };
                self.swiperId++;
            });

            SwiperHandler.findSyncs();

            if (SwiperHandler.initialized === false) {
                SwiperHandler.window = $(window);
                SwiperHandler.window.resize(function() {
                    clearTimeout(SwiperHandler.window.resizedFinished);
                    SwiperHandler.window.resizedFinished = setTimeout(SwiperHandler.rebuildOnResize, 250);
                });
            }

            SwiperHandler.buildAll(true);

            SwiperHandler.initialized = true;
        },
        rebuildOnResize: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                var swiper = SwiperHandler.swipers[swiperId];
                var breakpoint = SwiperHandler.getBreakpoint(swiperId);

                if (swiper.currentBreakpoint != breakpoint) {
                    SwiperHandler.build(swiperId);
                }
            });

            SwiperHandler.onAllSwipersBuilt();
        },
        buildAll: function(dontDestroy) {
            SwiperHandler._each(function(swiperId, swiper) {
                SwiperHandler.build(swiperId, dontDestroy);
            });

            SwiperHandler.onAllSwipersBuilt();
        },
        build: function(id, dontDestroy) {
            var dontDestroy = dontDestroy || false;
            var swiper = SwiperHandler.swipers[id];

            if (dontDestroy === false && swiper.instance != null) {
                SwiperHandler.destroy(id);
            }

            swiper.instance = new Swiper(swiper.swiperSelector, SwiperHandler.getSettings(id));
            SwiperHandler.pauseOnHover(id);
            swiper.element.addClass('initialized');
        },
        findSyncs () {
            SwiperHandler._each(function(swiperId, swiper) {
                var syncGroup = swiper.settings.syncGroup;
                if (syncGroup) {
                    SwiperHandler._each(function(iterationSwiperId, iterationSwiper) {
                        if (swiperId != iterationSwiperId && iterationSwiper.settings.syncGroup == syncGroup) {
                            swiper.syncsWith.push(parseInt(iterationSwiperId));
                        }
                    });
                }
            });
        },
        onAllSwipersBuilt: function() {
            SwiperHandler.syncSwipers();
            SwiperHandler.bindEvents();
        },
        syncSwipers: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                for (var i in swiper.syncsWith) {
                    var syncsWithSwiper = SwiperHandler.swipers[ swiper.syncsWith[i] ];
                    if (syncsWithSwiper.instance.controller && swiper.instance.controller) {
                        swiper.instance.controller.control = syncsWithSwiper.instance;
                    }
                }
            });
        },
        bindEvents () {
            SwiperHandler._each(function(swiperId, swiper) {
                swiper.instance.on('click touchEnd', function(e) {
                    SwiperHandler.toggleAutoplay(swiperId, false, true);
                    SwiperHandler.toggleAutoplayOnSynced(swiperId, false, true);
                });

                $(swiper.settings.default.navigation.prevEl +','+ swiper.settings.default.navigation.nextEl).on('click', function() {
                    SwiperHandler.toggleAutoplay(swiperId, false, true);
                    SwiperHandler.toggleAutoplayOnSynced(swiperId, false, true);
                });
            });
        },
        pauseOnHover: function(id) {
            var swiper = SwiperHandler.swipers[id];
            if ( ! swiper.settings.pauseOnHover) {
                return;
            }

            swiper.element.on('mouseover', function() {
                SwiperHandler.toggleAutoplay(id, false);
                SwiperHandler.toggleAutoplayOnSynced(id, false);
            });

            swiper.element.on('mouseleave', function() {
                if (swiper.allowAutoplay) {
                    SwiperHandler.toggleAutoplay(id, true);
                    SwiperHandler.toggleAutoplayOnSynced(id, true);
                }
            })
        },
        toggleAutoplay: function(id, play, removeAutoPlay) {
            var swiper = SwiperHandler.swipers[id];
            var play = play || false;
            var removeAutoPlay = removeAutoPlay || false;

            if (play) {
                swiper.instance.autoplay.start();
            } else {
                swiper.instance.autoplay.stop();
            }

            if (removeAutoPlay) {
                swiper.allowAutoplay = false;
            }
        },
        toggleAutoplayOnSynced (id, play, removeAutoPlay) {
            var swiper = SwiperHandler.swipers[id];
            var play = play || false;
            var removeAutoPlay = removeAutoPlay || false;

            for (var i in swiper.syncsWith) {
                var syncedSwiper = SwiperHandler.swipers[ swiper.syncsWith[i] ];

                if (play) {
                    syncedSwiper.instance.autoplay.start();
                } else {
                    syncedSwiper.instance.autoplay.stop();
                }

                if (removeAutoPlay) {
                    syncedSwiper.allowAutoplay = false;
                }
            }
        },
        getSettings: function(id) {
            var swiper = SwiperHandler.swipers[id];
            //Make sure there is a default navigation config
            var navigation = swiper.settings.default.navigation || {};
            navigation.prevEl = swiper.selector + ' ' + (navigation.prevEl || '.swiper-button-prev'),
            navigation.nextEl = swiper.selector + ' ' + (navigation.nextEl || '.swiper-button-next'),
            SwiperHandler.swipers[id].settings.default.navigation = navigation;

            var settings = swiper.settings || {};

            var breakpointSettings = {};
            swiper.currentBreakpoint = SwiperHandler.getBreakpoint(id);
            if (swiper.currentBreakpoint > 0) {
                breakpointSettings = swiper.settings.breakpoints[swiper.currentBreakpoint];
            }

            var newSettings = settings.default || {};
            newSettings = $.extend({}, newSettings, breakpointSettings);

            if (settings.centerSlidesIfTooFew && swiper.amountOfSlides < newSettings.slidesPerView) {
                newSettings.centeredSlides = true;
            }

            return newSettings;
        },
        getBreakpoint: function(id) {
            var swiper = SwiperHandler.swipers[id];

            for (var width in swiper.settings.breakpoints) {
              if (SwiperHandler.window.width() <= width) {
                return width;
              }
            }

            return 0;
        },
        destroyAll: function() {
            SwiperHandler._each(function(swiperId, swiper) {
                SwiperHandler.destroy(swiperId);
            });
        },
        destroy: function(id) {
            if (SwiperHandler.swipers[id].instance != null) {
                SwiperHandler.swipers[id].instance.destroy(false, true);
            }
        },
        _each: function(callback) {
            if (typeof callback != 'function') {
                return false;
            }
            $.each(SwiperHandler.swipers, function(swiperId, swiper) {
                callback(swiperId, swiper);
            });
        },
    };

    window.SwiperHandler = SwiperHandler;
})();

/*===========================
SwiperHandler AMD Export
===========================*/
if (typeof(module) !== 'undefined')
{
    module.exports = window.SwiperHandler;
}
else if (typeof define === 'function' && define.amd) {
    define([], function () {
        'use strict';
        return window.SwiperHandler;
    });
}
<|endoftext|>


<commit_before>var assert = require("assert");
var {Parser} = require("./parser");

exports.testParser = {
    testEvaluate: function() {
        assert.strictEqual(Parser.evaluate("2 ^ x", { x: 3 }), 8);
        assert.strictEqual(Parser.evaluate("2 * x + 1", { x: 3 }), 7);
        assert.strictEqual(Parser.evaluate("2 + 3 * x", { x: 4 }), 14);
        assert.strictEqual(Parser.evaluate("(2 + 3) * x", { x: 4 }), 20);
        assert.strictEqual(Parser.evaluate("2-3^x", { x: 4 }), -79);
        assert.strictEqual(Parser.evaluate("-2-3^x", { x: 4 }), -83);
        assert.strictEqual(Parser.evaluate("-3^x", { x: 4 }), -81);
        assert.strictEqual(Parser.evaluate("(-3)^x", { x: 4 }), 81);
    },

    testSubstitute: function() {
        var expr = Parser.parse("2 * x + 1");
        var expr2 = expr.substitute("x", "4 * x"); // ((2*(4*x))+1)
        assert.strictEqual(expr2.evaluate({ x: 3}), 25);
    },

    testSimplify: function() {
        var expr = Parser.parse("x * (y * atan(1))").simplify({ y: 4 });
        assert.strictEqual(expr.toString(), '(x*3.141592653589793)');
        assert.strictEqual(expr.evaluate({ x: 2 }), 6.283185307179586);
    },

    testVariables: function() {
        var expr = Parser.parse("x * (y * atan(1))");
        assert.deepEqual(expr.variables(), ['x', 'y']);
        assert.deepEqual(expr.simplify({ y: 4 }).variables(), ['x']);
    },

    testToJSFunction: function() {
        var expr = Parser.parse("x * (y * atan(1))");
        var fn = expr.toJSFunction(['x', 'y']);
        assert.strictEqual(fn(2, 4), 6.283185307179586);
        fn = expr.toJSFunction(['y']);
        assert.throws(function() { return fn(4); });
    },

    testFunctions: function() {
        /*sin(x)
        cos(x)
        tan(x)
        asin(x)
        acos(x)
        atan(x)
        sqrt(x)
        log(x)
        abs(x)
        ceil(x)
        floor(x)
        round(x)
        exp(x)
        */
    },
};

// start the test runner if we're called directly from command line
if (require.main == module.id) {
    system.exit(require('test').run(exports));
}
<commit_msg>Old test file removed<commit_after><|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var ipaMetadataParser = require('./');

describe('should parse .ipa file', function(){
  var error;
  var output;
  beforeEach(function(done) {
    ipaMetadataParser('tests/fixtures/testApp.ipa', function(err, data) {
      error = err;
      output = data;

      done();
    });
  });

  it('error should not be set', function() {
    assert.equal(error, void 0);
  });

  it('should contain the correct data', function() {
    assert.equal(output.metadata['CFBundleDisplayName'], 'Test App');
    assert.equal(output.metadata['CFBundleIdentifier'], 'io.mts.testapp');
    assert.equal(output.metadata['CFBundleName'], 'Test App');
    assert.equal(output.metadata['CFBundleShortVersionString'], '1.0.0');
    assert.equal(output.metadata['CFBundleVersion'], '1337');
  });
});
<commit_msg>Slight codestyle clean-up in test.js<commit_after>'use strict';

var assert = require('assert');
var ipaMetadataParser = require('./');

describe('should parse .ipa file', function(){
  var error, output;

  beforeEach(function(done) {
    ipaMetadataParser('tests/fixtures/testApp.ipa', function(err, data) {
      error = err;
      output = data;

      done();
    });
  });

  it('error should not be set', function() {
    assert.equal(error, void 0);
  });

  it('should contain the correct data', function() {
    assert.equal(output.metadata['CFBundleDisplayName'], 'Test App');
    assert.equal(output.metadata['CFBundleIdentifier'], 'io.mts.testapp');
    assert.equal(output.metadata['CFBundleName'], 'Test App');
    assert.equal(output.metadata['CFBundleShortVersionString'], '1.0.0');
    assert.equal(output.metadata['CFBundleVersion'], '1337');
  });
});
<|endoftext|>


<commit_before>var fs = require("fs");
var cs = require("colorplus").enable();
var crypto = require("crypto");

var file_system_tree = function()
{
	var r =
	{
		file_list:[],
		/*
			file_name,
			full_path,
			md5,
			stat,
			tag,
		*/
		md5_map:[],
		show_scan_dir_flag:true,
		file_filter:undefined,

		clean_ary: function(target_ary, delete_value)
		{
			for (var i = 0; i < target_ary.length; i++)
			{
				if (target_ary[i] == delete_value)
				{
					target_ary.splice(i, 1);
					i--;
				}
			}
		},
		default_filter: function(full_path, file_name)
		{
			if (!file_name.match(/.mp4$/)) return true;
			else return false;
		},
		init: function()
		{
			this.file_list = [];
			this.md5_map = [];
			this.file_filter = this.default_filter;
		},
		scan_dir: function(target_dir)
		{
			this.scan_dir_unit(target_dir);
			console.log("scan_dir".green, this.file_list.length);
		},
		scan_dir_unit: function(target_dir)
		{
			if (this.show_scan_dir_flag) console.log(("scan " + target_dir).yellow);
			var tmp_list = fs.readdirSync(target_dir);
			for (var key in tmp_list)
			{
				var r = {};
				r.file_name = tmp_list[key];
				//console.log(r.file_name.red);
				r.full_path = target_dir + r.file_name;

				try
				{
					r.stat = fs.statSync(r.full_path);
				}
				catch (e)
				{
					console.log("Error".red, "in file", r.full_path);
					console.log(e);
					continue;
				}
				if (r.stat.isDirectory())
				{
					this.scan_dir_unit(r.full_path + "/");
				}
				else
				{
					if (this.file_filter !== undefined)
					{
						if (this.file_filter(r.full_path, r.file_name))
						{
							//console.log(r.file_name, "blocked by filter");
							continue;
						}
					}
					var hash = crypto.createHash('md5').update(r.full_path).digest("hex");
					console.log(hash);
					this.md5_map[hash] = this.file_list.length;
					r.md5 = hash;

					var tag_tmp = r.file_name.split(".");
					r.tag = tag_tmp[0].split(/[\[\]]+/);
					this.clean_ary(r.tag, "");
					//r.tag.PG_clean("");
					this.file_list.push(r);

				}
			}
		},
		query: function(query_in)
		{
			if (this.md5_map[query_in] !== undefined)
			{
				var at = this.md5_map[query_in];
				return this.file_list[at];
			}
			else return undefined;
		},

	}
	return r;
}

var PG = file_system_tree();
//PG.scan_dir("I:/sense/Anime/");
PG.init();
PG.scan_dir("/Users/PG/Dropbox/code/anime2/test_sample/src/");

//PG.scan_dir("");
var express = require('express');
var app = express();
var cons = require("consolidate");
app.engine("haml", cons.haml);
app.set("view engine", "haml");
app.set("views", __dirname + "/views");

app.get("/", function(req, res)
{
	console.log(req);
	res.send("Orihime (TM)");
});

app.get("/list", function(req, res)
{
	var output_buffer = "";
	for (var i = 0; i < PG.file_list.length; i++)
	{
		var file = PG.file_list[i];
		var tmp = "" + file.file_name + "
";
		output_buffer += tmp;
	}
	res.send(output_buffer);

});
app.get("/getfile/:file", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	if (query_result !== undefined)
	{
		output_buffer += "
" + query_result.stat.size + "
";
		output_buffer += "
" + query_result.stat.atime + "
";
		output_buffer += "
" + query_result.stat.mtime + "
";
		output_buffer += "
" + query_result.stat.ctime + "
";
		output_buffer += query_result.file_name + "
";
		output_buffer += query_result.full_path + "
";
		output_buffer += query_result.tag[0] + " " + query_result.tag[1] + "
";
		output_buffer += "Yes
";
		output_buffer += " Download
";
	}
	else
	{
		output_buffer += req.params["file"] + "
";
		output_buffer += "No";
	}
	res.send(output_buffer);

});

app.get("/getfile/:file/go", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	console.log(query_result);
	if (query_result !== undefined)
	{
		res.download(query_result.full_path);
	}
	else
	{
		res.send("Error");
	}

});

app.get("/haml", function(req, res)
{

	res.render("animecloud",
	{
		title:"test",
		title2:"t2",
		items:["1", "2", "3"],
		tmp123:"123123"

	});

});
app.use('/views', express.static(__dirname + '/views'));

app.listen(35101);<commit_msg>vol and name<commit_after>var fs = require("fs");
var cs = require("colorplus").enable();
var crypto = require("crypto");

var file_system_tree = function()
{
	var r =
	{
		file_list:[],
		/*
			file_name,
			full_path,
			md5,
			stat,
			tag,
			anime_name,
			anime_vol,
		*/
		md5_map:[],
		show_scan_dir_flag:true,
		file_filter:undefined,

		clean_ary: function(target_ary, delete_value)
		{
			for (var i = 0; i < target_ary.length; i++)
			{
				if (target_ary[i] == delete_value)
				{
					target_ary.splice(i, 1);
					i--;
				}
			}
		},
		default_filter: function(full_path, file_name)
		{
			if (!file_name.match(/.mp4$/)) return true;
			else return false;
		},
		init: function()
		{
			this.file_list = [];
			this.md5_map = [];
			this.file_filter = this.default_filter;
		},
		scan_dir: function(target_dir)
		{
			this.scan_dir_unit(target_dir);
			console.log("scan_dir".green, this.file_list.length);
		},
		scan_dir_unit: function(target_dir)
		{
			if (this.show_scan_dir_flag) console.log(("scan " + target_dir).yellow);
			var tmp_list = fs.readdirSync(target_dir);
			for (var key in tmp_list)
			{
				var r = {};
				r.file_name = tmp_list[key];
				//console.log(r.file_name.red);
				r.full_path = target_dir + r.file_name;

				try
				{
					r.stat = fs.statSync(r.full_path);
				}
				catch (e)
				{
					console.log("Error".red, "in file", r.full_path);
					console.log(e);
					continue;
				}
				if (r.stat.isDirectory())
				{
					this.scan_dir_unit(r.full_path + "/");
				}
				else
				{
					if (this.file_filter !== undefined)
					{
						if (this.file_filter(r.full_path, r.file_name))
						{
							//console.log(r.file_name, "blocked by filter");
							continue;
						}
					}
					var hash = crypto.createHash('md5').update(r.full_path).digest("hex");
					console.log(hash);
					this.md5_map[hash] = this.file_list.length;
					r.md5 = hash;

					var tag_tmp = r.file_name.split(".");
					r.tag = tag_tmp[0].split(/[\[\]]+/);
					this.clean_ary(r.tag, "");
					for (var i = 0; i < r.tag.length; i++)
					{
						if (r.tag[i].match(/^[0-9vend ]+$/i))
						{
							//console.log(r.file_name, r.tag[i]);
							r.anime_vol = r.tag[i];
						}
					}
					r.anime_name = r.tag[1];
					this.file_list.push(r);

					//console.log(r);

				}
			}
		},
		query: function(query_in)
		{
			if (this.md5_map[query_in] !== undefined)
			{
				var at = this.md5_map[query_in];
				return this.file_list[at];
			}
			else return undefined;
		},

	}
	return r;
}

var PG = file_system_tree();
//PG.scan_dir("I:/sense/Anime/");
PG.init();
PG.scan_dir("/Users/PG/Dropbox/code/anime2/test_sample/src/");

//PG.scan_dir("");
var express = require('express');
var app = express();
var cons = require("consolidate");
app.engine("haml", cons.haml);
app.set("view engine", "haml");
app.set("views", __dirname + "/views");

app.get("/", function(req, res)
{
	console.log(req);
	res.send("Orihime (TM)");
});

app.get("/list", function(req, res)
{
	var output_buffer = "";
	for (var i = 0; i < PG.file_list.length; i++)
	{
		var file = PG.file_list[i];
		var tmp = "" + file.file_name + "
";
		output_buffer += tmp;
	}
	res.send(output_buffer);

});
app.get("/getfile/:file", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	if (query_result !== undefined)
	{
		output_buffer += "
" + query_result.stat.size + "
";
		output_buffer += "
" + query_result.stat.atime + "
";
		output_buffer += "
" + query_result.stat.mtime + "
";
		output_buffer += "
" + query_result.stat.ctime + "
";
		output_buffer += query_result.file_name + "
";
		output_buffer += query_result.full_path + "
";
		output_buffer += query_result.tag[0] + " " + query_result.tag[1] + "
";
		output_buffer += "Yes
";
		output_buffer += " Download
";
	}
	else
	{
		output_buffer += req.params["file"] + "
";
		output_buffer += "No";
	}
	res.send(output_buffer);

});

app.get("/getfile/:file/go", function(req, res)
{

	var output_buffer = "";
	var query_result = PG.query(req.params["file"]);
	console.log(query_result);
	if (query_result !== undefined)
	{
		res.download(query_result.full_path);
	}
	else
	{
		res.send("Error");
	}

});

app.get("/haml", function(req, res)
{

	res.render("animecloud",
	{
		title:"test",
		title2:"t2",
		items:["1", "2", "3"],
		tmp123:"123123"

	});

});
app.use('/views', express.static(__dirname + '/views'));

app.listen(35101);<|endoftext|>


<commit_before>'use strict';

var should = require('should');

var LegoFilter = require('./lib/lego-filter');
var LegoTransform = require('./lib/lego-transform');
var LegoContainer = require('./lib/lego-container');

describe('filter', function() {
  it('should allow matching pieces of data', function(done) {
    var filter = new LegoFilter({foo:/^(?:bar|baz)/});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'bar');
      done();
    });
    filter.input({foo:'bar'});
  });

  it('should not allow non-matching pieces of data', function(done) {
    var filter = new LegoFilter({foo:function(v){return false;}});
    filter.on('data', function(v) {
      done('Nope!');
    });

    filter.input({foo:1234});
    setTimeout(done, 20);
  });
});

describe('transform', function() {
  it('should transform simple values', function(done) {
    var filter = new LegoTransform({foo:3});
    filter.on('data', function(v) {
      v.should.have.property('foo', 3);
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should transform regex values', function(done) {
    var filter = new LegoTransform({foo:[/^b/, 'm']});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'mar');
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should ignore invalid transforms', function(done) {
    var filter = new LegoTransform({qux:[/^b/, 'm']});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'bar');
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should allow basic functional transforms', function(done) {
    var filter = new LegoTransform(function() { return "changed"; });
    filter.on('data', function(v) {
      v.should.equal("changed");
      done();
    });
    filter.input({foo:'bar'});
  });
});

describe('snapping', function() {
  it('should snap and transform + filter', function(done) {
    var transformer = new LegoTransform(function(v) { return v * 2; });
    var filter = new LegoFilter(function(v) { return v < 10; });
    var sum = 0;

    transformer.snap(filter);
    filter.on('data', function(v) {
      sum += v;
    });

    for (var i = 0; i < 100; i++) {
      transformer.input(i);
    }

    setTimeout(function() {
      sum.should.equal(20);
      done();
    }, 20);
  });
});

describe('container', function() {
  it('should push and transform + filter', function(done) {
    var container = new LegoContainer();
    var transformer = new LegoTransform(function(v) { return v * 2; });
    var filter = new LegoFilter(function(v) { return v < 10; });
    var sum = 0;

    container.push(transformer, filter);

    container.on('data', function(v) {
      sum += v;
    });

    for (var i = 0; i < 100; i++) {
      container.input(i);
    }

    setTimeout(function() {
      sum.should.equal(20);
      done();
    }, 20);
  });
});
<commit_msg>broke out push into two separate calls<commit_after>'use strict';

var should = require('should');

var LegoFilter = require('./lib/lego-filter');
var LegoTransform = require('./lib/lego-transform');
var LegoContainer = require('./lib/lego-container');

describe('filter', function() {
  it('should allow matching pieces of data', function(done) {
    var filter = new LegoFilter({foo:/^(?:bar|baz)/});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'bar');
      done();
    });
    filter.input({foo:'bar'});
  });

  it('should not allow non-matching pieces of data', function(done) {
    var filter = new LegoFilter({foo:function(v){return false;}});
    filter.on('data', function(v) {
      done('Nope!');
    });

    filter.input({foo:1234});
    setTimeout(done, 20);
  });
});

describe('transform', function() {
  it('should transform simple values', function(done) {
    var filter = new LegoTransform({foo:3});
    filter.on('data', function(v) {
      v.should.have.property('foo', 3);
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should transform regex values', function(done) {
    var filter = new LegoTransform({foo:[/^b/, 'm']});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'mar');
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should ignore invalid transforms', function(done) {
    var filter = new LegoTransform({qux:[/^b/, 'm']});
    filter.on('data', function(v) {
      v.should.have.property('foo', 'bar');
      done();
    });
    filter.input({foo:'bar'});
  });
  it('should allow basic functional transforms', function(done) {
    var filter = new LegoTransform(function() { return "changed"; });
    filter.on('data', function(v) {
      v.should.equal("changed");
      done();
    });
    filter.input({foo:'bar'});
  });
});

describe('snapping', function() {
  it('should snap and transform + filter', function(done) {
    var transformer = new LegoTransform(function(v) { return v * 2; });
    var filter = new LegoFilter(function(v) { return v < 10; });
    var sum = 0;

    transformer.snap(filter);
    filter.on('data', function(v) {
      sum += v;
    });

    for (var i = 0; i < 100; i++) {
      transformer.input(i);
    }

    setTimeout(function() {
      sum.should.equal(20);
      done();
    }, 20);
  });
});

describe('container', function() {
  it('should push and transform + filter', function(done) {
    var container = new LegoContainer();
    var transformer = new LegoTransform(function(v) { return v * 2; });
    var filter = new LegoFilter(function(v) { return v < 10; });
    var sum = 0;

    container.push(transformer);
    container.push(filter);

    container.on('data', function(v) {
      sum += v;
    });

    for (var i = 0; i < 100; i++) {
      container.input(i);
    }

    setTimeout(function() {
      sum.should.equal(20);
      done();
    }, 20);
  });
});
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
/* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */

var pdfDocument, canvas, pageDisplay, pageNum;
function load() {
    canvas = document.getElementById("canvas");
    canvas.mozOpaque = true;
    pageNum = parseInt(queryParams().page) || 1;
    fileName = queryParams().file || "compressed.tracemonkey-pldi-09.pdf";
    open(fileName);
}

function queryParams() {
    var qs = window.location.search.substring(1);
    var kvs = qs.split("&");
    var params = { };
    for (var i = 0; i < kvs.length; ++i) {
        var kv = kvs[i].split("=");
        params[unescape(kv[0])] = unescape(kv[1]);
    }
    return params;
}

function open(url) {
    document.title = url;
    req = new XMLHttpRequest();
    req.open("GET", url);
    req.mozResponseType = req.responseType = "arraybuffer";
    req.expected = (document.URL.indexOf("file:") == 0) ? 0 : 200;
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == req.expected) {
        var data = req.mozResponseArrayBuffer || req.mozResponse ||
                   req.responseArrayBuffer || req.response;
        pdfDocument = new PDFDoc(new Stream(data));
        numPages = pdfDocument.numPages;
        document.getElementById("numPages").innerHTML = numPages.toString();
        goToPage(pageNum);
      }
    };
    req.send(null);
}

function gotoPage(num) {
    if (0 <= num && num <= numPages)
        pageNum = num;
    displayPage(pageNum);
}

function displayPage(num) {
    document.getElementById("pageNumber").value = num;

    var t0 = Date.now();

    var page = pdfDocument.getPage(pageNum = num);

    function display() {
      var t1 = Date.now();
      var ctx = canvas.getContext("2d");
      ctx.save();
      ctx.fillStyle = "rgb(255, 255, 255)";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.restore();

      var gfx = new CanvasGraphics(ctx);
      page.display(gfx);

      var t2 = Date.now();
      var infoDisplay = document.getElementById("info");
      infoDisplay.innerHTML = "Time to render: "+ (t1 - t0) + "/" + (t2 - t1) + " ms";
    }

    // Loading a font via data uri is asynchronous, so wait for all font
    // of the page to be fully loaded before loading the page
    var fontsReady = true;
    var fonts = page.fonts;
    for (var i = 0; i < fonts.length; i++) {
      var fontName = fonts[i].replace("+", "_");
      var font = Fonts[fontName];
      if (!font) {
        // load the new font
        var xref = page.xref;
        var resources = xref.fetchIfRef(page.resources);
        var fontResource = resources.get("Font");
        for (var id in fontResource.map) {
          var res = xref.fetch(fontResource.get(id));
          var descriptor = xref.fetch(res.get("FontDescriptor"));
          var name = descriptor.get("FontName").toString();
          if (name == fontName.replace("_", "+")) {
            var subtype = res.get("Subtype").name;
            var fontFile = page.xref.fetchIfRef(descriptor.get("FontFile"));
            if (!fontFile)
              fontFile = page.xref.fetchIfRef(descriptor.get("FontFile2"));
            new Font(fontName, fontFile, subtype);
            fontsReady = false;
            break;
          }
        }
      } else if (font.loading) {
        fontsReady = false;
        break;
      }
    }

    // If everything is ready do not delayed the page loading any more
    if (fontsReady)
      display();
    else
      setTimeout(displayPage, 150, num);
}

function nextPage() {
    if (pageNum < pdfDocument.numPages)
      displayPage(++pageNum);
}

function prevPage() {
    if (pageNum > 1)
      displayPage(--pageNum);
}

function goToPage(num) {
  if (0 <= num && num <= numPages)
    displayPage(pageNum = num);
}

<commit_msg>Fix an issue with the setTimeout method used for waiting for fonts to load<commit_after>/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
/* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */

var pdfDocument, canvas, pageDisplay, pageNum, pageTimeout;
function load() {
    canvas = document.getElementById("canvas");
    canvas.mozOpaque = true;
    pageNum = parseInt(queryParams().page) || 1;
    fileName = queryParams().file || "compressed.tracemonkey-pldi-09.pdf";
    open(fileName);
}

function queryParams() {
    var qs = window.location.search.substring(1);
    var kvs = qs.split("&");
    var params = { };
    for (var i = 0; i < kvs.length; ++i) {
        var kv = kvs[i].split("=");
        params[unescape(kv[0])] = unescape(kv[1]);
    }
    return params;
}

function open(url) {
    document.title = url;
    req = new XMLHttpRequest();
    req.open("GET", url);
    req.mozResponseType = req.responseType = "arraybuffer";
    req.expected = (document.URL.indexOf("file:") == 0) ? 0 : 200;
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == req.expected) {
        var data = req.mozResponseArrayBuffer || req.mozResponse ||
                   req.responseArrayBuffer || req.response;
        pdfDocument = new PDFDoc(new Stream(data));
        numPages = pdfDocument.numPages;
        document.getElementById("numPages").innerHTML = numPages.toString();
        goToPage(pageNum);
      }
    };
    req.send(null);
}

function gotoPage(num) {
    if (0 <= num && num <= numPages)
        pageNum = num;
    displayPage(pageNum);
}

function displayPage(num) {
    if (pageNum != num)
      window.clearTimeout(pageTimeout);

    document.getElementById("pageNumber").value = num;

    var t0 = Date.now();

    var page = pdfDocument.getPage(pageNum = num);

    function display() {
      var t1 = Date.now();
      var ctx = canvas.getContext("2d");
      ctx.save();
      ctx.fillStyle = "rgb(255, 255, 255)";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.restore();

      var gfx = new CanvasGraphics(ctx);
      page.display(gfx);

      var t2 = Date.now();
      var infoDisplay = document.getElementById("info");
      infoDisplay.innerHTML = "Time to render: "+ (t1 - t0) + "/" + (t2 - t1) + " ms";
    }

    // Loading a font via data uri is asynchronous, so wait for all font
    // of the page to be fully loaded before loading the page
    var fontsReady = true;
    var fonts = page.fonts;
    for (var i = 0; i < fonts.length; i++) {
      var fontName = fonts[i].replace("+", "_");
      var font = Fonts[fontName];
      if (!font) {
        // load the new font
        var xref = page.xref;
        var resources = xref.fetchIfRef(page.resources);
        var fontResource = resources.get("Font");
        for (var id in fontResource.map) {
          var res = xref.fetch(fontResource.get(id));
          var descriptor = xref.fetch(res.get("FontDescriptor"));
          var name = descriptor.get("FontName").toString();
          if (name == fontName.replace("_", "+")) {
            var subtype = res.get("Subtype").name;
            var fontFile = page.xref.fetchIfRef(descriptor.get("FontFile"));
            if (!fontFile)
              fontFile = page.xref.fetchIfRef(descriptor.get("FontFile2"));
            new Font(fontName, fontFile, subtype);
            fontsReady = false;
            break;
          }
        }
      } else if (font.loading) {
        fontsReady = false;
        break;
      }
    }

    // If everything is ready do not delayed the page loading any more
    if (fontsReady)
      display();
    else {
      // FIXME Relying on an event seems much more cleaner here instead
      // of a setTimeout...
      pageTimeout = window.setTimeout(displayPage, 150, num);
    }
}

function nextPage() {
    if (pageNum < pdfDocument.numPages)
      displayPage(++pageNum);
}

function prevPage() {
    if (pageNum > 1)
      displayPage(--pageNum);
}

function goToPage(num) {
  if (0 <= num && num <= numPages)
    displayPage(pageNum = num);
}

<|endoftext|>


<commit_before>'use strict';

require('mocha');
var assert = require('assert');
var assign = require('./');

describe('assign', function() {
  it('should deeply assign properties of objects to the first object:', function() {
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'e', f: 'g', j: 'i'}}});
  });

  it('should extend properties onto a function:', function() {
    function target() {}
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: 'e', f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions:', function() {
    var fn = function() {};
    var target = {};
    var one = {b: {c: {d: fn}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: fn, f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions with properties:', function() {
    var fn = function() {};
    fn.foo = 'foo';
    fn.bar = 'bar';

    var target = {};
    var one = {b: {c: {d: fn}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: fn, f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions with nested properties:', function() {
    var fn = function() {};
    fn.foo = {y: 'y'};
    fn.bar = {z: 'z'};

    var target = {};
    var one = {a: {fn: fn}};
    var two = {b: {fn: fn}};
    two.b.fn.foo.w = 'w';
    two.b.fn.bar.x = 'x';

    assert.deepEqual(assign(target, one, two).a.fn, {
      foo: {y: 'y', w: 'w' },
      bar: { z: 'z', x: 'x' }
    });
  });

  it('should extend properties from functions to functions:', function() {
    function target() {}
    function one() {}
    function two() {}
    one.b = {c: {d: 'e'}};
    two.b = {c: {f: 'g', j: 'i'}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: 'e', f: 'g', j: 'i'}});
  });

  it('should update a value when a duplicate is assigned:', function() {
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {d: 'f'}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'f'}}});
  });

  it('should not loop over arrays:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: {c: {d: 'f', g: ['a']}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'f', g: ['a']}}});
  });

  it('should deeply assign values from multiple objects:', function() {
    var foo = {};
    var bar = {a: 'b'};
    var baz = {c: 'd', g: {h: 'i'}};
    var quux = {e: 'f', g: {j: 'k'}};

    assign(foo, bar, baz, quux);
    assert.deepEqual(foo, {a: 'b', c: 'd', e: 'f', g: {h: 'i', j: 'k'}});
  });

  it('should not assign primitive arguments:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = 5;
    assert.deepEqual(assign(one, two), one);
  });

  it('should assign primitive values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: 5};
    assert.deepEqual(assign(one, two), {b: 5});
  });

  it('should assign over primitive values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: 5};
    var three = {b: function() {}};
    three.b.foo = 'bar';
    assert.deepEqual(assign(one, two, three), three);
  });

  it('should assign null values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: null, c: null};
    assert.deepEqual(assign(one, two), {b: null, c: null});
  });

  it('should assign undefined values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: undefined};
    assert.deepEqual(assign(one, two), {b: undefined});
  });

  it('should assign properties to a function:', function() {
    function one() {}
    one.a = 'b';
    one.c = 'd';

    var two = {e: 'f', g: ['h']};
    assign(one, two);
    assert.deepEqual(one.g, ['h']);
    assert.equal(one.g, two.g);
    assert.equal(typeof one, 'function');
  });

  it('should assign properties from a function:', function() {
    function one() {}
    one.a = 'b';
    one.c = 'd';

    var two = {e: 'f', g: ['h']};
    assign(two, one);
    assert.deepEqual(two.g, ['h']);
    assert.equal(two.g, two.g);
    assert.equal(typeof two, 'object');
  });

  it('should deeply mix the properties of object into the first object.', function() {
    var a = assign({a: {aa: 'aa'} }, {a: {bb: 'bb'} }, {a: {cc: 'cc'} });
    assert.deepEqual(a, {a: {aa: 'aa', bb: 'bb', cc: 'cc'} });

    var b = assign({a: {aa: 'aa', dd: {ee: 'ff'} } }, {a: {bb: 'bb', dd: {gg: 'hh'} } }, {a: {cc: 'cc', dd: {ii: 'jj'} } });
    assert.deepEqual(b, {a: {aa: 'aa', dd: {ee: 'ff', gg: 'hh', ii: 'jj'}, bb: 'bb', cc: 'cc'} });
  });

  it('should merge object properties without affecting any object', function() {
    var obj1 = {a: 0, b: 1};
    var obj2 = {c: 2, d: 3};
    var obj3 = {a: 4, d: 5};

    var actual = {a: 4, b: 1, c: 2, d: 5 };

    assert.deepEqual(assign({}, obj1, obj2, obj3), actual);
    assert.notDeepEqual(actual, obj1);
    assert.notDeepEqual(actual, obj2);
    assert.notDeepEqual(actual, obj3);
  });

  it('should do a deep merge', function() {
    var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}};
    var obj2 = {a: {b: 2, d: {f: 'f'}}};

    assert.deepEqual(assign(obj1, obj2), {a: {b: 2, c: 1, d: {e: 1, f: 'f'} }});
  });

  it('should use the last value defined', function() {
    var obj1 = {a: 'b'};
    var obj2 = {a: 'c'};

    assert.deepEqual(assign(obj1, obj2), {a: 'c'});
  });

  it('should use the last value defined on nested object', function() {
    var obj1 = {a: 'b', c: {d: 'e'}};
    var obj2 = {a: 'c', c: {d: 'f'}};

    assert.deepEqual(assign(obj1, obj2), {a: 'c', c: {d: 'f'}});
  });

  it('should shallow clone when an empty object is passed', function() {
    var obj1 = {a: 'b', c: {d: 'e'}};
    var obj2 = {a: 'c', c: {d: 'f'}};

    var res = assign({}, obj1, obj2);
    assert.deepEqual(res, {a: 'c', c: {d: 'f'}});
  });

  it('should merge additional objects into the first:', function() {
    var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}};
    var obj2 = {a: {b: 2, d: {f: 'f'} }};

    assign(obj1, obj2);
    assert.deepEqual(obj1, {a: {b: 2, c: 1, d: {e: 1, f: 'f'} }});
  });

  it('should clone objects during merge', function() {
    var obj1 = {a: {b: 1}};
    var obj2 = {a: {c: 2}};

    var target = assign({}, obj1, obj2);
    assert.deepEqual(target, {a: {b: 1, c: 2}});
    assert.deepEqual(target.a, {b: 1, c: 2});
  });

  it('should deep clone arrays during merge', function() {
    var obj1 = {a: [1, 2, [3, 4]]};
    var obj2 = {b: [5, 6]};

    var actual = assign(obj1, obj2);
    assert.deepEqual(actual.a, [1, 2, [3, 4]]);
    assert.deepEqual(actual.a[2], [3, 4]);
    assert.deepEqual(actual.b, obj2.b);
  });

  it('should copy source properties', function() {
    assert(assign({ test: true }).test, true);
  });

  it('should not deep clone arrays', function() {
    assert.deepEqual(assign([1, 2, 3]), [1, 2, 3]);
    assert.deepEqual(assign([1, 2, 3], {}), [1, 2, 3]);
  });

  it('should work with sparse objects:', function() {
    var actual = assign({}, undefined, {a: 'b'}, undefined, {c: 'd'});
    assert.deepEqual(actual, {a: 'b', c: 'd'});
  });

  it('should clone RegExps', function() {
    var fixture = /test/g;
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });

  it('should clone Dates', function() {
    var fixture = new Date();
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });

  it('should not clone objects created with custom constructor', function() {
    function TestType() { }
    var fixture = new TestType();
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });
});

describe('symbols', function() {
  it('should return the first object when one argument is passed:', function() {
    assert.deepEqual(assign({a: 'b'}), {a: 'b'});
  });

  if (typeof Symbol !== 'undefined') {
    it('should assign symbol properties from an object to the receiver', function() {
      var a = {};
      var b = {};
      var key = Symbol('abc');
      b[key] = 'xyz';
      assign(a, b);
      assert.equal(a[key], 'xyz');
    });

    it('should deeply assign symbol properties', function() {
      var a = {c: {e: {f: {}}}};
      var b = {c: {e: {g: {}}}};
      var foo = Symbol('foo');
      var bar = Symbol('bar');
      a.c.e.f[foo] = 'xyz';
      b.c.e.g[bar] = 'xyz';
      assign(a, b);
      assert.equal(a.c.e.f[foo], 'xyz');
      assert.equal(a.c.e.g[bar], 'xyz');
    });

    it('should assign symbol properties from each object to the receiver', function() {
      var target = {};
      var a = {};
      var aa = Symbol('aa');
      a[aa] = 'aa';

      var b = {};
      var bb = Symbol('bb');
      b[bb] = 'bb';

      var c = {};
      var cc = Symbol('cc');
      c[cc] = 'cc';

      assign(target, a, b, c);
      assert.equal(target[aa], 'aa');
      assert.equal(target[bb], 'bb');
      assert.equal(target[cc], 'cc');
    });

    it('should not assign non-enumerable symbols', function() {
      var a = {};
      var key = Symbol('abc');
      function App() {}
      App.prototype[key] = 'xyz';
      var app = new App();
      assign(a, app);
      assert.equal(typeof a[key], 'undefined');
    });

    it('should return the receiver object', function() {
      var a = {};
      var b = {};
      var key = Symbol('abc');
      b[key] = 'xyz';
      var res = assign(a, b);
      assert.equal(res[key], 'xyz');
    });
  }
});
<commit_msg>ensure different function instances are used in tests<commit_after>'use strict';

require('mocha');
var assert = require('assert');
var assign = require('./');

describe('assign', function() {
  it('should deeply assign properties of objects to the first object:', function() {
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'e', f: 'g', j: 'i'}}});
  });

  it('should extend properties onto a function:', function() {
    function target() {}
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: 'e', f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions:', function() {
    var fn = function() {};
    var target = {};
    var one = {b: {c: {d: fn}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: fn, f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions with properties:', function() {
    var fn = function() {};
    fn.foo = 'foo';
    fn.bar = 'bar';

    var target = {};
    var one = {b: {c: {d: fn}}};
    var two = {b: {c: {f: 'g', j: 'i'}}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: fn, f: 'g', j: 'i'}});
  });

  it('should extend deeply nested functions with nested properties:', function() {
    var fnOne = function() {};
    fnOne.foo = {y: 'y'};
    fnOne.bar = {z: 'z'};

    var fnTwo = function() {};
    fnTwo.foo = {w: 'w'};
    fnTwo.bar = {x: 'x'};

    var target = {};
    var one = {a: {fn: fnOne}};
    var two = {a: {fn: fnTwo}};

    assert.deepEqual(assign(target, one, two).a.fn, {
      foo: {y: 'y', w: 'w' },
      bar: { z: 'z', x: 'x' }
    });
  });

  it('should extend properties from functions to functions:', function() {
    function target() {}
    function one() {}
    function two() {}
    one.b = {c: {d: 'e'}};
    two.b = {c: {f: 'g', j: 'i'}};
    assign(target, one, two);
    assert.deepEqual(target.b, {c: {d: 'e', f: 'g', j: 'i'}});
  });

  it('should update a value when a duplicate is assigned:', function() {
    var one = {b: {c: {d: 'e'}}};
    var two = {b: {c: {d: 'f'}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'f'}}});
  });

  it('should not loop over arrays:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: {c: {d: 'f', g: ['a']}}};
    assert.deepEqual(assign(one, two), {b: {c: {d: 'f', g: ['a']}}});
  });

  it('should deeply assign values from multiple objects:', function() {
    var foo = {};
    var bar = {a: 'b'};
    var baz = {c: 'd', g: {h: 'i'}};
    var quux = {e: 'f', g: {j: 'k'}};

    assign(foo, bar, baz, quux);
    assert.deepEqual(foo, {a: 'b', c: 'd', e: 'f', g: {h: 'i', j: 'k'}});
  });

  it('should not assign primitive arguments:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = 5;
    assert.deepEqual(assign(one, two), one);
  });

  it('should assign primitive values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: 5};
    assert.deepEqual(assign(one, two), {b: 5});
  });

  it('should assign over primitive values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: 5};
    var three = {b: function() {}};
    three.b.foo = 'bar';
    assert.deepEqual(assign(one, two, three), three);
  });

  it('should assign null values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: null, c: null};
    assert.deepEqual(assign(one, two), {b: null, c: null});
  });

  it('should assign undefined values:', function() {
    var one = {b: {c: {d: 'e', g: ['b']}}};
    var two = {b: undefined};
    assert.deepEqual(assign(one, two), {b: undefined});
  });

  it('should assign properties to a function:', function() {
    function one() {}
    one.a = 'b';
    one.c = 'd';

    var two = {e: 'f', g: ['h']};
    assign(one, two);
    assert.deepEqual(one.g, ['h']);
    assert.equal(one.g, two.g);
    assert.equal(typeof one, 'function');
  });

  it('should assign properties from a function:', function() {
    function one() {}
    one.a = 'b';
    one.c = 'd';

    var two = {e: 'f', g: ['h']};
    assign(two, one);
    assert.deepEqual(two.g, ['h']);
    assert.equal(two.g, two.g);
    assert.equal(typeof two, 'object');
  });

  it('should deeply mix the properties of object into the first object.', function() {
    var a = assign({a: {aa: 'aa'} }, {a: {bb: 'bb'} }, {a: {cc: 'cc'} });
    assert.deepEqual(a, {a: {aa: 'aa', bb: 'bb', cc: 'cc'} });

    var b = assign({a: {aa: 'aa', dd: {ee: 'ff'} } }, {a: {bb: 'bb', dd: {gg: 'hh'} } }, {a: {cc: 'cc', dd: {ii: 'jj'} } });
    assert.deepEqual(b, {a: {aa: 'aa', dd: {ee: 'ff', gg: 'hh', ii: 'jj'}, bb: 'bb', cc: 'cc'} });
  });

  it('should merge object properties without affecting any object', function() {
    var obj1 = {a: 0, b: 1};
    var obj2 = {c: 2, d: 3};
    var obj3 = {a: 4, d: 5};

    var actual = {a: 4, b: 1, c: 2, d: 5 };

    assert.deepEqual(assign({}, obj1, obj2, obj3), actual);
    assert.notDeepEqual(actual, obj1);
    assert.notDeepEqual(actual, obj2);
    assert.notDeepEqual(actual, obj3);
  });

  it('should do a deep merge', function() {
    var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}};
    var obj2 = {a: {b: 2, d: {f: 'f'}}};

    assert.deepEqual(assign(obj1, obj2), {a: {b: 2, c: 1, d: {e: 1, f: 'f'} }});
  });

  it('should use the last value defined', function() {
    var obj1 = {a: 'b'};
    var obj2 = {a: 'c'};

    assert.deepEqual(assign(obj1, obj2), {a: 'c'});
  });

  it('should use the last value defined on nested object', function() {
    var obj1 = {a: 'b', c: {d: 'e'}};
    var obj2 = {a: 'c', c: {d: 'f'}};

    assert.deepEqual(assign(obj1, obj2), {a: 'c', c: {d: 'f'}});
  });

  it('should shallow clone when an empty object is passed', function() {
    var obj1 = {a: 'b', c: {d: 'e'}};
    var obj2 = {a: 'c', c: {d: 'f'}};

    var res = assign({}, obj1, obj2);
    assert.deepEqual(res, {a: 'c', c: {d: 'f'}});
  });

  it('should merge additional objects into the first:', function() {
    var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}};
    var obj2 = {a: {b: 2, d: {f: 'f'} }};

    assign(obj1, obj2);
    assert.deepEqual(obj1, {a: {b: 2, c: 1, d: {e: 1, f: 'f'} }});
  });

  it('should clone objects during merge', function() {
    var obj1 = {a: {b: 1}};
    var obj2 = {a: {c: 2}};

    var target = assign({}, obj1, obj2);
    assert.deepEqual(target, {a: {b: 1, c: 2}});
    assert.deepEqual(target.a, {b: 1, c: 2});
  });

  it('should deep clone arrays during merge', function() {
    var obj1 = {a: [1, 2, [3, 4]]};
    var obj2 = {b: [5, 6]};

    var actual = assign(obj1, obj2);
    assert.deepEqual(actual.a, [1, 2, [3, 4]]);
    assert.deepEqual(actual.a[2], [3, 4]);
    assert.deepEqual(actual.b, obj2.b);
  });

  it('should copy source properties', function() {
    assert(assign({ test: true }).test, true);
  });

  it('should not deep clone arrays', function() {
    assert.deepEqual(assign([1, 2, 3]), [1, 2, 3]);
    assert.deepEqual(assign([1, 2, 3], {}), [1, 2, 3]);
  });

  it('should work with sparse objects:', function() {
    var actual = assign({}, undefined, {a: 'b'}, undefined, {c: 'd'});
    assert.deepEqual(actual, {a: 'b', c: 'd'});
  });

  it('should clone RegExps', function() {
    var fixture = /test/g;
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });

  it('should clone Dates', function() {
    var fixture = new Date();
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });

  it('should not clone objects created with custom constructor', function() {
    function TestType() { }
    var fixture = new TestType();
    var actual = assign(fixture);
    assert.deepEqual(actual, fixture);
  });
});

describe('symbols', function() {
  it('should return the first object when one argument is passed:', function() {
    assert.deepEqual(assign({a: 'b'}), {a: 'b'});
  });

  if (typeof Symbol !== 'undefined') {
    it('should assign symbol properties from an object to the receiver', function() {
      var a = {};
      var b = {};
      var key = Symbol('abc');
      b[key] = 'xyz';
      assign(a, b);
      assert.equal(a[key], 'xyz');
    });

    it('should deeply assign symbol properties', function() {
      var a = {c: {e: {f: {}}}};
      var b = {c: {e: {g: {}}}};
      var foo = Symbol('foo');
      var bar = Symbol('bar');
      a.c.e.f[foo] = 'xyz';
      b.c.e.g[bar] = 'xyz';
      assign(a, b);
      assert.equal(a.c.e.f[foo], 'xyz');
      assert.equal(a.c.e.g[bar], 'xyz');
    });

    it('should assign symbol properties from each object to the receiver', function() {
      var target = {};
      var a = {};
      var aa = Symbol('aa');
      a[aa] = 'aa';

      var b = {};
      var bb = Symbol('bb');
      b[bb] = 'bb';

      var c = {};
      var cc = Symbol('cc');
      c[cc] = 'cc';

      assign(target, a, b, c);
      assert.equal(target[aa], 'aa');
      assert.equal(target[bb], 'bb');
      assert.equal(target[cc], 'cc');
    });

    it('should not assign non-enumerable symbols', function() {
      var a = {};
      var key = Symbol('abc');
      function App() {}
      App.prototype[key] = 'xyz';
      var app = new App();
      assign(a, app);
      assert.equal(typeof a[key], 'undefined');
    });

    it('should return the receiver object', function() {
      var a = {};
      var b = {};
      var key = Symbol('abc');
      b[key] = 'xyz';
      var res = assign(a, b);
      assert.equal(res[key], 'xyz');
    });
  }
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-6-9 17:47:49<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict';
var DefaultStack = require('./src/template/stacks/default');
var htmlparser = require('htmlparser2');
var hogan = require('hogan-express/node_modules/hogan.js/lib/compiler');
var template = '{{! test }}
 {{#test}}faffce{{/test}}  {{^test}}book{{/test}}
';

var _stateBeforeAttributeName = htmlparser.Tokenizer.prototype._stateBeforeAttributeName;
htmlparser.Tokenizer.prototype._stateBeforeAttributeName = function(c) {
  if (c === '{') {
    var curlyCounter = 1;
    this._sectionStart = this._index;
    while (curlyCounter !== 0) {
      this._index += 1;
      c = this._buffer.charAt(this._index);
      if (c === '{') {
        curlyCounter += 1;
      } else if (c === '}') {
        curlyCounter -= 1;
      }
    }
    this._index += 1;
    c = this._buffer.charAt(this._index);
    var section = this._getSection();
    if (section.substr(0, 3) === '{{#') {
      this._dynamicAttributeDepth += 1;
    }
    if (section.substr(0, 3) === '{{/') {
      this._dynamicAttributeDepth -= 1;
    }
    this._dynamicAttributes.push(section);

    this._stateBeforeAttributeName(c);
  } else {
    _stateBeforeAttributeName.call(this, c);
  }
};

function processMustacheTokens(tokens) {
  // process token array into stack calls?
  return tokens;
}

function processMustacheString(str, parse) {
  var tokens = hogan.scan(str);
  return tokens;
}

var types = {
  INTERPOLATOR: 2,
  TRIPLE: 3,
  SECTION: 4,
  INVERTED: 5,
  ELEMENT: 7,
  PARTIAL: 8,
  COMMENT: 9
};

function processHoganObject(token) {
  if (Array.isArray(token)) {
    for (var i = 0; i < token.length; i++) {
      token[i] = processHoganObject(token[i]);
    }
    return token;
  }

  switch (token.tag) {
    case '#':
      return {
        type: types.SECTION,
        value: token.n,
        children: processHoganObject(token.nodes)
      };
    case '^':
      return {
        type: types.INVERTED,
        value: token.n,
        children: processHoganObject(token.nodes)
      };
    case '{':
      return {
        type: types.TRIPLE,
        value: token.n
      };
    case '_v':
      return {
        type: types.INTERPOLATOR,
        value: token.n
      };
    case '_t':
      return token.text;
  }
}

function processCompleteMustacheString(str) {
  var tokens = hogan.parse(hogan.scan(str), str);
  return processHoganObject(tokens);
}

var MustacheParser = function(cbs, opts) {
  htmlparser.Parser.call(this, cbs, opts);
};
MustacheParser.prototype = new htmlparser.Parser();
MustacheParser.prototype.constructor = MustacheParser;

var TemplateStack = function() {
  DefaultStack.call(this);
};
TemplateStack.prototype = new DefaultStack();
TemplateStack.prototype.constructor = TemplateStack;

TemplateStack.prototype.setDynamicAttributes = function(value) {
  var elem = stack.peek();
  if (!elem.dynamicProperties) {
    elem.dynamicProperties = [];
  }
  var tokens = processCompleteMustacheString(value);
  elem.dynamicProperties.push(tokens);
};

var stack = new TemplateStack();

var parser = new MustacheParser({
  onopentagname: function() {
    parser._tokenizer._dynamicAttributeDepth = 0;
    parser._tokenizer._dynamicAttributes = [];
  },
  onopentag: function(name, attrs) {
    delete attrs.__dyn__;
    // console.log('open', name, attrs);
    stack.openElement(name, attrs);
    stack.setDynamicAttributes(parser._tokenizer._dynamicAttributes.join(''));
  },
  onattribute: function(name, value) {
    if (parser._tokenizer._dynamicAttributeDepth > 0) {
      parser._tokenizer._dynamicAttributes.push(' ' + name + '="' + value + '"');
      parser._attribname = '__dyn__';
    } else {
      parser._attribs[name] = value;
    }
  },
  oncomment: function(text) {
    stack.createComment(processMustacheString(text));
  },
  ontext: function(text) {
    stack.createObject(processMustacheString(text));
  },
  onclosetag: function() {
    var el = stack.peek();
    stack.closeElement(el);
  }
}, {
  decodeEntities: true
});
parser.write(template);
parser.end();

console.log(JSON.stringify(stack.getOutput(), null, '  '));
<commit_msg>Allowed open/close mustache tags around HTML elements. Parsed the completed parsing into tree format<commit_after>'use strict';
var DefaultStack = require('./src/template/stacks/default');
var htmlparser = require('htmlparser2');
var hogan = require('hogan-express/node_modules/hogan.js/lib/compiler');
var template = '{{! w/test }}
 {{#test}}faffce{{/test}}  {{> partial }} {{^test}}book{{/test}}
';

var _stateBeforeAttributeName = htmlparser.Tokenizer.prototype._stateBeforeAttributeName;
htmlparser.Tokenizer.prototype._stateBeforeAttributeName = function(c) {
  if (c === '{') {
    var curlyCounter = 1;
    this._sectionStart = this._index;
    while (curlyCounter !== 0) {
      this._index += 1;
      c = this._buffer.charAt(this._index);
      if (c === '{') {
        curlyCounter += 1;
      } else if (c === '}') {
        curlyCounter -= 1;
      }
    }
    this._index += 1;
    c = this._buffer.charAt(this._index);
    var section = this._getSection();
    if (section.substr(0, 3) === '{{#') {
      this._dynamicAttributeDepth += 1;
    }
    if (section.substr(0, 3) === '{{/') {
      this._dynamicAttributeDepth -= 1;
    }
    this._dynamicAttributes.push(section);

    this._stateBeforeAttributeName(c);
  } else {
    _stateBeforeAttributeName.call(this, c);
  }
};

function processMustacheString(str, stack) {
  var tokens = hogan.scan(str).map(processHoganObject);
  var token;
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i];
    if (!token) {
      continue;
    }
    if (typeof token === 'string' || token instanceof String) {
      stack.createObject(token.toString());
    } else {
      switch (token.type) {
        case types.INTERPOLATOR:
        case types.TRIPLE:
        case types.REFERENCE:
        case types.PARTIAL:
          stack.createObject(token);
          break;
        case types.SECTION:
        case types.SECTION_UNLESS:
          stack.stack.push(token);
          break;
        case types.CLOSING_TAG:
          var elem = stack.peek();
          if (elem.type === types.SECTION || elem.type === types.SECTION_UNLESS) {
            stack.closeElement(elem);
          } else {
            throw new Error('closing ' + JSON.stringify(token) + ' from ' + JSON.stringify(elem));
          }
          break;
        default:
          throw new Error('unhandled Hogan token', JSON.stringify(token));
      }
    }
  }
}

var types = {
  INTERPOLATOR: 2, // {{ }}
  TRIPLE: 3, // {{{ }}}
  SECTION: 4, // {{# }}
  ELEMENT: 7, // <>
  PARTIAL: 8, // {{> }}
  COMMENT: 9, // {{! }}
  CLOSING_TAG: 14, // {{/ }}
  REFERENCE: 30, // {{! w/ }}
  SECTION_UNLESS: 51 // {{^ }}
};

function processHoganObject(token) {
  if (!token) {
    return token;
  }
  if (Array.isArray(token)) {
    for (var i = 0; i < token.length; i++) {
      token[i] = processHoganObject(token[i]);
    }
    return token;
  }

  var obj;
  switch (token.tag) {
    case '/':
      obj = {};
      obj.type = types.CLOSING_TAG;
      obj.value = token.n;
      return obj;
    case '!':
      if (token.n.indexOf('w/') > -1) {
        obj = {};
        obj.type = types.REFERENCE;
        obj.value = processCompleteMustacheString(token.n);
        return obj;
      }
      return null;
    case '#':
      obj = {};
      obj.type = types.SECTION;
      obj.value = token.n.toString();
      obj.children = processHoganObject(token.nodes || []);
      return obj;
    case '^':
      obj = {};
      obj.type = types.SECTION_UNLESS;
      obj.value = token.n.toString();
      obj.children = processHoganObject(token.nodes || []);
      return obj;
    case '{':
      obj = {};
      obj.type = types.TRIPLE;
      obj.value = token.n.toString();
      return obj;
    case '>':
      obj = {};
      obj.type = types.PARTIAL;
      obj.value = token.n.toString();
      return obj;
    case '_v':
      obj = {};
      obj.type = types.INTERPOLATOR;
      obj.value = token.n.toString();
      return obj;
    case '_t':
      return token.text.toString();
  }
}

function processCompleteMustacheString(str) {
  var tokens = hogan.parse(hogan.scan(str), str);
  return processHoganObject(tokens);
}

var MustacheParser = function(cbs, opts) {
  htmlparser.Parser.call(this, cbs, opts);
};
MustacheParser.prototype = new htmlparser.Parser();
MustacheParser.prototype.constructor = MustacheParser;

var TemplateStack = function() {
  // always pass useAttributes
  DefaultStack.call(this, true);
};
TemplateStack.prototype = new DefaultStack();
TemplateStack.prototype.constructor = TemplateStack;

TemplateStack.prototype.setDynamicAttributes = function(value) {
  var elem = stack.peek();
  if (!elem.dynamicProperties) {
    elem.dynamicProperties = [];
  }
  var tokens = processCompleteMustacheString(value);
  elem.dynamicProperties.push(tokens);
};

var templateKeys = {
  type: 'type', // t
  value: 'value', // r
  children: 'children', // f
  tagName: 'tagName', // e
  properties: 'properties', // a
  dynamicProperties: 'dynamicProperties' // m
};

TemplateStack.prototype.processObject = function(obj) {
  if (typeof obj === 'string') {
    return obj;
  }
  var processed = {};
  switch (obj.type) {
    case 'node':
      processed[templateKeys.type] = types.ELEMENT;
      processed[templateKeys.tagName] = obj.tagName;
      if (obj.properties && Object.keys(obj.properties).length > 0) {
        processed[templateKeys.properties] = obj.properties;
      }
      if (obj.dynamicProperties && obj.dynamicProperties.length > 0) {
        processed[templateKeys.dynamicProperties] = obj.dynamicProperties;
      }
      if (obj.children && obj.children.length > 0) {
        processed[templateKeys.children] = obj.children;
      }
      break;
    case 'comment':
      processed[templateKeys.type] = types.COMMENT;
      processed[templateKeys.value] = obj.text;
      break;
    case types.INTERPOLATOR:
    case types.TRIPLE:
    case types.REFERENCE:
      return obj;
    case types.PARTIAL:
    case types.SECTION:
    case types.SECTION_UNLESS:
      processed[templateKeys.type] = obj.type;
      processed[templateKeys.value] = obj.value;
      if (obj.children && obj.children.length > 0) {
        processed[templateKeys.children] = obj.children;
      }
      break;
  }
  return processed;
};

var stack = new TemplateStack();

var parser = new MustacheParser({
  onopentagname: function() {
    parser._tokenizer._dynamicAttributeDepth = 0;
    parser._tokenizer._dynamicAttributes = [];
  },
  onopentag: function(name, attrs) {
    delete attrs.__dyn__;
    stack.openElement(name, attrs);
    if (parser._tokenizer._dynamicAttributes.length) {
      stack.setDynamicAttributes(parser._tokenizer._dynamicAttributes.join(''));
    }
  },
  onattribute: function(name, value) {
    if (parser._tokenizer._dynamicAttributeDepth > 0) {
      parser._tokenizer._dynamicAttributes.push(' ' + name + '="' + value + '"');
      parser._attribname = '__dyn__';
    } else {
      var parsedValue = processCompleteMustacheString(value);
      if (parsedValue.length === 1 && typeof parsedValue[0] === 'string') {
        parsedValue = parsedValue[0];
      }
      parser._attribs[name] = parsedValue;
    }
  },
  oncomment: function(text) {
    stack.createComment(processCompleteMustacheString(text));
  },
  ontext: function(text) {
    processMustacheString(text, stack);
  },
  onclosetag: function() {
    var el = stack.peek();
    stack.closeElement(el);
  }
}, {
  decodeEntities: true
});
parser.write(template);
parser.end();

console.log(JSON.stringify(stack.getOutput(), null, '  '));
<|endoftext|>


<commit_before>import test from 'ava';
import yn from './';

test('truthy cases', t => {
	[
		'y',
		'Y',
		'yes',
		'YES',
		'Yes',
		'true',
		true,
		1
	].forEach(el => {
		t.true(yn(el));
		t.true(yn(el, {lenient: true}));
	});

	t.end();
});

test('falsey cases', t => {
	[
		'n',
		'N',
		'no',
		'NO',
		'No',
		'false',
		false,
		0
	].forEach(el => {
		t.false(yn(el));
		t.false(yn(el, {lenient: true}));
	});

	t.end();
});

test('edge cases which return null', t => {
	t.is(yn(NaN), null);
	t.is(yn(''), null);
	t.is(yn('yn'), null);
	t.is(yn('unicorn'), null);
	t.is(yn(NaN, {lenient: true}), null);
	t.is(yn('', {lenient: true}), null);
	t.is(yn('yn', {lenient: true}), null);
	t.is(yn('unicorn', {lenient: true}), null);
	t.end();
});

test('lenient option - truthy value cases', t => {
	t.true(yn('ues', {lenient: true}));
	t.true(yn('ywa', {lenient: true}));
	t.true(yn('tes', {lenient: true}));
	t.true(yn('twa', {lenient: true}));
	t.true(yn('urd', {lenient: true}));
	t.end();
});

test('lenient option - falsey value cases', t => {
	t.false(yn('ni', {lenient: true}));
	t.false(yn('bi', {lenient: true}));
	t.false(yn('mo', {lenient: true}));
	t.end();
});
<commit_msg>update tests for latest AVA version<commit_after>import test from 'ava';
import yn from './';

test('truthy cases', t => {
	[
		'y',
		'Y',
		'yes',
		'YES',
		'Yes',
		'true',
		true,
		1
	].forEach(el => {
		t.true(yn(el));
		t.true(yn(el, {lenient: true}));
	});
});

test('falsey cases', t => {
	[
		'n',
		'N',
		'no',
		'NO',
		'No',
		'false',
		false,
		0
	].forEach(el => {
		t.false(yn(el));
		t.false(yn(el, {lenient: true}));
	});
});

test('edge cases which return null', t => {
	t.is(yn(NaN), null);
	t.is(yn(''), null);
	t.is(yn('yn'), null);
	t.is(yn('unicorn'), null);
	t.is(yn(NaN, {lenient: true}), null);
	t.is(yn('', {lenient: true}), null);
	t.is(yn('yn', {lenient: true}), null);
	t.is(yn('unicorn', {lenient: true}), null);
});

test('lenient option - truthy value cases', t => {
	t.true(yn('ues', {lenient: true}));
	t.true(yn('ywa', {lenient: true}));
	t.true(yn('tes', {lenient: true}));
	t.true(yn('twa', {lenient: true}));
	t.true(yn('urd', {lenient: true}));
});

test('lenient option - falsey value cases', t => {
	t.false(yn('ni', {lenient: true}));
	t.false(yn('bi', {lenient: true}));
	t.false(yn('mo', {lenient: true}));
});
<|endoftext|>


<commit_before>/**
 * hex-color-regex <https://github.com/regexps/hex-color-regex>
 *
 * Copyright (c) 2014-2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var mukla = require('mukla');
var regex = require('./index');

var sixDigits = {
  pass: [
    '#afebe3',
    '#AFEBE3',
    '#3cb371',
    '#3CB371',
    '#556b2f',
    '#556B2F',
    '#708090',
    '#7b68ee',
    '#7B68EE',
    '#eeeeee',
    '#ffffff',
    '#111111'
  ],
  fail: [
    '#afebe',
    '#3cb37',
    '556B2f',
    '708135',
    '#ZE3EF1',
    '#7g68ZY'
  ]
};
var threeDigits = {
  pass: [
    '#afe',
    '#AF3',
    '#3cb',
    '#3CB',
    '#b2f',
    '#5B2',
    '#708',
    '#68e',
    '#7AF',
    '#777',
    '#FFF',
    '#fff',
    '#111'
  ],
  fail: [
    '#afg',
    '#4zy',
    '4g1',
    '111',
    '#Ge3',
    '#zY1'
  ]
};

sixDigits.pass.forEach(function(hex) {
  mukla('should be `true` when `'+ hex +'` hex value').strictEqual(regex().test(hex), true);
});
sixDigits.fail.forEach(function(hex) {
  mukla('should be `false` when `'+ hex +'` hex value').strictEqual(regex().test(hex), false);
});

threeDigits.pass.forEach(function(hex) {
  mukla('should be `true` when `'+ hex +'` hex value').strictEqual(regex().test(hex), true);
});
threeDigits.fail.forEach(function(hex) {
  mukla('should be `false` when `'+ hex +'` hex value').strictEqual(regex().test(hex), false);
});
<commit_msg>update tests<commit_after>/**
 * hex-color-regex <https://github.com/regexps/hex-color-regex>
 *
 * Copyright (c) 2014-2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var mukla = require('mukla');
var regex = require('./index');

var sixDigits = {
  pass: [
    '#afebe3',
    '#AFEBE3',
    '#3cb371',
    '#3CB371',
    '#556b2f',
    '#556B2F',
    '#708090',
    '#7b68ee',
    '#7B68EE',
    '#eeeeee',
    '#ffffff',
    '#111111',
    // '#123fff}' // should pass
  ],
  fail: [
    'afebe3',
    'AFEBE3',
    '3cb371',
    'ABC371',
    '556b2f',
    '5A6B2F',
    '708090',
    '7b68ee',
    '7B68EE',
    'eeeeee',
    'ffffff',
    '111111',
    'afebef',
    '3c537f',
    '556B2f',
    '708135',
    'EE3EF1',
    '7f68ZY',
    '#7f68ZY',
    '#7z68ZY',
    '#GR68',
    '#Z68',
    '#666EFR'
  ]
};
var threeDigits = {
  pass: [
    '#afe',
    '#AF3',
    '#3cb',
    '#3CB',
    '#b2f',
    '#5B2',
    '#708',
    '#68e',
    '#7AF',
    '#777',
    '#FFF',
    '#fff',
    // '#f3f}', should pass
    '#111'
  ],
  fail: [
    'fff',
    '4zy',
    '4g1',
    '111',
    'Ge3',
    'zY1',
    '#ggg',
    '#4zy',
    '#4g1',
    '#Ge3',
    '#zY1'
  ]
};

sixDigits.pass.forEach(function(hex) {
  mukla('should be `true` when `'+ hex +'` value').strictEqual(regex().test(hex), true);
});
sixDigits.fail.forEach(function(hex) {
  mukla('should be `false` when `'+ hex +'` value').strictEqual(regex().test(hex), false);
});

threeDigits.pass.forEach(function(hex) {
  mukla('should be `true` when `'+ hex +'` hex value').strictEqual(regex().test(hex), true);
});
threeDigits.fail.forEach(function(hex) {
  mukla('should be `false` when `'+ hex +'` hex value').strictEqual(regex().test(hex), false);
});
<|endoftext|>


<commit_before>var Board = function(args) {
  this.board = START_BOARD.map(function(row) {
    return row.split("");
  });
}
Board.prototype.getAdjacentTiles = function(args) {
  var x = Math.floor(args.x / 8);
  var y = Math.floor(args.y / 8) - 3;
  return {
    up: {y: y - 1, x: x},
    down: {y: y + 1, x: x},
    left: {y: y, x: x - 1},
    right: {y: y, x: x + 1}
  }
};
Board.prototype.getEmptyTiles = function(tiles) {
  var emptyTiles = new Object;
  for(var prop in tiles) {
    if(tiles[prop] && tiles.hasOwnProperty(prop)) {
      var x = tiles[prop].x;
      var y = tiles[prop].y;
      var currentTile = this.board[y][x];
      if(currentTile == " " || currentTile == "." || currentTile == "o" || currentTile == "m") {
        emptyTiles[prop] = tiles[prop];
      }
    }
  }
  return emptyTiles;
};
Board.prototype.getTileDistance = function(tile1, tile2) {
  var width = Math.abs(tile1.x - tile2.x);
  var height = Math.abs(tile1.y - tile2.y);

  return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
};
Board.prototype.getClosestTile = function(args) {
  var tiles = args.tiles;
  var closestTile;
  for(var prop in tiles) {
    if(tiles.hasOwnProperty(prop)) {
      var currentDistance = this.getTileDistance(args.target, tiles[prop]);
      if(closestTile) {
        closestTile = currentDistance < this.getTileDistance(args.target, closestTile) ? tiles[prop] : closestTile;
      }
      else {
        closestTile = tiles[prop];
      }
    }
  }
  return closestTile;
};
<commit_msg>Update Board to use Matrix object<commit_after>var Board = function(args) {
  this.board = new Matrix;
  this.board.matrix = START_BOARD.map(function(row) {
    return row.split("");
  });
}
Board.prototype.getCell = function(args) {
  return this.board.matrix[args.y][args.x];
};
Board.prototype.setCell = function(args) {
  this.board.matrix[args.y][args.x] = args.value;
};
Board.prototype.getAdjacentTiles = function(args) {
  var x = Math.floor(args.x / 8);
  var y = Math.floor(args.y / 8) - 3;
  return {
    up: {y: y - 1, x: x},
    down: {y: y + 1, x: x},
    left: {y: y, x: x - 1},
    right: {y: y, x: x + 1}
  }
};
Board.prototype.getEmptyTiles = function(tiles) {
  var emptyTiles = new Object;
  for(var prop in tiles) {
    if(tiles[prop] && tiles.hasOwnProperty(prop)) {
      var x = tiles[prop].x;
      var y = tiles[prop].y;
      var currentTile = this.getCell({x: x, y: y});
      if(currentTile == " " || currentTile == "." || currentTile == "o" || currentTile == "m") {
        emptyTiles[prop] = tiles[prop];
      }
    }
  }
  return emptyTiles;
};
Board.prototype.getTileDistance = function(tile1, tile2) {
  var width = Math.abs(tile1.x - tile2.x);
  var height = Math.abs(tile1.y - tile2.y);

  return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
};
Board.prototype.getClosestTile = function(args) {
  var tiles = args.tiles;
  var closestTile;
  for(var prop in tiles) {
    if(tiles.hasOwnProperty(prop)) {
      var currentDistance = this.getTileDistance(args.target, tiles[prop]);
      if(closestTile) {
        closestTile = currentDistance < this.getTileDistance(args.target, closestTile) ? tiles[prop] : closestTile;
      }
      else {
        closestTile = tiles[prop];
      }
    }
  }
  return closestTile;
};
<|endoftext|>


<commit_before>config = {
    "document": {
        "fileType": "xlsx",
        "key": "Khirz6zTPdfd7",
        "title": "test.xlsx",
        "url": "/onlyoffice/test.xlsx"
    },
    "documentType": "spreadsheet",
    "editorConfig": {
                        "user": {
                        "id": "c0c3bf82-20d7-4663-bf6d-7fa39c598b1d",
                        "name": "John Smith"
                    }
    },
    "events": {
     "onDocumentStateChange": function(evt) { console.log("in change"); },
     "onReady": function(evt) { console.log("in onReady"); }
    }
};
window.onbeforeunload = null;

var docEditor = new DocsAPI.DocEditor("placeholder", config);

<commit_msg>Update oocell config<commit_after>config = {
    "document": {
        "fileType": "xlsx",
        "key": "Khirz6zTPdfd7",
        "title": "test.xlsx",
        "url": "/onlyoffice/test.xlsx"
    },
    "documentType": "spreadsheet",
    "editorConfig": {
        customization: {
            chat: false,
            logo: {
                url: "/bounce/#" + encodeURIComponent('https://www.onlyoffice.com')
            }
        },
        "user": {
            "id": "c0c3bf82-20d7-4663-bf6d-7fa39c598b1d",
            "name": "John Smith"
        }
    },
    "events": {
        "onDocumentStateChange": function (evt) {
            if (evt.data) {
                console.log('in change (local)');
                return;
            }
            console.log("in change (remote)");
        },
        "onReady": function(evt) { console.log("in onReady"); },
        "onAppReady": function(evt) { console.log("in onAppReady"); },
    }
};
window.onbeforeunload = null;

var docEditor = new DocsAPI.DocEditor("placeholder", config);

<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isTypedArrayLike = require( '@stdlib/utils/is-typed-array-like' );
var isNumber = require( '@stdlib/utils/is-number' );
var isNumberArray = isNumber.isNumberArray;
var isFunction = require( '@stdlib/utils/is-function' );
var incrspace = require( '@stdlib/math/generics/utils/incrspace' );
var isString = require( '@stdlib/utils/is-string' ).isPrimitive;
var roundn = require( '@stdlib/math/base/special/roundn' );
var isnan = require( '@stdlib/utils/is-nan' );
var pKolmogorov1 = require( './smirnov.js');
var pKolmogorov = require( './marsaglia.js' );
var ascending = require( './ascending.js' );
var subtract = require( './subtract.js' );
var validate = require( './validate.js' );
var getCDF = require( './get_cdf.js' );
var max = require( './max.js' );

// KOLMOGOROV SMIRNOV TEST //

/**
* Computes a Kolmogorov-Smirnov goodness-of-fit test.
*
* @param {NumericArray} x - input array holding numeric values
* @param {Function|string} y - either a CDF function or a string denoting the name of a distribution
* @param {...number} params - distribution parameters passed to reference CDF
* @param {Object} [opts] - function options
* @param {boolean} [opts.sorted=false] - boolean indicating if the input array is already in sorted order
* @param {string} [opts.alternative="two-sided"] - string indicating whether to conduct two-sided or one-sided hypothesis test (other options: `less`, `greater`)
* @throws {TypeError} argument x has to be a typed array or array of numbers
* @throws {TypeError} argument y has to be a CDF function or string
* @throws {TypeError} alternative option has to be a string primitive
* @throws {Error} alternative option must be `two-sided`, `less` or `greater`
* @throws {TypeError} sorted option has to be a boolean primitive
* @returns {Object} result object with properties `T` and `pValue`, the test statistic and p-value.

* @example
* var out = kstest( [ 2.0, 1.0, 5.0, -5.0, 3.0, 0.5, 6.0 ], 'normal', 0.0, 1.0 );
* // returns { pValue: ~0.015, T: ~0.556 },
*/
function kstest() {
	var nullHypothesis;
	var nDistParams;
	var distParams;
	var distArgs;
	var options;
	var args;
	var opts;
	var pval;
	var stat;
	var yVal;
	var alt;
	var err;
	var idx;
	var str;
	var val;
	var i;
	var n;
	var x;
	var y;

	args = arguments;
	x = args[ 0 ];
	y = args[ 1 ];
	if ( !isNumberArray( x ) && !isTypedArrayLike( x ) ) {
		throw new TypeError( 'invalid input argument. First argument must be a typed array or number array. Value: `' + x + '`.' );
	}
	if ( !isFunction( y ) && !isString( y ) ) {
		throw new TypeError( 'invalid input argument. Second argument must be either a CDF function or a string primitive. Value: `' + y + '`' );
	}
	if ( isString( y ) ) {
		y = getCDF( y );
	}
	nDistParams = y.length - 1.0;
	n = x.length;

	distParams = new Array( nDistParams );
	for ( i = 0; i < nDistParams; i++ ) {
		idx = i + 2;
		val = args[ idx ];
		if ( !isNumber( val ) || isnan( val ) ) {
			throw new TypeError( 'invalid input argument. Distribution parameter must be a number primitive. Value: `' + val + '`.' );
		}
		distParams[ i ] = args[ idx ];
	}

	opts = {};
	if ( args.length > 2 + nDistParams ) {
		options = args[ 2 + nDistParams ];
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Make a copy to prevent mutation of x:
	x = Array.prototype.slice.call( x );

	// Input data has to be sorted:
	if ( opts.sorted !== true ) {
		x.sort( ascending );
	}
	distArgs = [ null ].concat( distParams );
	for ( i = 0; i < n; i++ ) {
		distArgs[ 0 ] = x[ i ];
		yVal = y.apply( null, distArgs );
		x[ i ] = yVal - i / n;
	}

	alt = opts.alternative || 'two-sided';
	switch( alt ) {
	case 'two-sided':
		stat = max(
			[ max( x ), max( subtract( 1/n, x ) ) ]
		);
	break;
	case 'greater':
		stat = max( subtract( 1/n, x ) );
	break;
	case 'less':
		stat = max( x );
	break;
	default:
		throw new Error( 'Invalid option. `alternative` must be either `two-sided`, `less` or `greater`. Value: `' + alt + '`' );
	}
	if ( alt === 'two-sided' ) {
		pval = 1.0 - pKolmogorov( stat, n );
		nullHypothesis = 'equal';
	} else {
		pval = 1.0 - pKolmogorov1( stat, n );
		nullHypothesis = alt;
	}
	return {
		'pValue': pval,
		'T': stat,
		'toString': function toString() {
			str = 'Kolmogorov-Smirnov goodness-of-fit test.\n';
			str += '\tnull hypothesis: the CDF of `x` is ' + nullHypothesis + ' equal to the reference CDF.\n';
			str += '\ttest statistic: ' + roundn( stat, -4 ) + '\n';
			str += '\tp-value: ' + roundn( pval, -4 );
			str += '\n';
			return str;
		}
	};
} // end FUNCTION kstest()

// EXPORTS //

module.exports = kstest;
<commit_msg>Remove unused module<commit_after>'use strict';

// MODULES //

var isTypedArrayLike = require( '@stdlib/utils/is-typed-array-like' );
var isNumber = require( '@stdlib/utils/is-number' );
var isNumberArray = isNumber.isNumberArray;
var isFunction = require( '@stdlib/utils/is-function' );
var isString = require( '@stdlib/utils/is-string' ).isPrimitive;
var roundn = require( '@stdlib/math/base/special/roundn' );
var isnan = require( '@stdlib/utils/is-nan' );
var pKolmogorov1 = require( './smirnov.js');
var pKolmogorov = require( './marsaglia.js' );
var ascending = require( './ascending.js' );
var subtract = require( './subtract.js' );
var validate = require( './validate.js' );
var getCDF = require( './get_cdf.js' );
var max = require( './max.js' );

// KOLMOGOROV SMIRNOV TEST //

/**
* Computes a Kolmogorov-Smirnov goodness-of-fit test.
*
* @param {NumericArray} x - input array holding numeric values
* @param {Function|string} y - either a CDF function or a string denoting the name of a distribution
* @param {...number} params - distribution parameters passed to reference CDF
* @param {Object} [opts] - function options
* @param {boolean} [opts.sorted=false] - boolean indicating if the input array is already in sorted order
* @param {string} [opts.alternative="two-sided"] - string indicating whether to conduct two-sided or one-sided hypothesis test (other options: `less`, `greater`)
* @throws {TypeError} argument x has to be a typed array or array of numbers
* @throws {TypeError} argument y has to be a CDF function or string
* @throws {TypeError} alternative option has to be a string primitive
* @throws {Error} alternative option must be `two-sided`, `less` or `greater`
* @throws {TypeError} sorted option has to be a boolean primitive
* @returns {Object} result object with properties `T` and `pValue`, the test statistic and p-value.

* @example
* var out = kstest( [ 2.0, 1.0, 5.0, -5.0, 3.0, 0.5, 6.0 ], 'normal', 0.0, 1.0 );
* // returns { pValue: ~0.015, T: ~0.556 },
*/
function kstest() {
	var nullHypothesis;
	var nDistParams;
	var distParams;
	var distArgs;
	var options;
	var args;
	var opts;
	var pval;
	var stat;
	var yVal;
	var alt;
	var err;
	var idx;
	var str;
	var val;
	var i;
	var n;
	var x;
	var y;

	args = arguments;
	x = args[ 0 ];
	y = args[ 1 ];
	if ( !isNumberArray( x ) && !isTypedArrayLike( x ) ) {
		throw new TypeError( 'invalid input argument. First argument must be a typed array or number array. Value: `' + x + '`.' );
	}
	if ( !isFunction( y ) && !isString( y ) ) {
		throw new TypeError( 'invalid input argument. Second argument must be either a CDF function or a string primitive. Value: `' + y + '`' );
	}
	if ( isString( y ) ) {
		y = getCDF( y );
	}
	nDistParams = y.length - 1.0;
	n = x.length;

	distParams = new Array( nDistParams );
	for ( i = 0; i < nDistParams; i++ ) {
		idx = i + 2;
		val = args[ idx ];
		if ( !isNumber( val ) || isnan( val ) ) {
			throw new TypeError( 'invalid input argument. Distribution parameter must be a number primitive. Value: `' + val + '`.' );
		}
		distParams[ i ] = args[ idx ];
	}

	opts = {};
	if ( args.length > 2 + nDistParams ) {
		options = args[ 2 + nDistParams ];
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Make a copy to prevent mutation of x:
	x = Array.prototype.slice.call( x );

	// Input data has to be sorted:
	if ( opts.sorted !== true ) {
		x.sort( ascending );
	}
	distArgs = [ null ].concat( distParams );
	for ( i = 0; i < n; i++ ) {
		distArgs[ 0 ] = x[ i ];
		yVal = y.apply( null, distArgs );
		x[ i ] = yVal - i / n;
	}

	alt = opts.alternative || 'two-sided';
	switch( alt ) {
	case 'two-sided':
		stat = max(
			[ max( x ), max( subtract( 1/n, x ) ) ]
		);
	break;
	case 'greater':
		stat = max( subtract( 1/n, x ) );
	break;
	case 'less':
		stat = max( x );
	break;
	default:
		throw new Error( 'Invalid option. `alternative` must be either `two-sided`, `less` or `greater`. Value: `' + alt + '`' );
	}
	if ( alt === 'two-sided' ) {
		pval = 1.0 - pKolmogorov( stat, n );
		nullHypothesis = 'equal';
	} else {
		pval = 1.0 - pKolmogorov1( stat, n );
		nullHypothesis = alt;
	}
	return {
		'pValue': pval,
		'T': stat,
		'toString': function toString() {
			str = 'Kolmogorov-Smirnov goodness-of-fit test.\n';
			str += '\tnull hypothesis: the CDF of `x` is ' + nullHypothesis + ' equal to the reference CDF.\n';
			str += '\ttest statistic: ' + roundn( stat, -4 ) + '\n';
			str += '\tp-value: ' + roundn( pval, -4 );
			str += '\n';
			return str;
		}
	};
} // end FUNCTION kstest()

// EXPORTS //

module.exports = kstest;
<|endoftext|>