<commit_before>var pause = undefined;
var play = undefined;
var video = undefined;
var canvas = undefined;
var tapesound = undefined;
// var staticsound = undefined;

function endstatic()
{
	document.body.style.backgroundImage = "none";
	document.body.style.backgroundColor = "black";

//	staticsound.pause();
}

function videoloop()
{
		if (video && !video.paused && !video.ended) {
				context.drawImage(video, 0, 0, canvas.width, canvas.height);
				setTimeout(videoloop, 1000 / 60);
		}
}

function startvid()
{
	canvas.style.display = "inline";
	video.play();
}

function playoff()
{
	play.style.display = "none";
}

function startsound()
{
	tapesound.play();
}

function onplay(e)
{
	pause.style.display = "none";
	play.style.display = "inline";

	setTimeout(playoff, 7000);
	setTimeout(startvid, 5000);
	setTimeout(endstatic, 2000);
	setTimeout(startsound, 1000);
}

function reset()
{
	pause.style.display = "inline";
	play.style.display = "none";
	canvas.style.display = "none";

	video.currentTime = 0;
	video.pause();

	tapesound.currentTime = 0;
	tapesound.pause();

 // staticsound.play();

	var string = "/img/tiled static.gif";
	document.body.style.backgroundImage = "url('" + string + "')";
	document.body.style.backgroundColor = "white";
}

window.onload = function()
{
	pause = document.getElementById("pause");
	play = document.getElementById("play");
	console.log("load successed");
	pause.onclick = onplay;

	tapesound = document.createElement("audio");
	tapesound.src = "/tapefeed.mp3";
	tapesound.pause();

//	staticsound = document.createElement("audio");
//	staticsound.src = "";
//	staticsound.loop = true;
//	staticsound.play();

	video = document.createElement("video");
	video.src = "http://oman.imjake.me/About.mp4";
	video.pause();
	video.addEventListener('play',function(){
		videoloop();
	},false);
	video.addEventListener('ended',function(){
		reset();
	},false);

	canvas = document.getElementById("canvas");
	context = canvas.getContext("2d");

	canvas.width = canvas.clientWidth;
	canvas.height = canvas.clientHeight;

	context.clearRect(0, 0, canvas.width, canvas.height);
}
<commit_msg>Update about.js<commit_after>var pause = undefined;
var play = undefined;
var video = undefined;
var canvas = undefined;
var tapesound = undefined;
// var staticsound = undefined;

function endstatic()
{
	document.body.style.backgroundImage = "none";
	document.body.style.backgroundColor = "black";

//	staticsound.pause();
}

function videoloop()
{
		if (video && !video.paused && !video.ended) {
				context.drawImage(video, 0, 0, canvas.width, canvas.height);
				requestAnimationFrame(videoloop);
		}
}

function startvid()
{
	canvas.style.display = "inline";
	video.play();
}

function playoff()
{
	play.style.display = "none";
}

function startsound()
{
	tapesound.play();
}

function onplay(e)
{
	pause.style.display = "none";
	play.style.display = "inline";

	setTimeout(playoff, 7000);
	setTimeout(startvid, 5000);
	setTimeout(endstatic, 2000);
	setTimeout(startsound, 1000);
}

function reset()
{
	pause.style.display = "inline";
	play.style.display = "none";
	canvas.style.display = "none";

	video.currentTime = 0;
	video.pause();

	tapesound.currentTime = 0;
	tapesound.pause();

 // staticsound.play();

	var string = "/img/tiled static.gif";
	document.body.style.backgroundImage = "url('" + string + "')";
	document.body.style.backgroundColor = "white";
}

window.onload = function()
{
	pause = document.getElementById("pause");
	play = document.getElementById("play");
	console.log("load successed");
	pause.onclick = onplay;

	tapesound = document.createElement("audio");
	tapesound.src = "/tapefeed.mp3";
	tapesound.pause();

//	staticsound = document.createElement("audio");
//	staticsound.src = "";
//	staticsound.loop = true;
//	staticsound.play();

	video = document.createElement("video");
	video.src = "http://oman.imjake.me/About.mp4";
	video.pause();
	video.addEventListener('play',function(){
		videoloop();
	},false);
	video.addEventListener('ended',function(){
		reset();
	},false);

	canvas = document.getElementById("canvas");
	context = canvas.getContext("2d");

	canvas.width = canvas.clientWidth;
	canvas.height = canvas.clientHeight;

	context.clearRect(0, 0, canvas.width, canvas.height);
}
<|endoftext|>


<commit_before>/*
    Written for my personal website by Rene Kjellerup
    published under GPLv3 or later and never in minified form.
    see https://www.gnu.org/licenses.html
*/
var page_cache = {};

function async_cached(ele, url)
{
    if (url in page_cache)
    {
        ele.innerHTML = page_cache[url];
        return true;
    }
    return false;
}

function async_load_content(div, url)
{
    const frame = document.getElementById(div);
    if(frame === null){
        console.error( new Error('element '+div+' not found on page'));
        return;
    }
    if (async_cached(frame, url)) {
        return;
    }
    fetch(url)
        .then((resp) => {
            if(!resp.ok)
                throw new Error('could not get '+url+' from server');
            return resp.text();
        })
        .then((page) => {
            page_cache[url] = page;
            frame.innerHTML = page;
        })
        .catch((err) => console.error(err));
}

function ajax_loadContent(div, url) {
    async_load_content(div, url);
}<commit_msg>fixed missing newline at the end of the new async.js script<commit_after>/*
    Written for my personal website by Rene Kjellerup
    published under GPLv3 or later and never in minified form.
    see https://www.gnu.org/licenses.html
*/
var page_cache = {};

function async_cached(ele, url)
{
    if (url in page_cache)
    {
        ele.innerHTML = page_cache[url];
        return true;
    }
    return false;
}

function async_load_content(div, url)
{
    const frame = document.getElementById(div);
    if(frame === null){
        console.error( new Error('element '+div+' not found on page'));
        return;
    }
    if (async_cached(frame, url)) {
        return;
    }
    fetch(url)
        .then((resp) => {
            if(!resp.ok)
                throw new Error('could not get '+url+' from server');
            return resp.text();
        })
        .then((page) => {
            page_cache[url] = page;
            frame.innerHTML = page;
        })
        .catch((err) => console.error(err));
}

function ajax_loadContent(div, url) {
    async_load_content(div, url);
}
<|endoftext|>


<commit_before>describe('module:Enum', function() {
    'use strict';

    var Enums = ne.util.Enums,
        enums;

    var isModernBrowser = (function () {
        try {
            Object.defineProperty({}, 'x', {});
            return true;
        } catch (e) {
            return false;
        }
    }());

    beforeEach(function() {
        enums = new Enums();
    });

    describe('.set()', function() {
        it('상수명을 입력받을수있다.', function() {
            enums.set('CONST1', 'CONST2');

            expect(enums.CONST1).toBeDefined();
            expect(enums.CONST2).toBeDefined();
        });

        it('배열로 상수를 지정할수있다', function() {
            enums.set(['CONST3', 'CONST4']);

            expect(enums.CONST3).toBeDefined();
            expect(enums.CONST4).toBeDefined();
        });

        it('상수들은 서로다른 값을 갖는다', function() {
            enums.set('CONST1', 'CONST2');

            expect(enums.CONST1).not.toEqual(enums.CONST2);
        });

        it('한번정의된 상수는 재정의 될수없다', function() {
            var originalValue;

            enums.set('CONST1', 'CONST2');
            originalValue = enums.CONST1;
            enums.set('CONST1');

            expect(enums.CONST1).toEqual(originalValue);
        });
    });

    describe('.getName()', function() {
        it('값을 입력해 상수명을 얻어올수있다', function() {
            var result;

            enums.set('CONST1', 'CONST2');
            result = enums.getName(enums.CONST1);

            expect(result).toEqual('CONST1');
        });
    });

    describe('생성자 옵션으로 상수들을 지정할수있다', function() {
        it('상수들이 정상적으로 생성되었다', function() {
            var enum2 = new Enums('CONST1', 'CONST2');

            expect(enum2.CONST1).toBeDefined();
            expect(enum2.CONST2).toBeDefined();
        });

        it('배열로 상수들이 정상적으로 생성되었다', function() {
            var enum2 = new Enums(['CONST1', 'CONST2']);

            expect(enum2.CONST1).toBeDefined();
            expect(enum2.CONST2).toBeDefined();
        });
    });

    if (isModernBrowser) {
        describe('Modern Browser: 정의된 값은 변경할수없다', function() {
            beforeEach(function() {
                enums.set('CONST1', 'CONST2');
            });

            it('상수의 값이 변경되지 않는다', function() {
                var desc = Object.getOwnPropertyDescriptor(enums, 'CONST1');

                expect(desc.writable).toEqual(false);
                expect(desc.configurable).toEqual(false);
            });
        });
    }
});
<commit_msg>테스트케이스 변경<commit_after>describe('module:Enum', function() {
    'use strict';

    var Enum = ne.util.Enum,
        enumO;

    var isModernBrowser = (function () {
        try {
            Object.defineProperty({}, 'x', {});
            return true;
        } catch (e) {
            return false;
        }
    }());

    beforeEach(function() {
        enumO = new Enum();
    });

    describe('.set()', function() {
        it('상수명을 입력받을수있다.', function() {
            enumO.set('CONST1', 'CONST2');

            expect(enumO.CONST1).toBeDefined();
            expect(enumO.CONST2).toBeDefined();
        });

        it('배열로 상수를 지정할수있다', function() {
            enumO.set(['CONST3', 'CONST4']);

            expect(enumO.CONST3).toBeDefined();
            expect(enumO.CONST4).toBeDefined();
        });

        it('상수들은 서로다른 값을 갖는다', function() {
            enumO.set('CONST1', 'CONST2');

            expect(enumO.CONST1).not.toEqual(enumO.CONST2);
        });

        it('한번정의된 상수는 재정의 될수없다', function() {
            var originalValue;

            enumO.set('CONST1', 'CONST2');
            originalValue = enumO.CONST1;
            enumO.set('CONST1');

            expect(enumO.CONST1).toEqual(originalValue);
        });
    });

    describe('.getName()', function() {
        it('값을 입력해 상수명을 얻어올수있다', function() {
            var result;

            enumO.set('CONST1', 'CONST2');
            result = enumO.getName(enumO.CONST1);

            expect(result).toEqual('CONST1');
        });
    });

    describe('생성자 옵션으로 상수들을 지정할수있다', function() {
        it('상수들이 정상적으로 생성되었다', function() {
            var enumO2 = new Enum('CONST1', 'CONST2');

            expect(enumO2.CONST1).toBeDefined();
            expect(enumO2.CONST2).toBeDefined();
        });

        it('배열로 상수들이 정상적으로 생성되었다', function() {
            var enumO2 = new Enum(['CONST1', 'CONST2']);

            expect(enumO2.CONST1).toBeDefined();
            expect(enumO2.CONST2).toBeDefined();
        });
    });

    if (isModernBrowser) {
        describe('Modern Browser: 정의된 값은 변경할수없다', function() {
            beforeEach(function() {
                enumO.set('CONST1', 'CONST2');
            });

            it('상수의 값이 변경되지 않는다', function() {
                var desc = Object.getOwnPropertyDescriptor(enumO, 'CONST1');

                expect(desc.writable).toEqual(false);
                expect(desc.configurable).toEqual(false);
            });
        });
    }
});
<|endoftext|>


<commit_before>/* global describe, it */

const assert = require('assert')

const Euler = require('../')

describe('Euler', function () {
  describe('#euler1()', function () {
    it('solves Project Euler #1', function () {
      assert.equal(233168, Euler.euler1())
    })
  })
  describe('#euler16()', function () {
    it('solves Project Euler #16', function () {
      assert.equal(1366, Euler.euler16(1000))
    })
  })
  describe('#euler19()', function () {
    it('solves Project Euler #19', function () {
      assert.equal(171, Euler.euler19())
    })
  })
  describe('#euler20()', function () {
    it('solves Project Euler #20', function () {
      assert.equal(648, Euler.euler20())
    })
  })
  describe('#euler48()', function () {
    it('solves Project Euler #48', function () {
      assert.equal('9110846700', Euler.euler48())
    })
  })
})
<commit_msg>fix: Add test parameter<commit_after>/* global describe, it */

const assert = require('assert')

const Euler = require('../')

describe('Euler', function () {
  describe('#euler1()', function () {
    it('solves Project Euler #1', function () {
      assert.equal(233168, Euler.euler1())
    })
  })
  describe('#euler16()', function () {
    it('solves Project Euler #16', function () {
      assert.equal(1366, Euler.euler16(1000))
    })
  })
  describe('#euler19()', function () {
    it('solves Project Euler #19', function () {
      assert.equal(171, Euler.euler19())
    })
  })
  describe('#euler20()', function () {
    it('solves Project Euler #20', function () {
      assert.equal(648, Euler.euler20(100))
    })
  })
  describe('#euler48()', function () {
    it('solves Project Euler #48', function () {
      assert.equal('9110846700', Euler.euler48())
    })
  })
})
<|endoftext|>


<commit_before>anol.control.Control = function(options) {
    if(options === undefined) {
        return;
    }

    this.active = options.active || false;
    this.exclusive = options.exclusive || false;
    this.element = options.element;

    if(options.olControl === undefined) {
        var controlElement;
        if(this.element !== undefined) {
            controlElement = this.element[0];
        }

        this.olControl = new ol.control.Control({
            element: controlElement
        });
    } else {
        this.olControl = options.olControl;
    }
};

anol.control.Control.prototype = {
    CLASS_NAME: 'anol.control.Control',
    DEFAULT_OPTIONS: {},
    activate: function() {
        this.active = true;
        $(this).triggerHandler('anol.control.activate');
    },
    onActivate: function(func, context) {
        var targetControl = this;
        $(this).on('anol.control.activate', function() {
            func(targetControl, context);
        });
    },
    deactivate: function() {
        this.active = false;
        $(this).triggerHandler('anol.control.deactivate');
    },
    onDeactivate: function(func, context) {
        var targetControl = this;
        $(this).on('anol.control.deactivate', function() {
            func(targetControl, context);
        });
    }
};
<commit_msg>Added interaction and target property to anol.control.Control<commit_after>anol.control.Control = function(options) {
    if(options === undefined) {
        return;
    }

    this.active = options.active || false;
    this.exclusive = options.exclusive || false;
    this.element = options.element;
    this.interaction = options.interaction;

    if(options.olControl === undefined) {
        var controlElement;
        if(this.element !== undefined) {
            controlElement = this.element[0];
        }
        var target;
        if(options.target !== undefined) {
            target = options.target[0];
        }

        this.olControl = new ol.control.Control({
            element: controlElement,
            target: target
        });
    } else {
        this.olControl = options.olControl;
    }
};

anol.control.Control.prototype = {
    CLASS_NAME: 'anol.control.Control',
    DEFAULT_OPTIONS: {},
    activate: function() {
        this.active = true;
        $(this).triggerHandler('anol.control.activate');
    },
    onActivate: function(func, context) {
        var targetControl = this;
        $(this).on('anol.control.activate', function() {
            func(targetControl, context);
        });
    },
    deactivate: function() {
        this.active = false;
        $(this).triggerHandler('anol.control.deactivate');
    },
    onDeactivate: function(func, context) {
        var targetControl = this;
        $(this).on('anol.control.deactivate', function() {
            func(targetControl, context);
        });
    }
};
<|endoftext|>


<commit_before>'use strict';
const expect = require('chai').expect;
const Faker = require('../src/faker');

describe('#Faker', () => {
  it('should be an object', () => {
    expect(Faker).to.be.a('object');
  });

  describe('#Address', () => {
    it('should be an object', () => {
      expect(Faker.Address).to.be.a('object');
    });
  });

  describe('#Ancient', () => {
    it('should be an object', () => {
      expect(Faker.Ancient).to.be.a('object');
    });
  });

  describe('#App', () => {
    it('should be an object', () => {
      expect(Faker.App).to.be.a('object');
    });
  });

  describe('#Avatar', () => {
    it('should be an object', () => {
      expect(Faker.Avatar).to.be.a('object');
    });
  });

  describe('#Bank', () => {
    it('should be an object', () => {
      expect(Faker.Bank).to.be.a('object');
    });
  });

  describe('#Beer', () => {
    it('should be an object', () => {
      expect(Faker.Beer).to.be.a('object');
    });
  });

  describe('#Bitcoin', () => {
    it('should be an object', () => {
      expect(Faker.Bitcoin).to.be.a('object');
    });
  });

  describe('#Book', () => {
    it('should be an object', () => {
      expect(Faker.Book).to.be.a('object');
    });
  });

  describe('#Boolean', () => {
    it('should be an object', () => {
      expect(Faker.Boolean).to.be.a('object');
    });
  });

  describe('#Business', () => {
    it('should be an object', () => {
      expect(Faker.Business).to.be.a('object');
    });
  });

  describe('#Cat', () => {
    it('should be an object', () => {
      expect(Faker.Cat).to.be.a('object');
    });
  });

  describe('#ChuckNorris', () => {
    it('should be an object', () => {
      expect(Faker.ChuckNorris).to.be.a('object');
    });
  });

  describe('#Coffee', () => {
    it('should be an object', () => {
      expect(Faker.Coffee).to.be.a('object');
    });
  });

  describe('#Color', () => {
    it('should be an object', () => {
      expect(Faker.Color).to.be.a('object');
    });
  });

  describe('#Commerce', () => {
    it('should be an object', () => {
      expect(Faker.Commerce).to.be.a('object');
    });
  });

  describe('#Company', () => {
    it('should be an object', () => {
      expect(Faker.Company).to.be.a('object');
    });
  });

  describe('#Compass', () => {
    it('should be an object', () => {
      expect(Faker.Compass).to.be.a('object');
    });
  });

  describe('#Crypto', () => {
    it('should be an object', () => {
      expect(Faker.Crypto).to.be.a('object');
    });
  });

  describe('#Date', () => {
    it('should be an object', () => {
      expect(Faker.Date).to.be.a('object');
    });
  });

  describe('#Demographic', () => {
    it('should be an object', () => {
      expect(Faker.Demographic).to.be.a('object');
    });
  });

  describe('#DragonBall', () => {
    it('should be an object', () => {
      expect(Faker.DragonBall).to.be.a('object');
    });
  });

  describe('#Educator', () => {
    it('should be an object', () => {
      expect(Faker.Educator).to.be.a('object');
    });
  });

  describe('#File', () => {
    it('should be an object', () => {
      expect(Faker.File).to.be.a('object');
    });
  });

  describe('#Fillmurray', () => {
    it('should be an object', () => {
      expect(Faker.Fillmurray).to.be.a('object');
    });
  });

  describe('#Food', () => {
    it('should be an object', () => {
      expect(Faker.Food).to.be.a('object');
    });
  });

  describe('#Friends', () => {
    it('should be an object', () => {
      expect(Faker.Friends).to.be.a('object');
    });
  });

  describe('#GameOfThrones', () => {
    it('should be an object', () => {
      expect(Faker.GameOfThrones).to.be.a('object');
    });
  });

  describe('#Hacker', () => {
    it('should be an object', () => {
      expect(Faker.Hacker).to.be.a('object');
    });
  });

  describe('#HarryPotter', () => {
    it('should be an object', () => {
      expect(Faker.HarryPotter).to.be.a('object');
    });
  });

  describe('#Hipster', () => {
    it('should be an object', () => {
      expect(Faker.Hipster).to.be.a('object');
    });
  });

  describe('#Internet', () => {
    it('should be an object', () => {
      expect(Faker.Internet).to.be.a('object');
    });
  });

  describe('#LordOfTheRings', () => {
    it('should be an object', () => {
      expect(Faker.LordOfTheRings).to.be.a('object');
    });
  });

  describe('#LoremFlickr', () => {
    it('should be an object', () => {
      expect(Faker.LoremFlickr).to.be.a('object');
    });
  });

  describe('#LoremPixel', () => {
    it('should be an object', () => {
      expect(Faker.LoremPixel).to.be.a('object');
    });
  });

  describe('#Lorem', () => {
    it('should be an object', () => {
      expect(Faker.Lorem).to.be.a('object');
    });
  });

  describe('#Matz', () => {
    it('should be an object', () => {
      expect(Faker.Matz).to.be.a('object');
    });
  });

  describe('#Music', () => {
    it('should be an object', () => {
      expect(Faker.Music).to.be.a('object');
    });
  });

  describe('#Name', () => {
    it('should be an object', () => {
      expect(Faker.Name).to.be.a('object');
    });
  });

  describe('#Number', () => {
    it('should be an object', () => {
      expect(Faker.Number).to.be.a('object');
    });
  });

  describe('#PhoneNumber', () => {
    it('should be an object', () => {
      expect(Faker.PhoneNumber).to.be.a('object');
    });
  });

  describe('#Placeholdit', () => {
    it('should be an object', () => {
      expect(Faker.Placeholdit).to.be.a('object');
    });
  });

  describe('#Pokemon', () => {
    it('should be an object', () => {
      expect(Faker.Pokemon).to.be.a('object');
    });
  });

  describe('#RickAndMorty', () => {
    it('should be an object', () => {
      expect(Faker.RickAndMorty).to.be.a('object');
    });
  });

  describe('#RockBand', () => {
    it('should be an object', () => {
      expect(Faker.RockBand).to.be.a('object');
    });
  });

  describe('#RuPaul', () => {
    it('should be an object', () => {
      expect(Faker.RuPaul).to.be.a('object');
    });
  });

  describe('#SlackEmoji', () => {
    it('should be an object', () => {
      expect(Faker.SlackEmoji).to.be.a('object');
    });
  });

  describe('#Space', () => {
    it('should be an object', () => {
      expect(Faker.Space).to.be.a('object');
    });
  });

  describe('#StarWars', () => {
    it('should be an object', () => {
      expect(Faker.StarWars).to.be.a('object');
    });
  });

  describe('#Superhero', () => {
    it('should be an object', () => {
      expect(Faker.Superhero).to.be.a('object');
    });
  });

  describe('#Team', () => {
    it('should be an object', () => {
      expect(Faker.Team).to.be.a('object');
    });
  });

  describe('#Time', () => {
    it('should be an object', () => {
      expect(Faker.Time).to.be.a('object');
    });
  });

  describe('#TwinPeaks', () => {
    it('should be an object', () => {
      expect(Faker.TwinPeaks).to.be.a('object');
    });
  });

  describe('#Twitter', () => {
    it('should be an object', () => {
      expect(Faker.Twitter).to.be.a('object');
    });
  });

  describe('#University', () => {
    it('should be an object', () => {
      expect(Faker.University).to.be.a('object');
    });
  });

  describe('#Vehicle', () => {
    it('should be an object', () => {
      expect(Faker.Vehicle).to.be.a('object');
    });
  });

  describe('#Zelda', () => {
    it('should be an object', () => {
      expect(Faker.Zelda).to.be.a('object');
    });
  });
});
<commit_msg>Added test to check that the faker has access to Random.<commit_after>'use strict';
const expect = require('chai').expect;
const Faker = require('../src/faker');

describe('#Faker', () => {
  it('should be an object', () => {
    expect(Faker).to.be.a('object');
  });

  describe('#Address', () => {
    it('should be an object', () => {
      expect(Faker.Address).to.be.a('object');
    });
  });

  describe('#Ancient', () => {
    it('should be an object', () => {
      expect(Faker.Ancient).to.be.a('object');
    });
  });

  describe('#App', () => {
    it('should be an object', () => {
      expect(Faker.App).to.be.a('object');
    });
  });

  describe('#Avatar', () => {
    it('should be an object', () => {
      expect(Faker.Avatar).to.be.a('object');
    });
  });

  describe('#Bank', () => {
    it('should be an object', () => {
      expect(Faker.Bank).to.be.a('object');
    });
  });

  describe('#Beer', () => {
    it('should be an object', () => {
      expect(Faker.Beer).to.be.a('object');
    });
  });

  describe('#Bitcoin', () => {
    it('should be an object', () => {
      expect(Faker.Bitcoin).to.be.a('object');
    });
  });

  describe('#Book', () => {
    it('should be an object', () => {
      expect(Faker.Book).to.be.a('object');
    });
  });

  describe('#Boolean', () => {
    it('should be an object', () => {
      expect(Faker.Boolean).to.be.a('object');
    });
  });

  describe('#Business', () => {
    it('should be an object', () => {
      expect(Faker.Business).to.be.a('object');
    });
  });

  describe('#Cat', () => {
    it('should be an object', () => {
      expect(Faker.Cat).to.be.a('object');
    });
  });

  describe('#ChuckNorris', () => {
    it('should be an object', () => {
      expect(Faker.ChuckNorris).to.be.a('object');
    });
  });

  describe('#Coffee', () => {
    it('should be an object', () => {
      expect(Faker.Coffee).to.be.a('object');
    });
  });

  describe('#Color', () => {
    it('should be an object', () => {
      expect(Faker.Color).to.be.a('object');
    });
  });

  describe('#Commerce', () => {
    it('should be an object', () => {
      expect(Faker.Commerce).to.be.a('object');
    });
  });

  describe('#Company', () => {
    it('should be an object', () => {
      expect(Faker.Company).to.be.a('object');
    });
  });

  describe('#Compass', () => {
    it('should be an object', () => {
      expect(Faker.Compass).to.be.a('object');
    });
  });

  describe('#Crypto', () => {
    it('should be an object', () => {
      expect(Faker.Crypto).to.be.a('object');
    });
  });

  describe('#Date', () => {
    it('should be an object', () => {
      expect(Faker.Date).to.be.a('object');
    });
  });

  describe('#Demographic', () => {
    it('should be an object', () => {
      expect(Faker.Demographic).to.be.a('object');
    });
  });

  describe('#DragonBall', () => {
    it('should be an object', () => {
      expect(Faker.DragonBall).to.be.a('object');
    });
  });

  describe('#Educator', () => {
    it('should be an object', () => {
      expect(Faker.Educator).to.be.a('object');
    });
  });

  describe('#File', () => {
    it('should be an object', () => {
      expect(Faker.File).to.be.a('object');
    });
  });

  describe('#Fillmurray', () => {
    it('should be an object', () => {
      expect(Faker.Fillmurray).to.be.a('object');
    });
  });

  describe('#Food', () => {
    it('should be an object', () => {
      expect(Faker.Food).to.be.a('object');
    });
  });

  describe('#Friends', () => {
    it('should be an object', () => {
      expect(Faker.Friends).to.be.a('object');
    });
  });

  describe('#GameOfThrones', () => {
    it('should be an object', () => {
      expect(Faker.GameOfThrones).to.be.a('object');
    });
  });

  describe('#Hacker', () => {
    it('should be an object', () => {
      expect(Faker.Hacker).to.be.a('object');
    });
  });

  describe('#HarryPotter', () => {
    it('should be an object', () => {
      expect(Faker.HarryPotter).to.be.a('object');
    });
  });

  describe('#Hipster', () => {
    it('should be an object', () => {
      expect(Faker.Hipster).to.be.a('object');
    });
  });

  describe('#Internet', () => {
    it('should be an object', () => {
      expect(Faker.Internet).to.be.a('object');
    });
  });

  describe('#LordOfTheRings', () => {
    it('should be an object', () => {
      expect(Faker.LordOfTheRings).to.be.a('object');
    });
  });

  describe('#LoremFlickr', () => {
    it('should be an object', () => {
      expect(Faker.LoremFlickr).to.be.a('object');
    });
  });

  describe('#LoremPixel', () => {
    it('should be an object', () => {
      expect(Faker.LoremPixel).to.be.a('object');
    });
  });

  describe('#Lorem', () => {
    it('should be an object', () => {
      expect(Faker.Lorem).to.be.a('object');
    });
  });

  describe('#Matz', () => {
    it('should be an object', () => {
      expect(Faker.Matz).to.be.a('object');
    });
  });

  describe('#Music', () => {
    it('should be an object', () => {
      expect(Faker.Music).to.be.a('object');
    });
  });

  describe('#Name', () => {
    it('should be an object', () => {
      expect(Faker.Name).to.be.a('object');
    });
  });

  describe('#Number', () => {
    it('should be an object', () => {
      expect(Faker.Number).to.be.a('object');
    });
  });

  describe('#PhoneNumber', () => {
    it('should be an object', () => {
      expect(Faker.PhoneNumber).to.be.a('object');
    });
  });

  describe('#Placeholdit', () => {
    it('should be an object', () => {
      expect(Faker.Placeholdit).to.be.a('object');
    });
  });

  describe('#Pokemon', () => {
    it('should be an object', () => {
      expect(Faker.Pokemon).to.be.a('object');
    });
  });

  describe('#Random', () => {
    it('should be an object', () => {
      expect(Faker.Random).to.be.a('object');
    });
  });

  describe('#RickAndMorty', () => {
    it('should be an object', () => {
      expect(Faker.RickAndMorty).to.be.a('object');
    });
  });

  describe('#RockBand', () => {
    it('should be an object', () => {
      expect(Faker.RockBand).to.be.a('object');
    });
  });

  describe('#RuPaul', () => {
    it('should be an object', () => {
      expect(Faker.RuPaul).to.be.a('object');
    });
  });

  describe('#SlackEmoji', () => {
    it('should be an object', () => {
      expect(Faker.SlackEmoji).to.be.a('object');
    });
  });

  describe('#Space', () => {
    it('should be an object', () => {
      expect(Faker.Space).to.be.a('object');
    });
  });

  describe('#StarWars', () => {
    it('should be an object', () => {
      expect(Faker.StarWars).to.be.a('object');
    });
  });

  describe('#Superhero', () => {
    it('should be an object', () => {
      expect(Faker.Superhero).to.be.a('object');
    });
  });

  describe('#Team', () => {
    it('should be an object', () => {
      expect(Faker.Team).to.be.a('object');
    });
  });

  describe('#Time', () => {
    it('should be an object', () => {
      expect(Faker.Time).to.be.a('object');
    });
  });

  describe('#TwinPeaks', () => {
    it('should be an object', () => {
      expect(Faker.TwinPeaks).to.be.a('object');
    });
  });

  describe('#Twitter', () => {
    it('should be an object', () => {
      expect(Faker.Twitter).to.be.a('object');
    });
  });

  describe('#University', () => {
    it('should be an object', () => {
      expect(Faker.University).to.be.a('object');
    });
  });

  describe('#Vehicle', () => {
    it('should be an object', () => {
      expect(Faker.Vehicle).to.be.a('object');
    });
  });

  describe('#Zelda', () => {
    it('should be an object', () => {
      expect(Faker.Zelda).to.be.a('object');
    });
  });
});
<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

var
  chai    = require( 'chai' ),
  should  = chai.should(),
  expect  = chai.expect,
  service = require( '../server' ),
  fetch   = require('../lib/fetch');

describe('Registry Fetch', function () {
  it('should fetch and return array of only audio components', function (done) {
    fetch(function (err, data) {
      expect(data).to.have.length(2);
      done();
    });
  });
});
<commit_msg>Update test to handle 3 mock comps<commit_after>process.env.NODE_ENV = 'test';

var
  chai    = require( 'chai' ),
  should  = chai.should(),
  expect  = chai.expect,
  service = require( '../server' ),
  fetch   = require('../lib/fetch');

describe('Registry Fetch', function () {
  it('should fetch and return array of only audio components', function (done) {
    fetch(function (err, data) {
      expect(data).to.have.length(3);
      done();
    });
  });
});
<|endoftext|>


<commit_before>FormViewCtrl.$inject = ['$scope', '$element'];
function FormViewCtrl($scope, $element) {

	DSViewCtrl('form', $scope, $element);

	var ds = $scope._dataSource;

	$scope.fields = {};
	$scope.fields_view = {};

	$scope.record = {};
	$scope.$$original = null;

	$scope._$events = {};

	/**
	 * Get field attributes.
	 *
	 * @param field field name or field element
	 */
	$scope.getViewDef = function(field) {
		var name = id = field,
			elem = $(field),
			attrs = {};

		if (_.isObject(field)) {  // assume element
			name = elem.attr('x-field') || elem.attr('data-field') || elem.attr('name');
			id = elem.attr('id') || name;
		}

		attrs = _.extend({}, $scope.fields[name], $scope.fields_view[id]);

		return attrs;
	};

	$scope.doRead = function(id) {
		var params = {
			fields : _.pluck($scope.fields, 'name')
		};
		return ds.read(id, params);
	};

	function doEdit(id) {
		return $scope.doRead(id).success(function(record){
			$scope.edit(record);
		});
	}

	$scope.onShow = function(viewPromise) {

		if (this._viewParams.recordId) {
			return doEdit(this._viewParams.recordId);
		}

		var page = ds.page(),
			record = null;

		if (page.index > -1) {
			record = ds.at(page.index);
		}
		viewPromise.then(function(){
			setTimeout(function(){
				if (record === undefined) {
					$scope.edit(null);
					$scope.$broadcast("on:new");
				}
				if (record && record.id)
					return doEdit(record.id);
				$scope.edit(record);
			});
		});
	};

	$scope.edit = function(record) {
		$scope.editRecord(record);
		$scope._viewPromise.then(function(){
			var events = $scope._$events;
			if (events.onLoad && record) {
				setTimeout(events.onLoad);
			}
		});
	};

	$scope.editRecord = function(record) {
		$scope.$$original = record || {};
		$scope.record = angular.copy($scope.$$original);
		setTimeout(function(){
			$scope.$apply();
			$scope.$broadcast("on:edit", $scope.record);
		});
	};

	function updateSelected(name, records) {
		var path = $scope.formPath ? $scope.formPath + '.' + name : name,
			child = $element.find('[x-path="' + path + '"]:first'),
			childScope = child.data('$scope');
		if (records == null || childScope == null)
			return records;

		var selected = childScope.selection || [],
			result = [];

		selected = _.map(selected, function(i){
			return childScope.dataView.getItem(i).id;
		});

		_.each(records, function(item){
			item = _.extend({}, item, {
				selected : _.contains(selected, item.id)
			});
			result.push(item);
		});

		return result;
	}

	$scope.getContext = function() {
		var context = _.extend({}, $scope.record);
		if ($scope.$parent && $scope.$parent.getContext) {
			context._parent = $scope.$parent.getContext();
		}

		_.each($scope.fields, function(field, name) {
			if (/-many$/.test(field.type)) {
				var items = updateSelected(field.name, context[name]);
				if (items) {
					context[name] = items;
				}
			}
		});
		context._model = ds._model;
		return context;
	};

	$scope.isDirty = function() {
		return !angular.equals($scope.record, $scope.$$original);
	};

	$scope.isValid = function() {
		return $scope.form && $scope.form.$valid;
	};

	$scope.canCopy = function() {
		return $scope.record && !$scope.isDirty() && $scope.record.id;
	};

	$scope.canSave = function() {
		return $scope.isDirty() && $scope.isValid();
	};

	$scope.onNew = function() {
		$scope.confirmDirty(function(){
			$scope.edit(null);
			$scope.$broadcast("on:new");
		});
	};

	$scope.$on("on:new", function(event){
		$scope._viewPromise.then(function(){
			var events = $scope._$events;
			if (events.onNew) {
				setTimeout(events.onNew);
			}
		});
	});

	$scope.onCopy = function() {
		var record = $scope.record;
		ds.copy(record.id).success(function(record){
			$scope.edit(record);
		});
	};

	$scope.onSave = function() {
		var events = $scope._$events,
			saveAction = events.onSave;

		function doSave() {
			ds.save($scope.record).success(function(record, page) {
				doEdit(record.id);
			});
		}

		if (saveAction) {
			saveAction().then(doSave);
		} else
			doSave();
	};

	$scope.confirmDirty = function(callback) {

		if (!$scope.isDirty())
			return callback();

		axelor.dialogs.confirm(_t("Current changes will be lost. Do you really want to proceed?"), function(confirmed){
			if (!confirmed)
				return;
			setTimeout(function(){
				$scope.$apply(function(){
					callback();
				});
			});
		});
	};

	$scope.onRefresh = function() {
		$scope.confirmDirty($scope.reload);
	};

	$scope.reload = function() {
		var record = $scope.record;
		if (record && record.id) {
			return doEdit(record.id);
		}
	};

	$scope.onCancel = function() {
		$scope.confirmDirty(function() {
			$scope.editRecord(null);
			$scope.switchTo('grid');
		});
	};

	$scope.onSearch = function() {
		$scope.onCancel();
	};

	$scope.pagerText = function() {
		var page = ds.page(),
			record = $scope.record || {};

		if (page && page.from !== undefined) {
			if (page.total == 0 || !record.id) return null;
			return _t("{0} of {1}", (page.from + page.index + 1), page.total);
		}
	},

	$scope.canNext = function() {
		var page = ds.page();
		return page.index < page.size - 1 || ds.canNext();
	};

	$scope.canPrev = function() {
		var page = ds.page();
		return page.index > 0 || ds.canPrev();
	};

	$scope.onNext = function() {
		$scope.confirmDirty(function() {
			ds.nextItem(function(record){
				if (record && record.id) doEdit(record.id);
			});
		});
	};

	$scope.onPrev = function() {
		$scope.confirmDirty(function() {
			ds.prevItem(function(record){
				if (record && record.id) doEdit(record.id);
			});
		});
	};
}

angular.module('axelor.ui').directive('uiViewForm', ['$compile', 'ViewService', function($compile, ViewService){

	function parse(scope, schema, fields, types) {

		var path = scope.formPath || "";

		function update(e, attrs) {
			_.each(attrs, function(v, k) {
				if (_.isUndefined(v)) return;
				e.attr(k, v);
			});
		}

		function process(items, parent) {

			$(items).each(function(){

				if (this.type == 'break') {
					return $('
').appendTo(parent);
				}

				if (this.type == 'field') {
					delete this.type;
				}

				var widget = this.widget || '',
					match = widget.match(/(\w+)(?:\[(.*?)\])/),
					attrs = {}, widgetAttrs = {};

				if (match) {
					widget = match[1];
					_.each(match[2].split(/\s*,\s*/), function(part) {
						var parts = part.split(/\s*=\s*/);
						attrs[parts[0]] = parts[1];
						widgetAttrs['x-' + parts[0]] = parts[1];
					});
				}

				var item = $('

').appendTo(parent),
					field = fields[this.name] || {},
					widgetId = _.uniqueId('_formWidget'),
					type = widget;

				attrs = angular.extend(attrs, field, this);
				type = types[widget] || types[attrs.type] || attrs.type || 'string';

				if (_.isArray(attrs.selection)) {
					type = 'select';
				}

				attrs.serverType = attrs.type;
				attrs.type = type;

				item.attr('ui-' + type, '');
				item.attr('id', widgetId);

				scope.fields_view[widgetId] = attrs;

				if (!_.isUndefined(attrs.noLabel)){
					attrs.showTitle = !attrs.noLabel;
				}

				//TODO: cover all attributes
				var _attrs = _.extend({}, attrs.attrs, this.attrs, widgetAttrs, {
						'name'			: attrs.name || this.name,
						'x-cols'		: this.cols,
						'x-colspan'		: this.colSpan,
						'x-rowspan'		: this.rowSpan,
						'x-widths'		: this.colWidths,
						'x-field'		: this.name,
						'x-title'		: attrs.title,
						'x-show-title'	: attrs.showTitle
					});

				if (attrs.required)
					_attrs['x-required'] = true;
				if (attrs.readonly)
					_attrs['x-readonly'] = true;

				if (_attrs.name) {
					_attrs['x-path'] = path ? path + "." + _attrs.name : _attrs.name;
				}

				update(item, _attrs);

				if (type == 'button' || type == 'static') {
					item.html(this.title);
				}

				if (/button|group|tabs|tab|separator|spacer|static/.test(type)) {
					item.attr('x-show-title', false);
				}

				var items = this.items || this.pages;
				if (items) {
					process(items, item);
					if (type != 'tabs') {
						item.attr('ui-table-layout', '');
					}
				}
			});
			return parent;
		}

		var elem = $('<form name="form" ui-form ui-table-layout ui-actions></form>');
		elem.attr('x-cols', schema.cols)
		  	.attr('x-widths', schema.colWidths);

		process(schema.items, elem);

		return elem;
	}

	return function(scope, element, attrs) {

		var loaded = false;

		function findItem(item) {
			var elem = item;
			if (_.isString(item))
				elem = $('#' + item);
			return elem ? $(elem) : null;
		}

		scope.setReadonly = function(item, readonly) {
			var flag = _.isUndefined(readonly) || readonly,
				elem = findItem(item),
				label, classOp;

			if (elem == null)
				return;

			label = elem.data('label') || $();
			classOp = flag ? 'addClass' : 'removeClass';

			elem.add(label)[classOp]('ui-state-disabled');

			if (elem.is(':input')) {
				return elem.attr('disabled', flag);
			}

			if (elem.is('.input-append')){
				return elem.find(':input').attr('disabled', flag)[classOp]('ui-state-disabled');
			}

			elem.find(':input, a').each(function(){
				var e = $(this);
				if (e.is('.ui-state-disabled')) {
					return;
				}
				if (e.is('a')) {
					if (e.attr('tabindex') !== -1) {
						return e.attr('tabindex', flag ? -2 : null);
					}
				}
				e.attr('disabled', flag);
			});

			var div = elem.children('.disabled-overlay');
			if (div.size() == 0) {
				div = $('

').click(function(e){
					handleNotebookTab(e, elem);
				});
				elem.append(div);
			}

			return flag ? div.show() : div.hide();
		};

		function handleNotebookTab(e, elem) {
			var elemOffset = elem.offset();
			elem.find('.nav.nav-tabs a').each(function(){
				var tab = $(this),
					offset = tab.offset(),
					x = offset.left - elemOffset.left,
					y = offset.top - elemOffset.top;
				if (e.offsetX > x && e.offsetX < x + tab.outerWidth() &&
					e.offsetY > y && e.offsetY < y + tab.outerHeight()) {
					tab.click();
				}
			});
		}

		scope.setHidden = function(item, hidden) {
			var flag = _.isUndefined(hidden) || hidden,
				elem = findItem(item), label, label_parent, parent;
			if (elem == null)
				return;
			label = elem.data('label') || $();
			label_parent = label.parent('td');
			parent = elem.parent('td');
			if (parent.size() == 0)
				parent = elem;
			if (label_parent.size())
				label = label_parent;
			return flag ? parent.add(label).hide() : parent.add(label).show();
		};

		scope.setRequired = function(item, required) {
			var flag = _.isUndefined(required) || required,
				elem = findItem(item), attrs, label;
			if (elem == null)
				return;
			attrs = elem.data('$attrs');
			label = elem.data('label') || $();
			if (label) {
				flag ? label.addClass('required') : label.removeClass('required');
			}
			if (attrs) {
				attrs.$set('required', flag);
			}
		};

		scope.$watch('schema', function(schema){

			if (schema == null || loaded)
				return;

			var form = parse(scope, schema, scope.fields, ViewService.FIELD_TYPES);

			form = $compile(form)(scope);
			element.append(form);

			if (scope._viewResolver) {
				scope._viewResolver.resolve(schema, element);
				scope.$broadcast("adjust:dialog");
			}

			loaded = true;
		});
	};
}]);
<commit_msg>Fixed spinner widget issue (disabled state).<commit_after>FormViewCtrl.$inject = ['$scope', '$element'];
function FormViewCtrl($scope, $element) {

	DSViewCtrl('form', $scope, $element);

	var ds = $scope._dataSource;

	$scope.fields = {};
	$scope.fields_view = {};

	$scope.record = {};
	$scope.$$original = null;

	$scope._$events = {};

	/**
	 * Get field attributes.
	 *
	 * @param field field name or field element
	 */
	$scope.getViewDef = function(field) {
		var name = id = field,
			elem = $(field),
			attrs = {};

		if (_.isObject(field)) {  // assume element
			name = elem.attr('x-field') || elem.attr('data-field') || elem.attr('name');
			id = elem.attr('id') || name;
		}

		attrs = _.extend({}, $scope.fields[name], $scope.fields_view[id]);

		return attrs;
	};

	$scope.doRead = function(id) {
		var params = {
			fields : _.pluck($scope.fields, 'name')
		};
		return ds.read(id, params);
	};

	function doEdit(id) {
		return $scope.doRead(id).success(function(record){
			$scope.edit(record);
		});
	}

	$scope.onShow = function(viewPromise) {

		if (this._viewParams.recordId) {
			return doEdit(this._viewParams.recordId);
		}

		var page = ds.page(),
			record = null;

		if (page.index > -1) {
			record = ds.at(page.index);
		}
		viewPromise.then(function(){
			setTimeout(function(){
				if (record === undefined) {
					$scope.edit(null);
					$scope.$broadcast("on:new");
				}
				if (record && record.id)
					return doEdit(record.id);
				$scope.edit(record);
			});
		});
	};

	$scope.edit = function(record) {
		$scope.editRecord(record);
		$scope._viewPromise.then(function(){
			var events = $scope._$events;
			if (events.onLoad && record) {
				setTimeout(events.onLoad);
			}
		});
	};

	$scope.editRecord = function(record) {
		$scope.$$original = record || {};
		$scope.record = angular.copy($scope.$$original);
		setTimeout(function(){
			$scope.$apply();
			$scope.$broadcast("on:edit", $scope.record);
		});
	};

	function updateSelected(name, records) {
		var path = $scope.formPath ? $scope.formPath + '.' + name : name,
			child = $element.find('[x-path="' + path + '"]:first'),
			childScope = child.data('$scope');
		if (records == null || childScope == null)
			return records;

		var selected = childScope.selection || [],
			result = [];

		selected = _.map(selected, function(i){
			return childScope.dataView.getItem(i).id;
		});

		_.each(records, function(item){
			item = _.extend({}, item, {
				selected : _.contains(selected, item.id)
			});
			result.push(item);
		});

		return result;
	}

	$scope.getContext = function() {
		var context = _.extend({}, $scope.record);
		if ($scope.$parent && $scope.$parent.getContext) {
			context._parent = $scope.$parent.getContext();
		}

		_.each($scope.fields, function(field, name) {
			if (/-many$/.test(field.type)) {
				var items = updateSelected(field.name, context[name]);
				if (items) {
					context[name] = items;
				}
			}
		});
		context._model = ds._model;
		return context;
	};

	$scope.isDirty = function() {
		return !angular.equals($scope.record, $scope.$$original);
	};

	$scope.isValid = function() {
		return $scope.form && $scope.form.$valid;
	};

	$scope.canCopy = function() {
		return $scope.record && !$scope.isDirty() && $scope.record.id;
	};

	$scope.canSave = function() {
		return $scope.isDirty() && $scope.isValid();
	};

	$scope.onNew = function() {
		$scope.confirmDirty(function(){
			$scope.edit(null);
			$scope.$broadcast("on:new");
		});
	};

	$scope.$on("on:new", function(event){
		$scope._viewPromise.then(function(){
			var events = $scope._$events;
			if (events.onNew) {
				setTimeout(events.onNew);
			}
		});
	});

	$scope.onCopy = function() {
		var record = $scope.record;
		ds.copy(record.id).success(function(record){
			$scope.edit(record);
		});
	};

	$scope.onSave = function() {
		var events = $scope._$events,
			saveAction = events.onSave;

		function doSave() {
			ds.save($scope.record).success(function(record, page) {
				doEdit(record.id);
			});
		}

		if (saveAction) {
			saveAction().then(doSave);
		} else
			doSave();
	};

	$scope.confirmDirty = function(callback) {

		if (!$scope.isDirty())
			return callback();

		axelor.dialogs.confirm(_t("Current changes will be lost. Do you really want to proceed?"), function(confirmed){
			if (!confirmed)
				return;
			setTimeout(function(){
				$scope.$apply(function(){
					callback();
				});
			});
		});
	};

	$scope.onRefresh = function() {
		$scope.confirmDirty($scope.reload);
	};

	$scope.reload = function() {
		var record = $scope.record;
		if (record && record.id) {
			return doEdit(record.id);
		}
	};

	$scope.onCancel = function() {
		$scope.confirmDirty(function() {
			$scope.editRecord(null);
			$scope.switchTo('grid');
		});
	};

	$scope.onSearch = function() {
		$scope.onCancel();
	};

	$scope.pagerText = function() {
		var page = ds.page(),
			record = $scope.record || {};

		if (page && page.from !== undefined) {
			if (page.total == 0 || !record.id) return null;
			return _t("{0} of {1}", (page.from + page.index + 1), page.total);
		}
	},

	$scope.canNext = function() {
		var page = ds.page();
		return page.index < page.size - 1 || ds.canNext();
	};

	$scope.canPrev = function() {
		var page = ds.page();
		return page.index > 0 || ds.canPrev();
	};

	$scope.onNext = function() {
		$scope.confirmDirty(function() {
			ds.nextItem(function(record){
				if (record && record.id) doEdit(record.id);
			});
		});
	};

	$scope.onPrev = function() {
		$scope.confirmDirty(function() {
			ds.prevItem(function(record){
				if (record && record.id) doEdit(record.id);
			});
		});
	};
}

angular.module('axelor.ui').directive('uiViewForm', ['$compile', 'ViewService', function($compile, ViewService){

	function parse(scope, schema, fields, types) {

		var path = scope.formPath || "";

		function update(e, attrs) {
			_.each(attrs, function(v, k) {
				if (_.isUndefined(v)) return;
				e.attr(k, v);
			});
		}

		function process(items, parent) {

			$(items).each(function(){

				if (this.type == 'break') {
					return $('
').appendTo(parent);
				}

				if (this.type == 'field') {
					delete this.type;
				}

				var widget = this.widget || '',
					match = widget.match(/(\w+)(?:\[(.*?)\])/),
					attrs = {}, widgetAttrs = {};

				if (match) {
					widget = match[1];
					_.each(match[2].split(/\s*,\s*/), function(part) {
						var parts = part.split(/\s*=\s*/);
						attrs[parts[0]] = parts[1];
						widgetAttrs['x-' + parts[0]] = parts[1];
					});
				}

				var item = $('

').appendTo(parent),
					field = fields[this.name] || {},
					widgetId = _.uniqueId('_formWidget'),
					type = widget;

				attrs = angular.extend(attrs, field, this);
				type = types[widget] || types[attrs.type] || attrs.type || 'string';

				if (_.isArray(attrs.selection)) {
					type = 'select';
				}

				attrs.serverType = attrs.type;
				attrs.type = type;

				item.attr('ui-' + type, '');
				item.attr('id', widgetId);

				scope.fields_view[widgetId] = attrs;

				if (!_.isUndefined(attrs.noLabel)){
					attrs.showTitle = !attrs.noLabel;
				}

				//TODO: cover all attributes
				var _attrs = _.extend({}, attrs.attrs, this.attrs, widgetAttrs, {
						'name'			: attrs.name || this.name,
						'x-cols'		: this.cols,
						'x-colspan'		: this.colSpan,
						'x-rowspan'		: this.rowSpan,
						'x-widths'		: this.colWidths,
						'x-field'		: this.name,
						'x-title'		: attrs.title,
						'x-show-title'	: attrs.showTitle
					});

				if (attrs.required)
					_attrs['x-required'] = true;
				if (attrs.readonly)
					_attrs['x-readonly'] = true;

				if (_attrs.name) {
					_attrs['x-path'] = path ? path + "." + _attrs.name : _attrs.name;
				}

				update(item, _attrs);

				if (type == 'button' || type == 'static') {
					item.html(this.title);
				}

				if (/button|group|tabs|tab|separator|spacer|static/.test(type)) {
					item.attr('x-show-title', false);
				}

				var items = this.items || this.pages;
				if (items) {
					process(items, item);
					if (type != 'tabs') {
						item.attr('ui-table-layout', '');
					}
				}
			});
			return parent;
		}

		var elem = $('<form name="form" ui-form ui-table-layout ui-actions></form>');
		elem.attr('x-cols', schema.cols)
		  	.attr('x-widths', schema.colWidths);

		process(schema.items, elem);

		return elem;
	}

	return function(scope, element, attrs) {

		var loaded = false;

		function findItem(item) {
			var elem = item;
			if (_.isString(item))
				elem = $('#' + item);
			return elem ? $(elem) : null;
		}

		scope.setReadonly = function(item, readonly) {
			var flag = _.isUndefined(readonly) || readonly,
				elem = findItem(item),
				label, classOp;

			if (elem == null)
				return;

			label = elem.data('label') || $();
			classOp = flag ? 'addClass' : 'removeClass';

			elem.add(label)[classOp]('ui-state-disabled');

			if (elem.is('.ui-spinner-input')) {
				return elem.spinner('option', 'disabled', flag);
			}
			if (elem.is(':input')) {
				return elem.attr('disabled', flag);
			}

			if (elem.is('.input-append')){
				return elem.find(':input').attr('disabled', flag)[classOp]('ui-state-disabled');
			}

			elem.find(':input, a').each(function(){
				var e = $(this);
				if (e.is('.ui-state-disabled')) {
					return;
				}
				if (e.is('a')) {
					if (e.attr('tabindex') !== -1) {
						return e.attr('tabindex', flag ? -2 : null);
					}
				}
				e.attr('disabled', flag);
			});

			var div = elem.children('.disabled-overlay');
			if (div.size() == 0) {
				div = $('

').click(function(e){
					handleNotebookTab(e, elem);
				});
				elem.append(div);
			}

			return flag ? div.show() : div.hide();
		};

		function handleNotebookTab(e, elem) {
			var elemOffset = elem.offset();
			elem.find('.nav.nav-tabs a').each(function(){
				var tab = $(this),
					offset = tab.offset(),
					x = offset.left - elemOffset.left,
					y = offset.top - elemOffset.top;
				if (e.offsetX > x && e.offsetX < x + tab.outerWidth() &&
					e.offsetY > y && e.offsetY < y + tab.outerHeight()) {
					tab.click();
				}
			});
		}

		scope.setHidden = function(item, hidden) {
			var flag = _.isUndefined(hidden) || hidden,
				elem = findItem(item), label, label_parent, parent;
			if (elem == null)
				return;
			label = elem.data('label') || $();
			label_parent = label.parent('td');
			parent = elem.parent('td');
			if (parent.size() == 0)
				parent = elem;
			if (label_parent.size())
				label = label_parent;
			return flag ? parent.add(label).hide() : parent.add(label).show();
		};

		scope.setRequired = function(item, required) {
			var flag = _.isUndefined(required) || required,
				elem = findItem(item), attrs, label;
			if (elem == null)
				return;
			attrs = elem.data('$attrs');
			label = elem.data('label') || $();
			if (label) {
				flag ? label.addClass('required') : label.removeClass('required');
			}
			if (attrs) {
				attrs.$set('required', flag);
			}
		};

		scope.$watch('schema', function(schema){

			if (schema == null || loaded)
				return;

			var form = parse(scope, schema, scope.fields, ViewService.FIELD_TYPES);

			form = $compile(form)(scope);
			element.append(form);

			if (scope._viewResolver) {
				scope._viewResolver.resolve(schema, element);
				scope.$broadcast("adjust:dialog");
			}

			loaded = true;
		});
	};
}]);
<|endoftext|>


<commit_before>/*
**  es6-features -- ECMAScript 6 Feature Overview & Comparison
**  Copyright (c) 2015 Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

let fs = require("fs")

/*  minimum Markdown translation ;-)  */
let md = txt => txt.replace(/`(.+?)`/g, "$1")

/*  generate JavaScript code block  */
let js = (clazz, title, code, icon) => {
    /*  protect special characters which are part of entity encoding  */
    code = code.replace(/&/g, "@1@")
    code = code.replace(/;/g, "@2@")

    /*  convert characters which have special meaning in HTML  */
    code = code.replace(/&/g, "&")
    code = code.replace(/</g, "<")
    code = code.replace(/>/g, ">")

    /*  unprotect special characters which are part of entity encoding  */
    code = code.replace(/@1@/g, "&")
    code = code.replace(/@2@([ \t]?\n|[ \t]+\|?\}|[ \t]+\/\/|$)/g, ";$1")
    code = code.replace(/@2@/g, ";")

    /*  convert ellipsis to corresponding Unicode character  */
    code = code.replace(/\.\.\./g, "…")

    /*  simple syntax-highlighting of JavaScript code, the rookie but sufficient way  */
    code = code.replace(
        /(\s=\s|=>|>|<|&|===|[%+*{}().,\[\]-])/g,
        "$1")
    code = code.replace(
        /("(?:.|\n)*?"|'(?:.|\n)*?'|`(?:.|\n)*?`|\d+(?:\.\d+)?(?!@))/g,
        "$1")
    code = code.replace(
        /\b(this|function|class(?=[^=])|extends|return|if|new|import|export|in|of|var|let|while|for|const)\b/g,
        "$1")
    code = code.replace(
        /((?:^|\s)\/\/[^\n]*)/g,
        "$1")
    code = code.replace(
        /\|(.+?)\|/g,
        "$1")
    code = code.replace(/@3@/g, "|");
    code = code.replace(/class=([a-z]+)/g, "class=\"$1\"")

    /*  extend title with style switcher  */
    title = "" + title + " — " +
        "syntactic sugar: reduced | " +
        "traditional"

    /*  assemble everything  */
    txt = `<div class="js ${clazz}">\n`
    txt += `    <div class="title">${title}</div>\n`
    txt += `    <div class="code">${code}</div>\n`
    txt += `    <i class="icon fa fa-circle"></i>\n`
    txt += `    <i class="icon fa fa-${icon}"></i>\n`
    txt += `</div>\n`

    return txt
}

/*  read the input source  */
let txt = fs.readFileSync("features.txt", "utf8")

/*  remove all comment lines  */
txt = txt.replace(/^#.*$/mg, "")

/*  iterate over input source  */
let nav = ""
let out = ""

/*  for every outer section...  */
nav += "
\n"
txt.replace(/\s*([^\n]+)\n====+[ \t]*\n((?:.|\n)+?)(?=[^\n]+\n====+[ \t]*\n|$)/g, (m, title, txt) => {
    /*  generate level-1 navigation entry  */
    nav += `<li class="title">${md(title)}\n`
    nav += "
\n"

    /*  for every inner section...  */
    txt.replace(/\s*([^\n]+)\n----+[ \t]*\n((?:.|\n)+?)(?=[^\n]+\n----+[ \t]*\n|$)/g, (m, subtitle, txt) => {
        let id = subtitle.replace(/[^a-zA-Z0-9]+/g, "")

        /*  generate level-2 navigation entry  */
        nav += `<li class="subtitle subtitle_${id}">\n`
        nav += `    <a href="#${id}">${md(subtitle)}</a> <i class="fa fa-arrow-circle-right"></i>`
        nav += "
\n"

        /*  generate showcase header  */
        out += `<div id="${id}" class="showcase showcase_${id}">`
        out += `    <div class="title">${md(title)}</div>\n`
        out += `    <div class="subtitle">${md(subtitle)}</div>\n`

        /*  for the showcode content...  */
        txt.replace(/^\s*((?:.|\n)+?)\n\n(6\|(?:.|\n)+?\n)\n(5\|(?:.|\n)+?)\s*$/, (m, desc, es6, es5) => {
            out += `    <div class="desc">${md(desc)}</div>\n`
            es6 = es6.replace(/^6\| ?/mg, "").replace(/^\s*/, "")
            es5 = es5.replace(/^5\| ?/mg, "").replace(/^\s*/, "")
            out += js("es6", "ECMAScript 6", es6, "check-circle")
            out += '

'
            out += js("es5", "ECMAScript 5", es5, "times-circle")
        })
        out += "
\n"
    })

    nav += "
\n"
    nav += "
\n"
})
nav += "
\n"

/*  read the HTML template  */
let tmpl = fs.readFileSync("features.html", "utf8")
tmpl = tmpl.replace(/%BODY%/, out).replace(/%NAV%/, nav)

/*  write the resulting HTML page  */
fs.writeFileSync("index.html", tmpl, "utf8")

<commit_msg>use ellipsis only in whitespace context<commit_after>/*
**  es6-features -- ECMAScript 6 Feature Overview & Comparison
**  Copyright (c) 2015 Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

let fs = require("fs")

/*  minimum Markdown translation ;-)  */
let md = txt => txt.replace(/`(.+?)`/g, "$1")

/*  generate JavaScript code block  */
let js = (clazz, title, code, icon) => {
    /*  protect special characters which are part of entity encoding  */
    code = code.replace(/&/g, "@1@")
    code = code.replace(/;/g, "@2@")

    /*  convert characters which have special meaning in HTML  */
    code = code.replace(/&/g, "&")
    code = code.replace(/</g, "<")
    code = code.replace(/>/g, ">")

    /*  unprotect special characters which are part of entity encoding  */
    code = code.replace(/@1@/g, "&")
    code = code.replace(/@2@([ \t]?\n|[ \t]+\|?\}|[ \t]+\/\/|$)/g, ";$1")
    code = code.replace(/@2@/g, ";")

    /*  convert ellipsis to corresponding Unicode character  */
    code = code.replace(/(\s+)\.\.\.(\s+)/g, "$1…$2")

    /*  simple syntax-highlighting of JavaScript code, the rookie but sufficient way  */
    code = code.replace(
        /(\s=\s|=>|>|<|&|===|[%+*{}().,\[\]-])/g,
        "$1")
    code = code.replace(
        /("(?:.|\n)*?"|'(?:.|\n)*?'|`(?:.|\n)*?`|\d+(?:\.\d+)?(?!@))/g,
        "$1")
    code = code.replace(
        /\b(this|function|class(?=[^=])|extends|return|if|new|import|export|in|of|var|let|while|for|const)\b/g,
        "$1")
    code = code.replace(
        /((?:^|\s)\/\/[^\n]*)/g,
        "$1")
    code = code.replace(
        /\|(.+?)\|/g,
        "$1")
    code = code.replace(/@3@/g, "|");
    code = code.replace(/class=([a-z]+)/g, "class=\"$1\"")

    /*  extend title with style switcher  */
    title = "" + title + " — " +
        "syntactic sugar: reduced | " +
        "traditional"

    /*  assemble everything  */
    txt = `<div class="js ${clazz}">\n`
    txt += `    <div class="title">${title}</div>\n`
    txt += `    <div class="code">${code}</div>\n`
    txt += `    <i class="icon fa fa-circle"></i>\n`
    txt += `    <i class="icon fa fa-${icon}"></i>\n`
    txt += `</div>\n`

    return txt
}

/*  read the input source  */
let txt = fs.readFileSync("features.txt", "utf8")

/*  remove all comment lines  */
txt = txt.replace(/^#.*$/mg, "")

/*  iterate over input source  */
let nav = ""
let out = ""

/*  for every outer section...  */
nav += "
\n"
txt.replace(/\s*([^\n]+)\n====+[ \t]*\n((?:.|\n)+?)(?=[^\n]+\n====+[ \t]*\n|$)/g, (m, title, txt) => {
    /*  generate level-1 navigation entry  */
    nav += `<li class="title">${md(title)}\n`
    nav += "
\n"

    /*  for every inner section...  */
    txt.replace(/\s*([^\n]+)\n----+[ \t]*\n((?:.|\n)+?)(?=[^\n]+\n----+[ \t]*\n|$)/g, (m, subtitle, txt) => {
        let id = subtitle.replace(/[^a-zA-Z0-9]+/g, "")

        /*  generate level-2 navigation entry  */
        nav += `<li class="subtitle subtitle_${id}">\n`
        nav += `    <a href="#${id}">${md(subtitle)}</a> <i class="fa fa-arrow-circle-right"></i>`
        nav += "
\n"

        /*  generate showcase header  */
        out += `<div id="${id}" class="showcase showcase_${id}">`
        out += `    <div class="title">${md(title)}</div>\n`
        out += `    <div class="subtitle">${md(subtitle)}</div>\n`

        /*  for the showcode content...  */
        txt.replace(/^\s*((?:.|\n)+?)\n\n(6\|(?:.|\n)+?\n)\n(5\|(?:.|\n)+?)\s*$/, (m, desc, es6, es5) => {
            out += `    <div class="desc">${md(desc)}</div>\n`
            es6 = es6.replace(/^6\| ?/mg, "").replace(/^\s*/, "")
            es5 = es5.replace(/^5\| ?/mg, "").replace(/^\s*/, "")
            out += js("es6", "ECMAScript 6", es6, "check-circle")
            out += '

'
            out += js("es5", "ECMAScript 5", es5, "times-circle")
        })
        out += "
\n"
    })

    nav += "
\n"
    nav += "
\n"
})
nav += "
\n"

/*  read the HTML template  */
let tmpl = fs.readFileSync("features.html", "utf8")
tmpl = tmpl.replace(/%BODY%/, out).replace(/%NAV%/, nav)

/*  write the resulting HTML page  */
fs.writeFileSync("index.html", tmpl, "utf8")

<|endoftext|>


<commit_before>// Router module

var userController = require('./user-controller'),
	dataController = require('./data-controller');

module.exports = function(app) {
	app.use('/user', function(req, res, next) {
		next();
	}, userController);

	app.use('/data', function(req, res, next) {
		next();
	}, dataController);
};<commit_msg>Is saal ka last commit<commit_after>// Router module

var userController = require('./user-controller'),
	dataController = require('./data-controller');

module.exports = function(app) {
	app.use('/user', userController);

	app.use('/data', dataController);
};<|endoftext|>


<commit_before>var assert = require('assert');
var Faire = require('../lib');
var async = require('async');

describe('Faire.Tasks API', function() {
	var user_id_1, user_id_2, user_id_3;
	before(function(done) {
		var email1 = 'tester@test.com';
		var passwrd1 = 'shdi2389chs98w3jnh';

		var email2 = 'getalltester@test.com';
		var passwrd2 = 'fsdoifushdf98w33h2';

		var email3 = 'hasnotasks@test.com';
		var passwrd3 = 'dskn2398fuisesSQ19';

		var virt_modules = [];
		virt_modules.push(Faire.Scurvy);

		var db = require('../lib/models');
		db.init(virt_modules, function() {
			console.log('-------- database setup complete --------');
			Faire.Scurvy.createUser({email: email1, passwrd: email2, status: 'active'}, function(err, userball1) {
				user_id_1 = userball1.user.id
				Faire.Scurvy.createUser({email: email2, passwrd: passwrd2, status: 'active'}, function(err, userball2) {
					user_id_2 = userball2.user.id;
					Faire.Scurvy.createUser({email: email3, passwrd: passwrd3, status: 'active'}, function(err, userball3) {
						user_id_3 = userball3.user.id;
						done();
					});
				});
			});
		});
	})
	describe('#add()', function() {
		it('should return the task object after adding it to the database.', function(done) {
			var taskName = 'This is an example task.';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				assert(err == null);
				assert(task !== undefined);
				assert(task.id !== undefined);
				assert(task.name !== undefined && task.name === taskName);
				assert(task.status !== undefined && task.status === 'active');
				done();
			})
		})
		it('should return the task object with a nondefault status after adding it to the database.', function(done) {
			var taskName = 'This is an example task2.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive }, function(err, task) {
				assert(err == null);
				assert(task !== undefined);
				assert(task.id !== undefined);
				assert(task.name !== undefined && task.name === taskName);
				assert(task.status !== undefined && task.status === status_inactive);
				done();
			})
		})
		it('should error out when required parameters "user" and "name" are missing.', function(done) {
			var taskName = 'This is an example task3.';
			Faire.Tasks.add({}, function(err, task) {
				assert(err instanceof Error);
				assert(task === undefined);
				done();
			})
		})
	})

	describe('#activate()', function() {
		it('should return the activated task object after activating it in the database.', function(done) {
			var taskName = 'This is an example task4.';
			var status_inactive = 'inactive';
			var status_active = 'active';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive  }, function(err, task) {
				Faire.Tasks.activate({ id: task.id, user: user_id_1}, function(err1, activatedTask) {
					assert(err1 == null);
					assert(activatedTask !== undefined);
					assert(activatedTask.id !== undefined && activatedTask.id === task.id);
					assert(activatedTask.name !== undefined && activatedTask.name === taskName);
					assert(activatedTask.status !== undefined && activatedTask.status === status_active);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task5.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.activate({}, function(err1, activatedTask1) {
					assert(err1 instanceof Error);
					assert(activatedTask1 === undefined);
					//missing user
					Faire.Tasks.activate({ id: task.id }, function(err2, activatedTask2) {
						assert(err2 instanceof Error);
						assert(activatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#inactivate()', function() {
		it('should return the inactivated task object after inactivating it in the database.', function(done) {
			var taskName = 'This is an example task6.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.inactivate({ id: task.id, user: user_id_1}, function(err1, inactivatedTask) {
					assert(err1 == null);
					assert(inactivatedTask !== undefined);
					assert(inactivatedTask.id !== undefined && inactivatedTask.id === task.id);
					assert(inactivatedTask.name !== undefined && inactivatedTask.name === taskName);
					assert(inactivatedTask.status !== undefined && inactivatedTask.status === status_inactive);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task7.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.inactivate({}, function(err1, inactivatedTask1) {
					assert(err1 instanceof Error);
					assert(inactivatedTask1 === undefined);
					//missing user
					Faire.Tasks.inactivate({ id: task.id }, function(err2, inactivatedTask2) {
						assert(err2 instanceof Error);
						assert(inactivatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#delete()', function() {
		it('should return the deleted task object after deleting it in the database.', function(done) {
			var taskName = 'This is an example task8.';
			var status_deleted = 'deleted';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.delete({ id: task.id, user: user_id_1}, function(err1, deletedTask) {
					assert(err1 == null);
					assert(deletedTask !== undefined);
					assert(deletedTask.id !== undefined && deletedTask.id === task.id);
					assert(deletedTask.name !== undefined && deletedTask.name === taskName);
					assert(deletedTask.status !== undefined && deletedTask.status === status_deleted);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task9.';
			var status_deleted = 'deleted';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.delete({}, function(err1, deletedTask1) {
					assert(err1 instanceof Error);
					assert(deletedTask1 === undefined);
					//missing user
					Faire.Tasks.delete({ id: task.id }, function(err2, deletedTask2) {
						assert(err2 instanceof Error);
						assert(deletedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#update()', function() {
		it('should return the updated task object after updating it in the database.', function(done) {
			var taskName = 'This is an example task10.';
			var updatedTaskName = 'This is task10 updated with something new';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.update({ id: task.id, user: user_id_1, name: updatedTaskName }, function(err1, updatedTask) {
					assert(err1 == null);
					assert(updatedTask !== undefined);
					assert(updatedTask.id !== undefined && updatedTask.id === task.id);
					assert(updatedTask.name !== undefined && updatedTask.name === updatedTaskName);
					assert(updatedTask.status !== undefined);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task11.';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.update({}, function(err1, updatedTask1) {
					assert(err1 instanceof Error);
					assert(updatedTask1 === undefined);
					//missing user
					Faire.Tasks.update({ id: task.id }, function(err2, updatedTask2) {
						assert(err2 instanceof Error);
						assert(updatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#get()', function() {
		it('should return the task object keyed by the given id. if the task does not exist, return empty', function(done) {
			var taskName = 'This is an example task12.';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.get({ id: task.id, user: user_id_1 }, function(err1, getTask) {
					assert(err1 == null);
					assert(getTask !== undefined);
					assert(getTask.id !== undefined && getTask.id === task.id);
					assert(getTask.name !== undefined && getTask.name === taskName);
					assert(getTask.status !== undefined);
					assert(getTask.updatedAt !== undefined);
					assert(getTask.createdAt !== undefined);

					Faire.Tasks.get({ id: 9999999, user: user_id_1 }, function(err2, getTask2) {
						assert(err2 == null);
						assert(getTask2 !== undefined);
						assert(getTask2.id === undefined);
					})
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task13.';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.get({}, function(err1, getTask1) {
					assert(err1 instanceof Error);
					assert(getTask1 === undefined);
					//missing user
					Faire.Tasks.get({ id: task.id }, function(err2, getTask2) {
						assert(err2 instanceof Error);
						assert(getTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#getAll()', function() {
		it('should return all tasks for a given user if no filters are applied. if there are no tasks for that user, return empty', function(done) {
			var taskName = 'This is an example task14.';
			Faire.Tasks.add({ user: user_id_2, name: taskName }, function(err, task) {
				Faire.Tasks.getAll({ user: user_id_2 }, function(err1, getAllTasks1) {
					assert(err1 == null);
					assert(getAllTasks1 !== undefined && Array.isArray(getAllTasks1) && getAllTasks1.length == 1);
					assert(getAllTasks1[0].id !== undefined && getAllTasks1[0].id === task.id);
					assert(getAllTasks1[0].name !== undefined && getAllTasks1[0].name === taskName);
					assert(getAllTasks1[0].status !== undefined);
					assert(getAllTasks1[0].updatedAt !== undefined);
					assert(getAllTasks1[0].createdAt !== undefined);

					//User 3 has no tasks
					Faire.Tasks.getAll({ user: user_id_3 }, function(err2, getAllTasks2) {
						assert(err2 == null);
						assert(getAllTasks2 !== undefined && Array.isArray(getAllTasks2) && getAllTasks2.length == 0);
						assert(getAllTasks2.id === undefined);
						done();
					})
				})
			})
		})
		it('should error out when required parameter "user" is missing.', function(done) {
			var taskName = 'This is an example task15.';
			Faire.Tasks.getAll({ }, function(err1, getAllTasks1) {
				assert(err1 instanceof Error);
				assert(getAllTasks1 === undefined);
				done();
			})
		})
	})
})
<commit_msg>Fix a logic error in a test.<commit_after>var assert = require('assert');
var Faire = require('../lib');
var async = require('async');

describe('Faire.Tasks API', function() {
	var user_id_1, user_id_2, user_id_3;
	before(function(done) {
		var email1 = 'tester@test.com';
		var passwrd1 = 'shdi2389chs98w3jnh';

		var email2 = 'getalltester@test.com';
		var passwrd2 = 'fsdoifushdf98w33h2';

		var email3 = 'hasnotasks@test.com';
		var passwrd3 = 'dskn2398fuisesSQ19';

		var virt_modules = [];
		virt_modules.push(Faire.Scurvy);

		var db = require('../lib/models');
		db.init(virt_modules, function() {
			console.log('-------- database setup complete --------');
			Faire.Scurvy.createUser({email: email1, passwrd: email2, status: 'active'}, function(err, userball1) {
				user_id_1 = userball1.user.id
				Faire.Scurvy.createUser({email: email2, passwrd: passwrd2, status: 'active'}, function(err, userball2) {
					user_id_2 = userball2.user.id;
					Faire.Scurvy.createUser({email: email3, passwrd: passwrd3, status: 'active'}, function(err, userball3) {
						user_id_3 = userball3.user.id;
						done();
					});
				});
			});
		});
	})
	describe('#add()', function() {
		it('should return the task object after adding it to the database.', function(done) {
			var taskName = 'This is an example task.';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				assert(err == null);
				assert(task !== undefined);
				assert(task.id !== undefined);
				assert(task.name !== undefined && task.name === taskName);
				assert(task.status !== undefined && task.status === 'active');
				done();
			})
		})
		it('should return the task object with a nondefault status after adding it to the database.', function(done) {
			var taskName = 'This is an example task2.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive }, function(err, task) {
				assert(err == null);
				assert(task !== undefined);
				assert(task.id !== undefined);
				assert(task.name !== undefined && task.name === taskName);
				assert(task.status !== undefined && task.status === status_inactive);
				done();
			})
		})
		it('should error out when required parameters "user" and "name" are missing.', function(done) {
			var taskName = 'This is an example task3.';
			Faire.Tasks.add({}, function(err, task) {
				assert(err instanceof Error);
				assert(task === undefined);
				done();
			})
		})
	})

	describe('#activate()', function() {
		it('should return the activated task object after activating it in the database.', function(done) {
			var taskName = 'This is an example task4.';
			var status_inactive = 'inactive';
			var status_active = 'active';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive  }, function(err, task) {
				Faire.Tasks.activate({ id: task.id, user: user_id_1}, function(err1, activatedTask) {
					assert(err1 == null);
					assert(activatedTask !== undefined);
					assert(activatedTask.id !== undefined && activatedTask.id === task.id);
					assert(activatedTask.name !== undefined && activatedTask.name === taskName);
					assert(activatedTask.status !== undefined && activatedTask.status === status_active);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task5.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName, status: status_inactive  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.activate({}, function(err1, activatedTask1) {
					assert(err1 instanceof Error);
					assert(activatedTask1 === undefined);
					//missing user
					Faire.Tasks.activate({ id: task.id }, function(err2, activatedTask2) {
						assert(err2 instanceof Error);
						assert(activatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#inactivate()', function() {
		it('should return the inactivated task object after inactivating it in the database.', function(done) {
			var taskName = 'This is an example task6.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.inactivate({ id: task.id, user: user_id_1}, function(err1, inactivatedTask) {
					assert(err1 == null);
					assert(inactivatedTask !== undefined);
					assert(inactivatedTask.id !== undefined && inactivatedTask.id === task.id);
					assert(inactivatedTask.name !== undefined && inactivatedTask.name === taskName);
					assert(inactivatedTask.status !== undefined && inactivatedTask.status === status_inactive);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task7.';
			var status_inactive = 'inactive';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.inactivate({}, function(err1, inactivatedTask1) {
					assert(err1 instanceof Error);
					assert(inactivatedTask1 === undefined);
					//missing user
					Faire.Tasks.inactivate({ id: task.id }, function(err2, inactivatedTask2) {
						assert(err2 instanceof Error);
						assert(inactivatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#delete()', function() {
		it('should return the deleted task object after deleting it in the database.', function(done) {
			var taskName = 'This is an example task8.';
			var status_deleted = 'deleted';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.delete({ id: task.id, user: user_id_1}, function(err1, deletedTask) {
					assert(err1 == null);
					assert(deletedTask !== undefined);
					assert(deletedTask.id !== undefined && deletedTask.id === task.id);
					assert(deletedTask.name !== undefined && deletedTask.name === taskName);
					assert(deletedTask.status !== undefined && deletedTask.status === status_deleted);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task9.';
			var status_deleted = 'deleted';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.delete({}, function(err1, deletedTask1) {
					assert(err1 instanceof Error);
					assert(deletedTask1 === undefined);
					//missing user
					Faire.Tasks.delete({ id: task.id }, function(err2, deletedTask2) {
						assert(err2 instanceof Error);
						assert(deletedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#update()', function() {
		it('should return the updated task object after updating it in the database.', function(done) {
			var taskName = 'This is an example task10.';
			var updatedTaskName = 'This is task10 updated with something new';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.update({ id: task.id, user: user_id_1, name: updatedTaskName }, function(err1, updatedTask) {
					assert(err1 == null);
					assert(updatedTask !== undefined);
					assert(updatedTask.id !== undefined && updatedTask.id === task.id);
					assert(updatedTask.name !== undefined && updatedTask.name === updatedTaskName);
					assert(updatedTask.status !== undefined);
					done();
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task11.';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.update({}, function(err1, updatedTask1) {
					assert(err1 instanceof Error);
					assert(updatedTask1 === undefined);
					//missing user
					Faire.Tasks.update({ id: task.id }, function(err2, updatedTask2) {
						assert(err2 instanceof Error);
						assert(updatedTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#get()', function() {
		it('should return the task object keyed by the given id. if the task does not exist, return empty', function(done) {
			var taskName = 'This is an example task12.';
			Faire.Tasks.add({ user: user_id_1, name: taskName }, function(err, task) {
				Faire.Tasks.get({ id: task.id, user: user_id_1 }, function(err1, getTask) {
					assert(err1 == null);
					assert(getTask !== undefined);
					assert(getTask.id !== undefined && getTask.id === task.id);
					assert(getTask.name !== undefined && getTask.name === taskName);
					assert(getTask.status !== undefined);
					assert(getTask.updatedAt !== undefined);
					assert(getTask.createdAt !== undefined);

					Faire.Tasks.get({ id: 9999999, user: user_id_1 }, function(err2, getTask2) {
						assert(err2 == null);
						assert(getTask2 !== undefined);
						assert(getTask2.id === undefined);
						done();
					})
				})
			})
		})
		it('should error out when required parameters "user" and "id" are missing.', function(done) {
			var taskName = 'This is an example task13.';
			Faire.Tasks.add({ user: user_id_1, name: taskName  }, function(err, task) {
				//missing both user and id
				Faire.Tasks.get({}, function(err1, getTask1) {
					assert(err1 instanceof Error);
					assert(getTask1 === undefined);
					//missing user
					Faire.Tasks.get({ id: task.id }, function(err2, getTask2) {
						assert(err2 instanceof Error);
						assert(getTask2 === undefined);
						done();
					})

				})
			})
		})
	})

	describe('#getAll()', function() {
		it('should return all tasks for a given user if no filters are applied. if there are no tasks for that user, return empty', function(done) {
			var taskName = 'This is an example task14.';
			Faire.Tasks.add({ user: user_id_2, name: taskName }, function(err, task) {
				Faire.Tasks.getAll({ user: user_id_2 }, function(err1, getAllTasks1) {
					assert(err1 == null);
					assert(getAllTasks1 !== undefined && Array.isArray(getAllTasks1) && getAllTasks1.length == 1);
					assert(getAllTasks1[0].id !== undefined && getAllTasks1[0].id === task.id);
					assert(getAllTasks1[0].name !== undefined && getAllTasks1[0].name === taskName);
					assert(getAllTasks1[0].status !== undefined);
					assert(getAllTasks1[0].updatedAt !== undefined);
					assert(getAllTasks1[0].createdAt !== undefined);

					//User 3 has no tasks
					Faire.Tasks.getAll({ user: user_id_3 }, function(err2, getAllTasks2) {
						assert(err2 == null);
						assert(getAllTasks2 !== undefined && Array.isArray(getAllTasks2) && getAllTasks2.length == 0);
						assert(getAllTasks2.id === undefined);
						done();
					})
				})
			})
		})
		it('should error out when required parameter "user" is missing.', function(done) {
			var taskName = 'This is an example task15.';
			Faire.Tasks.getAll({ }, function(err1, getAllTasks1) {
				assert(err1 instanceof Error);
				assert(getAllTasks1 === undefined);
				done();
			})
		})
	})
})
<|endoftext|>


<commit_before>const db = require('sqlite')
const KoaRouter = require('koa-router')
const Providers = require('../../providers')
const getPrefs = require('../socket/prefs').getPrefs

const router = KoaRouter()
const debug = require('debug')
const log = debug('app:library')
const error = debug('app:library:error')

// call media provider for song
router.get('/api/provider/:provider/:method', async (ctx, next) => {
  const { provider, method } = ctx.params
  let cfg

  if (! Providers[provider]) {
    ctx.status = 404
    return ctx.body = `Provider "${provider}" not found`
  }

  if (! Providers[provider][method]) {
    ctx.status = 404
    return ctx.body = `Method "${method}" not found in provider "${provider}"`
  }

  // get provider config
  try {
    cfg = await getPrefs('provider.'+provider)
  } catch(err) {
    return Promise.reject(err)
  }

  if (!cfg.enabled) {
    ctx.status = 401
    return ctx.body = `Provider "${provider}" not enabled`
  }

  log(`Calling "${method}" method of "${provider}" provider`)
  await Providers[provider][method](ctx, cfg)
})

// list providers and their configuration
router.get('/api/provider', async (ctx, next) => {
  let cfg = {}

  // get provider config
  let rows = await db.all('SELECT * FROM config WHERE domain LIKE "%.provider"')

  rows.forEach(function(row){
    cfg[row.domain] = JSON.parse(row.data)
  })

  return ctx.body = cfg
})

module.exports = router
<commit_msg>Remove dead endpoint<commit_after>const db = require('sqlite')
const KoaRouter = require('koa-router')
const Providers = require('../../providers')
const getPrefs = require('../socket/prefs').getPrefs

const router = KoaRouter()
const debug = require('debug')
const log = debug('app:library')
const error = debug('app:library:error')

// call media provider for song
router.get('/api/provider/:provider/:method', async (ctx, next) => {
  const { provider, method } = ctx.params
  let cfg

  if (! Providers[provider]) {
    ctx.status = 404
    return ctx.body = `Provider "${provider}" not found`
  }

  if (! Providers[provider][method]) {
    ctx.status = 404
    return ctx.body = `Method "${method}" not found in provider "${provider}"`
  }

  // get provider config
  try {
    cfg = await getPrefs('provider.'+provider)
  } catch(err) {
    return Promise.reject(err)
  }

  if (!cfg.enabled) {
    ctx.status = 401
    return ctx.body = `Provider "${provider}" not enabled`
  }

  log(`Calling "${method}" method of "${provider}" provider`)
  await Providers[provider][method](ctx, cfg)
})

module.exports = router
<|endoftext|>


<commit_before>var HomeController = Class('HomeController')({
  prototype : {
    init : function (){
      this._initRouter();
      return this;
    },

    _initRouter : function() {
      router.route('/')
        .get(this.index);
    },

    index : function(req, res) {
      // res.sendFile('views/index.html', {'root': __dirname + '/..'});
      res.render('home/index.ejs');
    }
  }
});

module.exports = new HomeController();
<commit_msg>Remove comment<commit_after>var HomeController = Class('HomeController')({
  prototype : {
    init : function (){
      this._initRouter();
      return this;
    },

    _initRouter : function() {
      router.route('/')
        .get(this.index);
    },

    index : function(req, res) {
      res.render('home/index.ejs');
    }
  }
});

module.exports = new HomeController();
<|endoftext|>


<commit_before>require('../support');

var expect = require('chai').expect;
var loopback = require('loopback');
var request = require('supertest');

var loopbackJsonSchema = require('../../index');
var JsonSchema = require('../../lib/models/json-schema');
var jsonSchemaMiddleware = require('../../lib/middleware/json-schema.middleware');

var app = loopback();
app.set('restApiRoot', '/api');
app.use(app.get('restApiRoot'), jsonSchemaMiddleware());
loopbackJsonSchema.init(app);
app.installMiddleware();

describe('GET /collection-schemas/:schemaId', function () {
   describe('when item schema exists', function () {
        var jsonSchemaId;

        beforeEach(function (done) {
            JsonSchema.create({
                modelName: 'person',
                collectionName: 'people',
                title: 'Person',
                collectionTitle: 'People',
                type: 'object',
                properties: {}
            }, function(err, jsonSchema) {
                if (err) { throw err };
                jsonSchemaId = jsonSchema.id;
                done();
            });
        });

        it('should return Collection schema', function (done) {
            request(app)
                .get('/api/collection-schemas/' + jsonSchemaId)
                .expect(200)
                .end(function (err, res) {
                    if (err) { throw err };
                    expect(res.body).to.not.be.empty;
                    expect(res.body).to.include.keys(['$schema', 'title', 'type', 'items']);
                    done();
            });
        });
    });

   describe('when item schema does not exist', function () {
        it('should return 404', function (done) {
            request(app)
                .get('/api/collection-schemas/invalid-schema-id')
                .expect(404)
                .end(function (err, res) {
                    if (err) { throw err };
                    expect(res.body).to.not.be.emtpy;
                    done();
            });
        });
    });
});<commit_msg>Links in GET collection-schemas acceptance test.<commit_after>require('../support');

var expect = require('chai').expect;
var loopback = require('loopback');
var request = require('supertest');

var loopbackJsonSchema = require('../../index');
var JsonSchema = require('../../lib/models/json-schema');
var jsonSchemaMiddleware = require('../../lib/middleware/json-schema.middleware');

var app = loopback();
app.set('restApiRoot', '/api');
app.use(app.get('restApiRoot'), jsonSchemaMiddleware());
loopbackJsonSchema.init(app);
app.installMiddleware();

describe('GET /collection-schemas/:schemaId', function () {
   describe('when item schema exists', function () {
        var jsonSchemaId;

        beforeEach(function (done) {
            JsonSchema.create({
                modelName: 'person',
                collectionName: 'people',
                title: 'Person',
                collectionTitle: 'People',
                type: 'object',
                properties: {}
            }, function(err, jsonSchema) {
                if (err) { throw err };
                jsonSchemaId = jsonSchema.id;
                done();
            });
        });

        it('should return Collection schema', function (done) {
            request(app)
                .get('/api/collection-schemas/' + jsonSchemaId)
                .expect(200)
                .end(function (err, res) {
                    if (err) { throw err };
                    expect(res.body).to.not.be.empty;
                    expect(res.body).to.include.keys(['$schema', 'title', 'type', 'items', 'links']);
                    done();
            });
        });
    });

   describe('when item schema does not exist', function () {
        it('should return 404', function (done) {
            request(app)
                .get('/api/collection-schemas/invalid-schema-id')
                .expect(404)
                .end(function (err, res) {
                    if (err) { throw err };
                    expect(res.body).to.not.be.emtpy;
                    done();
            });
        });
    });
});<|endoftext|>