<commit_before>describe('Functional', function() {
  var data, bindData, el, input;

  beforeEach(function() {
    data = new Data({foo: 'bar', items: [{name: 'a'}, {name: 'b'}]});
    bindData = {data: data};
    el = document.createElement('div');
    input = document.createElement('input');
    input.setAttribute('type', 'text');

    rivets.configure({
      preloadData: true,
      adapter: {
        subscribe: function(obj, keypath, callback) {
          obj.on(keypath, callback);
        },
        read: function(obj, keypath) {
          return obj.get(keypath);
        },
        publish: function(obj, keypath, value) {
          attributes = {};
          attributes[keypath] = value;
          obj.set(attributes);
        }
      }
    });
  });

  describe('Adapter', function() {
    it('should read the initial value', function() {
      spyOn(data, 'get');
      el.setAttribute('data-text', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.get).toHaveBeenCalledWith('foo');
    });

    it('should read the initial value unless preloadData is false', function() {
      rivets.configure({preloadData: false});
      spyOn(data, 'get');
      el.setAttribute('data-value', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.get).not.toHaveBeenCalled();
    });

    it('should subscribe to updates', function() {
      spyOn(data, 'on');
      el.setAttribute('data-value', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.on).toHaveBeenCalled();
    });
  });

  describe('Binds', function() {
    describe('Text', function() {
      it('should set the text content of the element', function() {
        el.setAttribute('data-text', 'data.foo');
        rivets.bind(el, bindData);
        expect(el.textContent || el.innerText).toBe(data.get('foo'));
      });

      it('should correctly handle HTML in the content', function() {
        el.setAttribute('data-text', 'data.foo');
        value = 'Fail';
        data.set({foo: value});
        rivets.bind(el, bindData);
        expect(el.textContent || el.innerText).toBe(value);
      });
    });

    describe('HTML', function() {
      it('should set the html content of the element', function() {
        el.setAttribute('data-html', 'data.foo');
        rivets.bind(el, bindData);
        expect(el).toHaveTheTextContent(data.get('foo'));
      });

      it('should correctly handle HTML in the content', function() {
        el.setAttribute('data-html', 'data.foo');
        value = 'Fail';
        data.set({foo: value});
        rivets.bind(el, bindData);
        expect(el.innerHTML).toBe(value);
      });
    });

    describe('Value', function() {
      it('should set the value of the element', function() {
        input.setAttribute('data-value', 'data.foo');
        rivets.bind(input, bindData);
        expect(input.value).toBe(data.get('foo'));
      });
    });

    describe('Multiple', function() {
      it('should bind a list of multiple elements', function() {
        el.setAttribute('data-html', 'data.foo');
        input.setAttribute('data-value', 'data.foo');
        rivets.bind([el, input], bindData);
        expect(el).toHaveTheTextContent(data.get('foo'));
        expect(input.value).toBe(data.get('foo'));
      });
    });

    describe('Iteration', function() {
      beforeEach(function(){
        list = document.createElement('ul');
        el.appendChild(list);
        listItem = document.createElement('li');
        listItem.setAttribute('data-each-item', 'data.items');
        list.appendChild(listItem);
      });

      it('should loop over a collection and create new instances of that element + children', function() {
        expect(el.getElementsByTagName('li').length).toBe(1);
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li').length).toBe(2);
      });

      it('should re-loop over the collection and create new instances when the array changes', function() {
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li').length).toBe(2);

        newItems = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
        data.set({items: newItems});
        expect(el.getElementsByTagName('li').length).toBe(3);
      });

      it('should allow binding to the iterated item as well as any parent contexts', function() {
        span1 = document.createElement('span');
        span1.setAttribute('data-text', 'item:name')
        span2 = document.createElement('span');
        span2.setAttribute('data-text', 'data.foo')
        listItem.appendChild(span1);
        listItem.appendChild(span2);

        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('span')[0]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('span')[1]).toHaveTheTextContent('bar');
      });

      it('should allow binding to the iterated element directly', function() {
        listItem.setAttribute('data-text', 'item:name');
        listItem.setAttribute('data-class', 'data.foo');
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('li')[0].className).toBe('bar');
      });

      it('should insert items between any surrounding elements', function(){
        firstItem = document.createElement('li');
        lastItem = document.createElement('li');
        firstItem.textContent = 'first';
        lastItem.textContent = 'last';
        list.appendChild(lastItem);
        list.insertBefore(firstItem, listItem);

        listItem.setAttribute('data-text', 'item:name');

        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('first');
        expect(el.getElementsByTagName('li')[1]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('li')[2]).toHaveTheTextContent('b');
        expect(el.getElementsByTagName('li')[3]).toHaveTheTextContent('last');
      })
    });
  });

  describe('Updates', function() {
    it('should change the value', function() {
      el.setAttribute('data-text', 'data.foo');
      rivets.bind(el, bindData);
      data.set({foo: 'some new value'});
      expect(el).toHaveTheTextContent(data.get('foo'));
    });
  });

  describe('Input', function() {
    it('should update the model value', function() {
      input.setAttribute('data-value', 'data.foo');
      rivets.bind(input, bindData);
      input.value = 'some new value';
      var event = document.createEvent('HTMLEvents')
      event.initEvent('change', true, true);
      input.dispatchEvent(event);
      expect(input.value).toBe(data.get('foo'));
    });
  });
});
<commit_msg>adds test to #110 so that we can close it out [Closes #110]<commit_after>describe('Functional', function() {
  var data, bindData, el, input;

  beforeEach(function() {
    data = new Data({foo: 'bar', items: [{name: 'a'}, {name: 'b'}]});
    bindData = {data: data};
    el = document.createElement('div');
    input = document.createElement('input');
    input.setAttribute('type', 'text');

    rivets.configure({
      preloadData: true,
      adapter: {
        subscribe: function(obj, keypath, callback) {
          obj.on(keypath, callback);
        },
        read: function(obj, keypath) {
          return obj.get(keypath);
        },
        publish: function(obj, keypath, value) {
          attributes = {};
          attributes[keypath] = value;
          obj.set(attributes);
        }
      }
    });
  });

  describe('Adapter', function() {
    it('should read the initial value', function() {
      spyOn(data, 'get');
      el.setAttribute('data-text', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.get).toHaveBeenCalledWith('foo');
    });

    it('should read the initial value unless preloadData is false', function() {
      rivets.configure({preloadData: false});
      spyOn(data, 'get');
      el.setAttribute('data-value', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.get).not.toHaveBeenCalled();
    });

    it('should subscribe to updates', function() {
      spyOn(data, 'on');
      el.setAttribute('data-value', 'data.foo');
      rivets.bind(el, bindData);
      expect(data.on).toHaveBeenCalled();
    });
  });

  describe('Binds', function() {
    describe('Text', function() {
      it('should set the text content of the element', function() {
        el.setAttribute('data-text', 'data.foo');
        rivets.bind(el, bindData);
        expect(el.textContent || el.innerText).toBe(data.get('foo'));
      });

      it('should correctly handle HTML in the content', function() {
        el.setAttribute('data-text', 'data.foo');
        value = 'Fail';
        data.set({foo: value});
        rivets.bind(el, bindData);
        expect(el.textContent || el.innerText).toBe(value);
      });
    });

    describe('HTML', function() {
      it('should set the html content of the element', function() {
        el.setAttribute('data-html', 'data.foo');
        rivets.bind(el, bindData);
        expect(el).toHaveTheTextContent(data.get('foo'));
      });

      it('should correctly handle HTML in the content', function() {
        el.setAttribute('data-html', 'data.foo');
        value = 'Fail';
        data.set({foo: value});
        rivets.bind(el, bindData);
        expect(el.innerHTML).toBe(value);
      });
    });

    describe('Value', function() {
      it('should set the value of the element', function() {
        input.setAttribute('data-value', 'data.foo');
        rivets.bind(input, bindData);
        expect(input.value).toBe(data.get('foo'));
      });
    });

    describe('Multiple', function() {
      it('should bind a list of multiple elements', function() {
        el.setAttribute('data-html', 'data.foo');
        input.setAttribute('data-value', 'data.foo');
        rivets.bind([el, input], bindData);
        expect(el).toHaveTheTextContent(data.get('foo'));
        expect(input.value).toBe(data.get('foo'));
      });
    });

    describe('Iteration', function() {
      beforeEach(function(){
        list = document.createElement('ul');
        el.appendChild(list);
        listItem = document.createElement('li');
        listItem.setAttribute('data-each-item', 'data.items');
        list.appendChild(listItem);
      });

      it('should loop over a collection and create new instances of that element + children', function() {
        expect(el.getElementsByTagName('li').length).toBe(1);
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li').length).toBe(2);
      });

      it('should not fail if the collection being bound to is null', function() {
        data.set({ items: null});
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li').length).toBe(0);
      });

      it('should re-loop over the collection and create new instances when the array changes', function() {
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li').length).toBe(2);

        newItems = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
        data.set({items: newItems});
        expect(el.getElementsByTagName('li').length).toBe(3);
      });

      it('should allow binding to the iterated item as well as any parent contexts', function() {
        span1 = document.createElement('span');
        span1.setAttribute('data-text', 'item:name')
        span2 = document.createElement('span');
        span2.setAttribute('data-text', 'data.foo')
        listItem.appendChild(span1);
        listItem.appendChild(span2);

        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('span')[0]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('span')[1]).toHaveTheTextContent('bar');
      });

      it('should allow binding to the iterated element directly', function() {
        listItem.setAttribute('data-text', 'item:name');
        listItem.setAttribute('data-class', 'data.foo');
        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('li')[0].className).toBe('bar');
      });

      /*
      it('should insert items between any surrounding elements', function(){
        firstItem = document.createElement('li');
        lastItem = document.createElement('li');
        firstItem.textContent = 'first';
        lastItem.textContent = 'last';
        list.appendChild(lastItem);
        list.insertBefore(firstItem, listItem);

        listItem.setAttribute('data-text', 'item:name');

        rivets.bind(el, bindData);
        expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('first');
        expect(el.getElementsByTagName('li')[1]).toHaveTheTextContent('a');
        expect(el.getElementsByTagName('li')[2]).toHaveTheTextContent('b');
        expect(el.getElementsByTagName('li')[3]).toHaveTheTextContent('last');
      })*/

    });
  });

  describe('Updates', function() {
    it('should change the value', function() {
      el.setAttribute('data-text', 'data.foo');
      rivets.bind(el, bindData);
      data.set({foo: 'some new value'});
      expect(el).toHaveTheTextContent(data.get('foo'));
    });
  });

  describe('Input', function() {
    it('should update the model value', function() {
      input.setAttribute('data-value', 'data.foo');
      rivets.bind(input, bindData);
      input.value = 'some new value';
      var event = document.createEvent('HTMLEvents')
      event.initEvent('change', true, true);
      input.dispatchEvent(event);
      expect(input.value).toBe(data.get('foo'));
    });
  });
});
<|endoftext|>


<commit_before>// This file is executed before all specs and before all other handlers

// Enable typescript compilation for .ts files
require('ts-node/register');

// Patch jasmine so that async tests can just return promises (or use the async keyword) and do not need to call done()
global.jasmineRequire = {}; // jasmine-promise expects this be there and patches it, but it is not required
require('jasmine-promises');
<commit_msg>Disable TLS verification in tests<commit_after>// This file is executed before all specs and before all other handlers

// Enable typescript compilation for .ts files
require('ts-node/register');

// Patch jasmine so that async tests can just return promises (or use the async keyword) and do not need to call done()
global.jasmineRequire = {}; // jasmine-promise expects this be there and patches it, but it is not required
require('jasmine-promises');

// to get through firewall
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
<|endoftext|>


<commit_before>const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');
const { lookupScope, rejectQueryingOtherUsers } = require('./hooks');

class ScopeService {
	constructor(handler) {
		this.handler = handler;
	}

	async setup(app) {
		this.app = app;
	}

	static hooks() {
		return {
			before: {
				all: [
					globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
					globalHooks.ifNotLocal(rejectQueryingOtherUsers),
					lookupScope,
				],
			},
		};
	}

	static initialize(app, path, handler) {
		if (!handler) {
			throw new Error(`ScopePermisionService initialized at '${path}' without handler.`);
		}

		app.use(path, new this(handler));
		const scopePermissionService = app.service(path);
		scopePermissionService.hooks(this.hooks());
	}
}

class ScopePermissionService extends ScopeService {
	async getUserPermissions(userId, scope) {
		const permissions = await this.handler.apply(this, [userId, scope]);
		return permissions || [];
	}

	get(userId, params) {
		return this.getUserPermissions(userId, params.scope);
	}

	find(params) {
		const userIds = [];
		const query = params.query.userId;
		if (query) {
			if (query.$in) {
				userIds.concat(query.$in);
			} else {
				userIds.push(query);
			}
		}
		const ops = userIds.map(async userId => [userId, await this.getUserPermissions(userId, params.scope)]);
		return Promise.all(ops)
			.then(results => results.reduce((agg, [key, value]) => {
				const newAgg = agg;
				newAgg[key] = value;
				return newAgg;
			}, {}));
	}
}

class ScopeListService extends ScopeService {
	async getUserScopes(userId, permissions = []) {
		const scopes = await this.handler.apply(this, [userId, permissions]);
		return scopes || [];
	}

	find(params) {
		return this.getUserScopes(params.scope);
	}

	static hooks() {
		return {
			before: {
				all: [
					globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
					lookupScope,
				],
			},
		};
	}
}

module.exports = {
	ScopeService,
	ScopePermissionService,
	ScopeListService,
};
<commit_msg>Supply permissions to handler if necessary<commit_after>const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');
const { lookupScope, rejectQueryingOtherUsers } = require('./hooks');

class ScopeService {
	constructor(handler) {
		this.handler = handler;
	}

	async setup(app) {
		this.app = app;
	}

	static hooks() {
		return {
			before: {
				all: [
					globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
					globalHooks.ifNotLocal(rejectQueryingOtherUsers),
					lookupScope,
				],
			},
		};
	}

	static initialize(app, path, handler) {
		if (!handler) {
			throw new Error(`ScopePermisionService initialized at '${path}' without handler.`);
		}

		app.use(path, new this(handler));
		const scopePermissionService = app.service(path);
		scopePermissionService.hooks(this.hooks());
	}
}

class ScopePermissionService extends ScopeService {
	async getUserPermissions(userId, scope) {
		const permissions = await this.handler.apply(this, [userId, scope]);
		return permissions || [];
	}

	get(userId, params) {
		return this.getUserPermissions(userId, params.scope);
	}

	find(params) {
		const userIds = [];
		const query = params.query.userId;
		if (query) {
			if (query.$in) {
				userIds.concat(query.$in);
			} else {
				userIds.push(query);
			}
		}
		const ops = userIds.map(async userId => [userId, await this.getUserPermissions(userId, params.scope)]);
		return Promise.all(ops)
			.then(results => results.reduce((agg, [key, value]) => {
				const newAgg = agg;
				newAgg[key] = value;
				return newAgg;
			}, {}));
	}
}

class ScopeListService extends ScopeService {
	async getUserScopes(userId, permissions = []) {
		const scopes = await this.handler.apply(this, [userId, permissions]);
		return scopes || [];
	}

	find(params) {
		let list = [];
		if (params.query && params.query.permissions) {
			list = params.query.permissions;
		}
		return this.getUserScopes(params.scope, list);
	}

	static hooks() {
		return {
			before: {
				all: [
					globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
					lookupScope,
				],
			},
		};
	}
}

module.exports = {
	ScopeService,
	ScopePermissionService,
	ScopeListService,
};
<|endoftext|>


<commit_before>/**
  * Use positive and negative values to find an optimal value for the Maximum
  * edit threshold (for phonemes)
  * @author Sahib Singh Pandori <pandori@wisc.edu>
  */

// AnalyzeThreshold.THRESHOLD_INCREMENT = 0.01;

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "src/arpabet/data.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

/**
  * Reads a given CSV file and returns a list of attributes of each row
  * @param filepath - the csv file to be read
  * @return array of array of attributes of each row
  */
function processData(allText) {
  var BLOCK_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var VALUE_SETS = [
      ['up', 'down'],
      ['left', 'right'],
      ['45', '72', '90', '120', '144'],
      ['2', '3', '4', '5'],
      ['red', 'orange', 'blue', 'green', 'yellow', 'purple', 'brown', 'black', 'white']];
  var BLOCK_TYPES = ['move', 'turn', 'pen', 'color', 'repeat'];
  var THRESHOLD_INCREMENT = 0.01;

  // Get all lines and header
  var allTextLines = allText.split(/\r\n|\n/);
  var headers = allTextLines[0].split(',');
  var results = [];

  // For each value of threshold go over all lines and calculate accuracy
  for (var i = 0; i <= (1.0/THRESHOLD_INCREMENT); i++) {
    // Set the threshold to current value
    var corrector = Corrector();
    corrector.MAX_MODIFICATION = i*THRESHOLD_INCREMENT;

    // Calculate the accuracy with current threshold
    var numCorrect = 0;
    for (var i = 1; i < allTextLines.length; i++) {
      var data = allTextLines[i].split(',');
      var cor = corrector.correct(data[1], BLOCK_IDS, VALUE_SETS, BLOCK_TYPES);
      var accepted = data[1] != cor;
      var correct = data[0] == cor;
      if ((correct && accepted) || (!correct && !accepted)) {
        numCorrect++;
      }
    }

    // Store the accuracy result
    results.push(numCorrect/allTextLines.length);
  }

  console.log(results);
}

// function AnalyzeThreshold() {
//   this.curr_threshold = AnalyzeThreshold.THRESHOLD_INCREMENT;
//   while (this.curr_threshold < 1) {
//     // TODO: Read the csv file for recognition and correction
//     var lines = this.readCSV();
//     console.log(lines);
//     // TODO: Loop through them and get accuracy at each threshold
//     // TODO: Print the accuracy for each one (and optimal threshold)
//     this.curr_threshold += AnalyzeThreshold.THRESHOLD_INCREMENT;
//   }
// }
<commit_msg>minor fix<commit_after>/**
  * Use positive and negative values to find an optimal value for the Maximum
  * edit threshold (for phonemes)
  * @author Sahib Singh Pandori <pandori@wisc.edu>
  */

// AnalyzeThreshold.THRESHOLD_INCREMENT = 0.01;

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "src/arpabet/data.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

/**
  * Reads a given CSV file and returns a list of attributes of each row
  * @param filepath - the csv file to be read
  * @return array of array of attributes of each row
  */
function processData(allText) {
  var BLOCK_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var VALUE_SETS = [
      ['up', 'down'],
      ['left', 'right'],
      ['45', '72', '90', '120', '144'],
      ['2', '3', '4', '5'],
      ['red', 'orange', 'blue', 'green', 'yellow', 'purple', 'brown', 'black', 'white']];
  var BLOCK_TYPES = ['move', 'turn', 'pen', 'color', 'repeat'];
  var THRESHOLD_INCREMENT = 0.01;

  // Get all lines and header
  var allTextLines = allText.split(/\r\n|\n/);
  var headers = allTextLines[0].split(',');
  var results = [];

  // For each value of threshold go over all lines and calculate accuracy
  for (var i = 0; i <= (1.0/THRESHOLD_INCREMENT); i++) {
    // Set the threshold to current value
    var corrector = new Corrector();
    corrector.MAX_MODIFICATION = i*THRESHOLD_INCREMENT;

    // Calculate the accuracy with current threshold
    var numCorrect = 0;
    for (var i = 1; i < allTextLines.length; i++) {
      var data = allTextLines[i].split(',');
      var cor = corrector.correct(data[1], BLOCK_IDS, VALUE_SETS, BLOCK_TYPES);
      var accepted = data[1] != cor;
      var correct = data[0] == cor;
      if ((correct && accepted) || (!correct && !accepted)) {
        numCorrect++;
      }
    }

    // Store the accuracy result
    results.push(numCorrect/allTextLines.length);
  }

  console.log(results);
}

// function AnalyzeThreshold() {
//   this.curr_threshold = AnalyzeThreshold.THRESHOLD_INCREMENT;
//   while (this.curr_threshold < 1) {
//     // TODO: Read the csv file for recognition and correction
//     var lines = this.readCSV();
//     console.log(lines);
//     // TODO: Loop through them and get accuracy at each threshold
//     // TODO: Print the accuracy for each one (and optimal threshold)
//     this.curr_threshold += AnalyzeThreshold.THRESHOLD_INCREMENT;
//   }
// }
<|endoftext|>


<commit_before>require('proof')(1, prove)

function prove (okay, callback) {
    var Processor = require('../reduce.processor')
    var sink = {
        gathered: [],
        process: function (entry) {
            this.gathered.push(entry)
            if (entry.json.callback) {
                okay(this.gathered, [{
                    json: {}
                }, {
                    json: {
                        instance: 1,
                        start: 0,
                        end: 1,
                        ended: true,
                        qualified: 'prolific.example#start',
                        array: [ 'a', 'b' ]
                    }
                }, {
                    json: {
                        callback: true
                    }
                }], 'reduce')
                callback()
            }
        }
    }
    var processor = new Processor({
        pivot: '$.instance',
        end: '$.ended',
        calculate: [ '$.duration = $.end - $.start' ]
    }, sink, { delay: 250 })

    processor.open(function () {})

    // Not processed.
    processor.process({ json: { } })
    processor.process({
        json: {
            instance: 1,
            start: 0,
            qualified: 'prolific.example#start',
            array: [ 'a' ]
        }
    })
    processor.process({
        json: {
            instance: 1,
            start: 1,
            end: 1,
            ended: true,
            qualified: 'prolific.example#end',
            array: [ 'b' ]
        }
    })

    processor.close(function () {})

    setTimeout(function () {
        processor.process({ json: { callback: true } })
    }, 350)
}
<commit_msg>100% test coverage of reduce.<commit_after>require('proof')(1, prove)

function prove (okay, callback) {
    var Processor = require('../reduce.processor')
    var sink = {
        gathered: [],
        process: function (entry) {
            this.gathered.push(entry)
            if (entry.json.callback) {
                okay(this.gathered, [{
                    json: {}
                }, {
                    json: {
                        instance: 1,
                        start: 0,
                        end: 1,
                        ended: true,
                        qualified: 'prolific.example#start',
                        name: 'steve',
                        array: [ 'a', 'b' ]
                    }
                }, {
                    json: {
                        callback: true
                    }
                }], 'reduce')
                callback()
            }
        }
    }
    new Processor({
        pivot: '$.instance',
        end: '$.ended',
        calculate: [ '$.duration = $.end - $.start' ]
    }, sink)
    var processor = new Processor({
        pivot: '$.instance',
        end: '$.ended',
        calculate: [ '$.duration = $.end - $.start' ]
    }, sink, { delay: 250 })

    processor.open(function () {})

    // Not processed.
    processor.process({ json: { } })
    processor.process({
        json: {
            instance: 1,
            start: 0,
            qualified: 'prolific.example#start',
            array: [ 'a' ]
        }
    })
    processor.process({
        json: {
            instance: 1,
            start: 1,
            end: 1,
            ended: true,
            qualified: 'prolific.example#end',
            array: [ 'b' ]
        }
    })
    processor.process({
        json: {
            instance: 1,
            name: 'steve',
            qualified: 'prolific.example#name'
        }
    })

    processor.close(function () {})

    setTimeout(function () {
        processor.process({ json: { callback: true } })
    }, 350)
}
<|endoftext|>


<commit_before>const should = require('should');

describe('Circle CI environment variables should be set up', () => {
	it('Should have env variable CIRCLECI', () => {
		process.env.CIRCLECI.should.be.ok;
		process.env.CI.should.be.ok;
	})
})

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const MONGO_URI = process.env.MONGO_URI || require('../../config').MONGO_URI;
mongoose.connect(MONGO_URI);

const model = require('../../server/db/dbmodel');
const Challenges = model.Challenges;
const Tutorial = model.Tutorial;
const Users = model.Users;

const userHandlers = require('../../server/db/userHandlers');
const dbQueryHandler = require('../../server/db/dbQueryHandler');

const john_doe = new Users({
	gitHandle: 'john_doe',
	_id: mongoose.Types.ObjectId()
});

let abc_challenge = {
	name: "Abcs",
	description: "Write a regex that matches whitespace at the beginning and end of strings",
	author: 'john_doe',
	difficulty: 2,
	testCases: [
	  { case: " I have whitespace! ", expectation: true },
	  { case: "I have more whitespace!   ", expectation: true },
	  { case: "   I have some whitespace too!", expectation: true },
	  { case: "Did you say whitespace?", expectation: false },
	  { case: "Naw", expectation: false },
	  { case: "Remember me?", expectation: false }
	]
};

describe('Database Handlers', () => {

	let userId = '';
	before((done) => {
		john_doe.save((err, newUser) => {
			if (err) done(err);
			userId = newUser._id;
			abc_challenge.authorId = userId;
			abc_challenge._id = mongoose.Types.ObjectId();
			abc_challenge = new Challenges(abc_challenge);
			done();
		});
	});
	after((done)=>  {
		Users.remove({ gitHandle: 'john_doe'}, (err, deleted) => {
			if (err) done(err);
			done();
		})
	});

	describe('Challenge Handlers', () => {
		describe('Getting Challenge Data', () => {
			it('getChallenges: Should return all the challenges currently in db', (done) => {
				const getChallenges = dbQueryHandler.getChallenges;
				should.exist(getChallenges);
				getChallenges((challenges) => {
					challenges.should.be.instanceOf(Array);
					challenges.length.should.be.ok;
					challenges.forEach((challenge) => {
						challenge.should.be.instanceOf(Object);
					})
					done();
				})
			});
		});
		describe('Posting Challenge Data', () => {
			let challengeId = '';
			after((done) => {
				Challenges.findOneAndRemove({ authorId: userId }, (err, removed) => {
					if (err) throw err;
					done();
				});
			});
			it('postChallenge: Should be able to post challenges', (done) => {
				const postChallenge = dbQueryHandler.postChallenge;
				should.exist(postChallenge);
				postChallenge(abc_challenge, (newChallenge) => {
					newChallenge.should.be.instanceOf(Object);
					newChallenge.should.have.properties(
						['_id', 'name', 'nameurl', 'description', 'author', 'authorId', 'difficulty', 'testCases', 'answers']
					);
					challengeId = newChallenge._id;
					done();
				});
			});
			it("postChallengeAnswer: Should be able to post a user's answer", (done) => {
				const postChallengeAnswer = dbQueryHandler.postChallengeAnswer;
				const answer = {
					answer: '/abc/',
					user: 'john_doe',
					userId,
				};
				postChallengeAnswer(answer, challengeId, (updatedChallenge) => {
					updatedChallenge.answers.length.should.equal(1);
					const answerObject = updatedChallenge.answers[0]
					answerObject.should.be.instanceOf(Object);
					answerObject.should.have.properties(['answer', 'user', 'userId']);
					done();
				})
			});
		});
	});
	describe('Tutorial Handlers', () => {
		describe('Getting Tutorial Data', () => {
			it('getTutorial: Should get all of the tutorial data', (done) => {
				const getTutorial = dbQueryHandler.getTutorial;
				should.exist(getTutorial);
				getTutorial((tutorials) => {
					tutorials.length.should.be.ok;
					tutorials.should.be.instanceOf(Array);
					tutorials.forEach((tutorial) => {
						tutorial.should.have.property('order');
					})
					done();
				})
			});
		});
	});
	describe('User Handlers', () => {
		let challengeId = '';
		before((done) => {
			dbQueryHandler.postChallenge(abc_challenge, (newChallenge) => {
				challengeId = newChallenge._id;
				done();
			});
		})
		after((done) => {
			Challenges.findOneAndRemove({ authorId: userId }, (err, removed) => {
				if (err) throw err;
				done();
			});
		});
		describe('Getting User Info', () => {
			it('getUserInfo: Should be able to query user info', (done) => {
				const getUserInfo = userHandlers.getUserInfo;
				should.exist(getUserInfo);
				getUserInfo(userId, (userData) => {
					userData.should.be.instanceOf(Object);
					userData._id.should.be.instanceOf(Object);
					done();
				});
			});
		});
		describe('Posting User Info', () => {
			it('addToAuthoredChallenge: Should be able to post to the users authored challenges', (done) => {
				const addToAuthoredChallenge = userHandlers.addToAuthoredChallenge;
				should.exist(addToAuthoredChallenge);
				addToAuthoredChallenge(challengeId, userId, (updatedUser) => {
					should.exist(updatedUser.authored_challenges);
					updatedUser.authored_challenges.length.should.equal(3);
					done();
				});
			});
			it('postCompletedChallenge: Should be able to add challengeIds to user completed_challenges property', (done) => {
				const postCompletedChallenge = userHandlers.postCompletedChallenge;
				should.exist(postCompletedChallenge);
				postCompletedChallenge(challengeId, userId, (updatedUser) => {
					updatedUser.completed_challenges.length.should.equal(1);
					updatedUser.completed_challenges[0].should.deepEqual(challengeId);
					done();
				});
			});
			it('findUserRelatedChallenges: Should be able to return challenge objects for user completed_challenges', (done) => {
				const findUserRelatedChallenges = userHandlers.findUserRelatedChallenges;
				should.exist(findUserRelatedChallenges);
				userId.should.be.instanceOf(Object);
				findUserRelatedChallenges(userId, 'completed_challenges', (challenges) => {
					challenges.length.should.equal(1);
					const firstCompletedChallenge = challenges[0];
					firstCompletedChallenge.should.be.instanceOf(Object);
					done();
				});
			});
			it('findUserRelatedChallenges: Should be able to return challenge objects for user authored challenges', (done) => {
				const findUserRelatedChallenges = userHandlers.findUserRelatedChallenges;
				findUserRelatedChallenges(userId, 'authored_challenges', (challenges) => {
					challenges.length.should.equal(1);
					done();
				});
			});
		});
	});

});

// TODO: Test below functions

// exports.verifyUserExistence = (githubProfile, callback) => {
// 	Users.findOne({ githubId: githubProfile.id }, (err, user) => {
// 		if (err) throw err;
// 		if (!user) {
// 			exports.addUser(githubProfile, (newUser) => {
// 				callback(newUser)
// 			});
// 		} else {
// 			callback(user)
// 		}
// 	})
// };

// exports.addUser = (githubProfile, callback) => {
// 	const user = new Users({
//     accessToken: githubProfile.accessToken,
//     refreshToken: githubProfile.refreshToken,
//     _id: mongoose.Types.ObjectId(),
//     gitHandle: githubProfile.username,
//     githubId: githubProfile.id,
//     name: githubProfile.displayName,
//     created: Date.now(),
//     avatar_url: githubProfile._json.avatar_url,
//     authored_challenges: [],
//     completed_challenges: [],
//     tutorial_progress: '',
//   });
//   user.save((err, newUser) => {
//   	if (err) throw err;
//   	callback(newUser);
//   });
// };
<commit_msg>[ BUGFIX ] Working on circle ci<commit_after>const should = require('should');

describe('Circle CI environment variables should be set up', () => {
	it('Should have env variable CIRCLECI', () => {
		process.env.CIRCLECI.should.be.ok;
		process.env.CI.should.be.ok;
	})
})

/*
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const MONGO_URI = process.env.MONGO_URI || require('../../config').MONGO_URI;
mongoose.connect(MONGO_URI);

const model = require('../../server/db/dbmodel');
const Challenges = model.Challenges;
const Tutorial = model.Tutorial;
const Users = model.Users;

const userHandlers = require('../../server/db/userHandlers');
const dbQueryHandler = require('../../server/db/dbQueryHandler');

const john_doe = new Users({
	gitHandle: 'john_doe',
	_id: mongoose.Types.ObjectId()
});

let abc_challenge = {
	name: "Abcs",
	description: "Write a regex that matches whitespace at the beginning and end of strings",
	author: 'john_doe',
	difficulty: 2,
	testCases: [
	  { case: " I have whitespace! ", expectation: true },
	  { case: "I have more whitespace!   ", expectation: true },
	  { case: "   I have some whitespace too!", expectation: true },
	  { case: "Did you say whitespace?", expectation: false },
	  { case: "Naw", expectation: false },
	  { case: "Remember me?", expectation: false }
	]
};

describe('Database Handlers', () => {

	let userId = '';
	before((done) => {
		john_doe.save((err, newUser) => {
			if (err) done(err);
			userId = newUser._id;
			abc_challenge.authorId = userId;
			abc_challenge._id = mongoose.Types.ObjectId();
			abc_challenge = new Challenges(abc_challenge);
			done();
		});
	});
	after((done)=>  {
		Users.remove({ gitHandle: 'john_doe'}, (err, deleted) => {
			if (err) done(err);
			done();
		})
	});

	describe('Challenge Handlers', () => {
		describe('Getting Challenge Data', () => {
			it('getChallenges: Should return all the challenges currently in db', (done) => {
				const getChallenges = dbQueryHandler.getChallenges;
				should.exist(getChallenges);
				getChallenges((challenges) => {
					challenges.should.be.instanceOf(Array);
					challenges.length.should.be.ok;
					challenges.forEach((challenge) => {
						challenge.should.be.instanceOf(Object);
					})
					done();
				})
			});
		});
		describe('Posting Challenge Data', () => {
			let challengeId = '';
			after((done) => {
				Challenges.findOneAndRemove({ authorId: userId }, (err, removed) => {
					if (err) throw err;
					done();
				});
			});
			it('postChallenge: Should be able to post challenges', (done) => {
				const postChallenge = dbQueryHandler.postChallenge;
				should.exist(postChallenge);
				postChallenge(abc_challenge, (newChallenge) => {
					newChallenge.should.be.instanceOf(Object);
					newChallenge.should.have.properties(
						['_id', 'name', 'nameurl', 'description', 'author', 'authorId', 'difficulty', 'testCases', 'answers']
					);
					challengeId = newChallenge._id;
					done();
				});
			});
			it("postChallengeAnswer: Should be able to post a user's answer", (done) => {
				const postChallengeAnswer = dbQueryHandler.postChallengeAnswer;
				const answer = {
					answer: '/abc/',
					user: 'john_doe',
					userId,
				};
				postChallengeAnswer(answer, challengeId, (updatedChallenge) => {
					updatedChallenge.answers.length.should.equal(1);
					const answerObject = updatedChallenge.answers[0]
					answerObject.should.be.instanceOf(Object);
					answerObject.should.have.properties(['answer', 'user', 'userId']);
					done();
				})
			});
		});
	});
	describe('Tutorial Handlers', () => {
		describe('Getting Tutorial Data', () => {
			it('getTutorial: Should get all of the tutorial data', (done) => {
				const getTutorial = dbQueryHandler.getTutorial;
				should.exist(getTutorial);
				getTutorial((tutorials) => {
					tutorials.length.should.be.ok;
					tutorials.should.be.instanceOf(Array);
					tutorials.forEach((tutorial) => {
						tutorial.should.have.property('order');
					})
					done();
				})
			});
		});
	});
	describe('User Handlers', () => {
		let challengeId = '';
		before((done) => {
			dbQueryHandler.postChallenge(abc_challenge, (newChallenge) => {
				challengeId = newChallenge._id;
				done();
			});
		})
		after((done) => {
			Challenges.findOneAndRemove({ authorId: userId }, (err, removed) => {
				if (err) throw err;
				done();
			});
		});
		describe('Getting User Info', () => {
			it('getUserInfo: Should be able to query user info', (done) => {
				const getUserInfo = userHandlers.getUserInfo;
				should.exist(getUserInfo);
				getUserInfo(userId, (userData) => {
					userData.should.be.instanceOf(Object);
					userData._id.should.be.instanceOf(Object);
					done();
				});
			});
		});
		describe('Posting User Info', () => {
			it('addToAuthoredChallenge: Should be able to post to the users authored challenges', (done) => {
				const addToAuthoredChallenge = userHandlers.addToAuthoredChallenge;
				should.exist(addToAuthoredChallenge);
				addToAuthoredChallenge(challengeId, userId, (updatedUser) => {
					should.exist(updatedUser.authored_challenges);
					updatedUser.authored_challenges.length.should.equal(3);
					done();
				});
			});
			it('postCompletedChallenge: Should be able to add challengeIds to user completed_challenges property', (done) => {
				const postCompletedChallenge = userHandlers.postCompletedChallenge;
				should.exist(postCompletedChallenge);
				postCompletedChallenge(challengeId, userId, (updatedUser) => {
					updatedUser.completed_challenges.length.should.equal(1);
					updatedUser.completed_challenges[0].should.deepEqual(challengeId);
					done();
				});
			});
			it('findUserRelatedChallenges: Should be able to return challenge objects for user completed_challenges', (done) => {
				const findUserRelatedChallenges = userHandlers.findUserRelatedChallenges;
				should.exist(findUserRelatedChallenges);
				userId.should.be.instanceOf(Object);
				findUserRelatedChallenges(userId, 'completed_challenges', (challenges) => {
					challenges.length.should.equal(1);
					const firstCompletedChallenge = challenges[0];
					firstCompletedChallenge.should.be.instanceOf(Object);
					done();
				});
			});
			it('findUserRelatedChallenges: Should be able to return challenge objects for user authored challenges', (done) => {
				const findUserRelatedChallenges = userHandlers.findUserRelatedChallenges;
				findUserRelatedChallenges(userId, 'authored_challenges', (challenges) => {
					challenges.length.should.equal(1);
					done();
				});
			});
		});
	});

});

// TODO: Test below functions

// exports.verifyUserExistence = (githubProfile, callback) => {
// 	Users.findOne({ githubId: githubProfile.id }, (err, user) => {
// 		if (err) throw err;
// 		if (!user) {
// 			exports.addUser(githubProfile, (newUser) => {
// 				callback(newUser)
// 			});
// 		} else {
// 			callback(user)
// 		}
// 	})
// };

// exports.addUser = (githubProfile, callback) => {
// 	const user = new Users({
//     accessToken: githubProfile.accessToken,
//     refreshToken: githubProfile.refreshToken,
//     _id: mongoose.Types.ObjectId(),
//     gitHandle: githubProfile.username,
//     githubId: githubProfile.id,
//     name: githubProfile.displayName,
//     created: Date.now(),
//     avatar_url: githubProfile._json.avatar_url,
//     authored_challenges: [],
//     completed_challenges: [],
//     tutorial_progress: '',
//   });
//   user.save((err, newUser) => {
//   	if (err) throw err;
//   	callback(newUser);
//   });
// };

*/
<|endoftext|>


<commit_before>var Uploader, file;

module("Ember.Uploader", {
  setup: function() {
    if (typeof WebKitBlobBuilder === "undefined") {
      file = new Blob(['test'], { type: 'text/plain' });
    } else {
      var builder;
      builder = new WebKitBlobBuilder();
      builder.append('test');
      file = builder.getBlob();
    }

    Uploader = Ember.Uploader.extend({
      url: '/test',
    });
  }
});

test("has a url of '/test'", function() {
  var uploader = Uploader.create();
  equal(uploader.url, '/test');
});

test("uploads to the given url", function() {
  expect(1);

  var uploader = Uploader.create({
    url: '/upload',
    file: file
  });

  uploader.on('didUpload', function(data) {
    start();
    equal(data, 'OK');
  });

  uploader.upload(file);

  stop();
});

test("emits progress event", function() {
  expect(1);

  var uploader = Uploader.create({
    url: '/upload',
    file: file
  });

  uploader.on('progress', function(e) {
    start();
    equal(e.percent, 100);
  });

  uploader.upload(file);

  stop();
});
<commit_msg>Add test for changing ajax type<commit_after>var Uploader, file;

module("Ember.Uploader", {
  setup: function() {
    if (typeof WebKitBlobBuilder === "undefined") {
      file = new Blob(['test'], { type: 'text/plain' });
    } else {
      var builder;
      builder = new WebKitBlobBuilder();
      builder.append('test');
      file = builder.getBlob();
    }

    Uploader = Ember.Uploader.extend({
      url: '/test',
    });
  }
});

test("has a url of '/test'", function() {
  var uploader = Uploader.create();
  equal(uploader.url, '/test');
});

test("has an ajax request of type 'PUT'", function() {
  var uploader = Uploader.create({type: 'PUT'});
  equal(uploader.type, 'PUT');
});

test("uploads to the given url", function() {
  expect(1);

  var uploader = Uploader.create({
    url: '/upload',
    file: file
  });

  uploader.on('didUpload', function(data) {
    start();
    equal(data, 'OK');
  });

  uploader.upload(file);

  stop();
});

test("emits progress event", function() {
  expect(1);

  var uploader = Uploader.create({
    url: '/upload',
    file: file
  });

  uploader.on('progress', function(e) {
    start();
    equal(e.percent, 100);
  });

  uploader.upload(file);

  stop();
});
<|endoftext|>


<commit_before>!function(t){function n(e){if(r[e])return r[e].exports;var i=r[e]={exports:{},id:e,loaded:!1};return t[e].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}var r={};return n.m=t,n.c=r,n.p="",n(0)}([function(t,n,r){r(1)(window)},function(t,n){t.exports=function(t){var n="RealXMLHttpRequest";t.hookAjax=function(t){function r(n){return function(){var r=this.hasOwnProperty(n+"_")?this[n+"_"]:this.xhr[n],e=(t[n]||{}).getter;return e&&e(r,this)||r}}function e(n){return function(r){var e=this.xhr,i=this,o=t[n];if("function"==typeof o)e[n]=function(){t[n](i)||r.apply(e,arguments)};else{var u=(o||{}).setter;r=u&&u(r,i)||r;try{e[n]=r}catch(t){this[n+"_"]=r}}}}function i(n){return function(){var r=[].slice.call(arguments);if(!t[n]||!t[n].call(this,r,this.xhr))return this.xhr[n].apply(this.xhr,r)}}return window[n]=window[n]||XMLHttpRequest,XMLHttpRequest=function(){var t=new window[n];for(var o in t){var u="";try{u=typeof t[o]}catch(t){}"function"===u?this[o]=i(o):Object.defineProperty(this,o,{get:r(o),set:e(o),enumerable:!0})}this.xhr=t},window[n]},t.unHookAjax=function(){window[n]&&(XMLHttpRequest=window[n]),window[n]=void 0},t.default=t}}]);

hookAjax({
  //拦截回调
  onreadystatechange:function(xhr){
    xhrObject = xhr;
    const response = xhrObject.responseText||xhrObject.response;
    const requestUrl = xhrObject.xhr.responseURL;
    console.log(requestUrl,response)
    localStorage.setItem(requestUrl,response);
  },
  onload:function(xhr){
    console.log("onload called: %O",xhr)
  },
  //拦截方法
  open:function(arg,xhr){
    xhrObject = xhr;
  },
  send:function (xhr) {
    xhrObject.setRequestHeader("location", window.location.pathname+window.location.hash);
  }
})
<commit_msg>打印第二参数<commit_after>!function(t){function n(e){if(r[e])return r[e].exports;var i=r[e]={exports:{},id:e,loaded:!1};return t[e].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}var r={};return n.m=t,n.c=r,n.p="",n(0)}([function(t,n,r){r(1)(window)},function(t,n){t.exports=function(t){var n="RealXMLHttpRequest";t.hookAjax=function(t){function r(n){return function(){var r=this.hasOwnProperty(n+"_")?this[n+"_"]:this.xhr[n],e=(t[n]||{}).getter;return e&&e(r,this)||r}}function e(n){return function(r){var e=this.xhr,i=this,o=t[n];if("function"==typeof o)e[n]=function(){t[n](i)||r.apply(e,arguments)};else{var u=(o||{}).setter;r=u&&u(r,i)||r;try{e[n]=r}catch(t){this[n+"_"]=r}}}}function i(n){return function(){var r=[].slice.call(arguments);if(!t[n]||!t[n].call(this,r,this.xhr))return this.xhr[n].apply(this.xhr,r)}}return window[n]=window[n]||XMLHttpRequest,XMLHttpRequest=function(){var t=new window[n];for(var o in t){var u="";try{u=typeof t[o]}catch(t){}"function"===u?this[o]=i(o):Object.defineProperty(this,o,{get:r(o),set:e(o),enumerable:!0})}this.xhr=t},window[n]},t.unHookAjax=function(){window[n]&&(XMLHttpRequest=window[n]),window[n]=void 0},t.default=t}}]);

hookAjax({
  //拦截回调
  onreadystatechange:function(xhr,second){
    xhrObject = xhr;
    const response = xhrObject.responseText||xhrObject.response;
    const requestUrl = xhrObject.xhr.responseURL;
    console.log(xhrObject,second);
    localStorage.setItem(requestUrl,response);
  },
  onload:function(xhr){
    console.log("onload called: %O",xhr)
  },
  //拦截方法
  open:function(arg,xhr){
    xhrObject = xhr;
  },
  send:function (xhr) {
    xhrObject.setRequestHeader("location", window.location.pathname+window.location.hash);
  }
})
<|endoftext|>


<commit_before>#!/usr/bin/env node
const { join } = require('path')
const { execSync } = require('child_process')
const fs = require('fs')
const mkdirp = require('mkdirp')

process.chdir(join(__dirname, '..'))

mkdirp.sync('repos')

let repos = [
  'ever-increasing-faith',
  'faith-that-prevails',
  'andrew-murray-humility',
  'first-clement',
  'pilgrims-progress',
  'incarnation',
  'christian-pilgrim'
]

let cloned = fs.readdirSync('repos')

repos.forEach(repo => {
  if (cloned.includes(repo)) {
    return
  }
  let command = `git clone https://github.com/christian-classics-jp/${repo}.git`
  console.log('>', command)
  let out = execSync(command, {
    cwd: join(__dirname, '../repos')
  }).toString()
  console.log(out)
})
<commit_msg>Add repos<commit_after>#!/usr/bin/env node
const { join } = require('path')
const { execSync } = require('child_process')
const fs = require('fs')
const mkdirp = require('mkdirp')

process.chdir(join(__dirname, '..'))

mkdirp.sync('repos')

let repos = [
  'ever-increasing-faith',
  'faith-that-prevails',
  'andrew-murray-humility',
  'first-clement',
  'pilgrims-progress',
  'incarnation',
  'christian-pilgrim',
  'wesley-sermons'
]

let cloned = fs.readdirSync('repos')

repos.forEach(repo => {
  if (cloned.includes(repo)) {
    return
  }
  let command = `git clone https://github.com/christian-classics-jp/${repo}.git`
  console.log('>', command)
  let out = execSync(command, {
    cwd: join(__dirname, '../repos')
  }).toString()
  console.log(out)
})
<|endoftext|>


<commit_before>/**
 * 将TypeScript和EXML编译为JavaScript
 */
var path = require("path");
var async = require('../core/async');
var globals = require("../core/globals");
var param = require("../core/params_analyze.js");
var file = require("../core/file.js");
var sdoc = require("./save_docs");
var addExtends = require("./addExtends");

function run(dir, args, opts) {
    if (opts["--output"] == null || opts["--output"].length == 0 || opts["--output"][0] == "") {
        console.log("请设置输出api地址  egret tscdoc --output path");
        return;
    }
    var outputPath = opts["--output"][0] || "";

    var moduleArr = ["core", "html5", "native", "gui", "socket", "dragonbones"];
    var tsList = [];
    for (var i = 0; i < moduleArr.length; i++) {
        tsList = tsList.concat(getModuleList(moduleArr[i]));
    }

    var typeScriptCompiler = require("../tools/egret_tsc_api.js");

    var tempTime = Date.now();
    var cmd = tsList.join(" ") + " -d -t ES5 --out " + outputPath + "a.d.ts";
    var apiArr = typeScriptCompiler.compile(function () {
    }, cmd, null);

    globals.debugLog("耗时：%d秒", (Date.now() - tempTime) / 1000);

    var tempClassArr = sdoc.screening(apiArr);
    tempClassArr = addExtends.addChildClasses(tempClassArr);
    var extendsObj = addExtends.addExtends(tempClassArr);

    file.remove(outputPath);
    addExtends.save(extendsObj, outputPath);

    file.remove("tsc_config_temp.txt");
}

function getModuleList(moduleName) {
    var modulePath = path.join(process.argv[1], "../../../tools/lib/manifest", moduleName + ".json");

    var moduleConfig = JSON.parse(file.read(modulePath));

    //获取源文件地址
    var tsList = moduleConfig.file_list;
    tsList = tsList.map(function (item) {
        return globals.addQuotes(path.join(param.getEgretPath(), moduleConfig.source, item));
    }).filter(function (item) {
        return item.indexOf(".js") == -1;
    });

    return tsList;
}

exports.run = run;
<commit_msg>去掉egretpath路径使用<commit_after>/**
 * 将TypeScript和EXML编译为JavaScript
 */
var path = require("path");
var async = require('../core/async');
var globals = require("../core/globals");
var param = require("../core/params_analyze.js");
var file = require("../core/file.js");
var sdoc = require("./save_docs");
var addExtends = require("./addExtends");

function run(dir, args, opts) {
    if (opts["--output"] == null || opts["--output"].length == 0 || opts["--output"][0] == "") {
        console.log("请设置输出api地址  egret tscdoc --output path");
        return;
    }
    var outputPath = opts["--output"][0] || "";

    var moduleArr = ["core", "html5", "native", "gui", "socket", "dragonbones"];
    var tsList = [];
    for (var i = 0; i < moduleArr.length; i++) {
        tsList = tsList.concat(getModuleList(moduleArr[i]));
    }

    var typeScriptCompiler = require("../tools/egret_tsc_api.js");

    var tempTime = Date.now();
    var cmd = tsList.join(" ") + " -d -t ES5 --out " + outputPath + "a.d.ts";
    var apiArr = typeScriptCompiler.compile(function () {
    }, cmd, null);

    globals.debugLog("耗时：%d秒", (Date.now() - tempTime) / 1000);

    var tempClassArr = sdoc.screening(apiArr);
    tempClassArr = addExtends.addChildClasses(tempClassArr);
    var extendsObj = addExtends.addExtends(tempClassArr);

    file.remove(outputPath);
    addExtends.save(extendsObj, outputPath);

    file.remove("tsc_config_temp.txt");
}

function getModuleList(moduleName) {
    var egretPath = path.join(process.argv[1], "../../../");

    var modulePath = path.join(egretPath, "tools/lib/manifest", moduleName + ".json");

    var moduleConfig = JSON.parse(file.read(modulePath));

    //获取源文件地址
    var tsList = moduleConfig.file_list;
    tsList = tsList.map(function (item) {
        return globals.addQuotes(path.join(egretPath, moduleConfig.source, item));
    }).filter(function (item) {
        return item.indexOf(".js") == -1;
    });

    return tsList;
}

exports.run = run;
<|endoftext|>


<commit_before>var BACKEND_ENDPOINT = "http://localhost:7231/bookmarks";

var bookmarksCache = [];

// The bookmark model
function Bookmark(href, url, title, thumbnail, summary) {
    var self = this;
    self.href = href;
    self.url = url;
    self.summary = summary;
    self.title = title;
    self.thumbnail = thumbnail;
}

// The bookmark view model
function BookmarkViewModel() {
    var self = this;

    self.bookmarks = ko.observableArray(bookmarksCache);
    self.query = ko.observable();
    self.url = ko.observable();

    self.loadBookmarks = function() {
        $.ajax({
            url: BACKEND_ENDPOINT,
            type: "GET",
            success: function(data){
                bookmarksCache = [];
                if (data._embedded){
                    var bookmarks = data._embedded.bookmarks;
                    for (var i=0; i < bookmarks.length; i++){
                        var bookmark = bookmarks[i];
                        bookmarksCache.push(new Bookmark(
                            bookmark._links.self.href,
                            bookmark.url,
                            bookmark.title,
                            bookmark.thumbnail,
                            bookmark.summary
                        ));

                    }
                }
            }
        }).done(function(){
            self.search();
        });
    };

    self.addBookmark = function() {
        var bookmark = new Bookmark(self.url(),
            "a new title", "100x100.png", "summary");
        bookmarksCache.push(bookmark);
        self.search();
    };

    self.deleteBookmark = function(bookmark){
        for(var i = 0; i < bookmarksCache.length; i++){
            if (bookmarksCache[i].url ==  bookmark.url){
                bookmarksCache.splice(i, 1);
                self.search();
            }
        }
    };

    self.updateBookmark = function(bookmark) {
        //alert('saved new summary: ' + bookmark.summary);
    };

    self.search = function(){
        var searchResult = [];
        for(var i=0; i < bookmarksCache.length; i++){
            var bookmark = bookmarksCache[i];
            var query = new RegExp(self.query(), 'i');
            if (bookmark.url.search(query) > -1 || bookmark.title.search(query) > -1 || bookmark.summary.search(query) > -1){
                searchResult.push(bookmark)
            }
        }
        self.bookmarks(searchResult);
    };

    // Load initial data
    self.loadBookmarks();
}

// Activates knockout.js
ko.applyBindings(new BookmarkViewModel());<commit_msg>solution<commit_after>var BACKEND_ENDPOINT = "http://localhost:7231/bookmarks";

var bookmarksCache = [];

// The bookmark model
function Bookmark(href, url, title, thumbnail, summary) {
    var self = this;
    self.href = href;
    self.url = url;
    self.summary = summary;
    self.title = title;
    self.thumbnail = thumbnail;
}

// The bookmark view model
function BookmarkViewModel() {
    var self = this;

    self.bookmarks = ko.observableArray(bookmarksCache);
    self.query = ko.observable();
    self.url = ko.observable();

    self.loadBookmarks = function() {
        $.ajax({
            url: BACKEND_ENDPOINT,
            type: "GET",
            success: function(data){
                bookmarksCache = [];
                if (data._embedded){
                    var bookmarks = data._embedded.bookmarks;
                    for (var i=0; i < bookmarks.length; i++){
                        var bookmark = bookmarks[i];
                        bookmarksCache.push(new Bookmark(
                            bookmark._links.self.href,
                            bookmark.url,
                            bookmark.title,
                            bookmark.thumbnail,
                            bookmark.summary
                        ));

                    }
                }
            }
        }).done(function(){
            self.search();
        });
    };

    self.addBookmark = function() {
        $.ajax({
            url: BACKEND_ENDPOINT,
            type: "POST",
            contentType: "application/json",
            data: ko.toJSON(self),
            success: function(data){
                self.query("");
                self.loadBookmarks();
            }
        });
    };

    self.deleteBookmark = function(bookmark){
        $.ajax({
            url: bookmark.href,
            type: "DELETE",
            success: function(data){
                self.loadBookmarks();
            }
        });
    };

    self.updateBookmark = function(bookmark) {
        $.ajax({
            url: bookmark.href,
            type: "PUT",
            contentType: "application/json",
            data: ko.toJSON(bookmark),
            success: function(data){
                self.loadBookmarks();
            }
        });
    };

    self.search = function(){
        var searchResult = [];
        for(var i=0; i < bookmarksCache.length; i++){
            var bookmark = bookmarksCache[i];
            var query = new RegExp(self.query(), 'i');
            if (bookmark.url.search(query) > -1 || bookmark.title.search(query) > -1 || bookmark.summary.search(query) > -1){
                searchResult.push(bookmark)
            }
        }
        self.bookmarks(searchResult);
    };

    // Load initial data
    self.loadBookmarks();
}

// Activates knockout.js
ko.applyBindings(new BookmarkViewModel());<|endoftext|>


<commit_before>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     * Should this be in rui?
     */
    Ext.define('Rally.apps.iterationplanningboard.IterationPlanningBoardBacklogColumn', {
        extend: 'Rally.ui.cardboard.Column',
        alias: 'widget.iterationplanningboardappbacklogcolumn',

        cls: 'column',

        requires: [
            'Rally.ui.TextField'
        ],

        mixins: {
            maskable: 'Rally.ui.mask.Maskable'
        },

        config: {
            value: null
        },

        getColumnStatus: function() {
            return this.columnStatus;
        },

        getStatusCell: function() {
            return Ext.get(this.statusCell);
        },

        drawHeader: function() {
            this.callParent(arguments);

            this.getColumnHeader().add(
                {
                    xtype: 'container',
                    cls: 'search',
                    items: [
                        {
                            xtype: 'rallytextfield',
                            cls: 'search-text',
                            itemId: 'searchText',
                            enableKeyEvents: true,
                            emptyText: 'Search',
                            listeners: {
                                specialkey: this._onSearchTextSpecialKey,
                                scope: this
                            }
                        },
                        {
                            xtype: 'component',
                            cls: 'search-button',
                            listeners: {
                                click: {
                                    element: 'el',
                                    fn: this._onSearchClicked,
                                    scope: this
                                }
                            }
                        }
                    ]
                }
            );
        },

        initComponent: function() {
            this.callParent(arguments);

            this.on('afterrender', function() {
                var cls = 'planning-column backlog';
                this.getContentCell().addCls(cls);
                this.getStatusCell().addCls(cls);
                this.getColumnHeaderCell().addCls(cls);
            }, this, {single: true});
        },

        _onSearchClicked: function() {
            this._refreshColumn();
        },

        _onSearchTextSpecialKey: function(searchTextField, e) {
            if (e.getKey() === e.ENTER) {
                this._refreshColumn();
            }
        },

        _refreshColumn: function() {
            if (this.searching) {
                return;
            }

            this._clearFilters();

            this.searching = true;
            var searchValue = this.getColumnHeader().down('#searchText').getValue();
            this.setMaskTarget(this.getContentCell());
            this.showMask();
            this._deactivatedCards = [];

            this.on('load', function() {
                this.fireEvent('filter', this);
                this.hideMask();
                this.searching = false;
            }, this, {single: true});

            this.refresh({
                storeConfig: {
                    search: searchValue ? Ext.String.trim(searchValue) : ""
                }
            });
        },

        getStoreFilter: function(model) {
            var filters = [];
            Ext.Array.push(filters, this.callParent(arguments));
            if (model.elementName === 'HierarchicalRequirement') {
                if (this.context.getSubscription().StoryHierarchyEnabled) {
                    filters.push({
                        property: 'DirectChildrenCount',
                        operator: '=',
                        value: 0
                    });
                }
            } else if (model.elementName === 'Defect') {
                Ext.Array.push(filters,
                    {
                        property: 'Requirement',
                        operator: '=',
                        value: null
                    },
                    {
                        property: 'State',
                        operator: '!=',
                        value: 'Closed'
                    });
            }

            return filters;
        },

        isMatchingRecord: function(record) {
            var isMatching = this.callParent(arguments);
            if (record.self.elementName === 'HierarchicalRequirement') {
                isMatching = isMatching && (!record.hasField('DirectChildrenCount') || record.get('DirectChildrenCount') === 0);
            } else if (record.self.elementName === 'Defect') {
                isMatching = isMatching && (!record.hasField('Requirement') || !record.get('Requirement'));
            }
            return isMatching;
        },

        _clearFilters: function() {
            if (this.filterCollection) {
                this.filterCollection.clearAllFilters();
            }
        }
    });
})();
<commit_msg>S55875 refactored clearing of temp filters on column refresh.<commit_after>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     * Should this be in rui?
     */
    Ext.define('Rally.apps.iterationplanningboard.IterationPlanningBoardBacklogColumn', {
        extend: 'Rally.ui.cardboard.Column',
        alias: 'widget.iterationplanningboardappbacklogcolumn',

        cls: 'column',

        requires: [
            'Rally.ui.TextField'
        ],

        mixins: {
            maskable: 'Rally.ui.mask.Maskable'
        },

        config: {
            value: null
        },

        getColumnStatus: function() {
            return this.columnStatus;
        },

        getStatusCell: function() {
            return Ext.get(this.statusCell);
        },

        drawHeader: function() {
            this.callParent(arguments);

            this.getColumnHeader().add(
                {
                    xtype: 'container',
                    cls: 'search',
                    items: [
                        {
                            xtype: 'rallytextfield',
                            cls: 'search-text',
                            itemId: 'searchText',
                            enableKeyEvents: true,
                            emptyText: 'Search',
                            listeners: {
                                specialkey: this._onSearchTextSpecialKey,
                                scope: this
                            }
                        },
                        {
                            xtype: 'component',
                            cls: 'search-button',
                            listeners: {
                                click: {
                                    element: 'el',
                                    fn: this._onSearchClicked,
                                    scope: this
                                }
                            }
                        }
                    ]
                }
            );
        },

        initComponent: function() {
            this.callParent(arguments);

            this.on('afterrender', function() {
                var cls = 'planning-column backlog';
                this.getContentCell().addCls(cls);
                this.getStatusCell().addCls(cls);
                this.getColumnHeaderCell().addCls(cls);
            }, this, {single: true});
        },

        _onSearchClicked: function() {
            this._refreshColumn();
        },

        _onSearchTextSpecialKey: function(searchTextField, e) {
            if (e.getKey() === e.ENTER) {
                this._refreshColumn();
            }
        },

        _refreshColumn: function() {
            if (this.searching) {
                return;
            }

            this.searching = true;
            var searchValue = this.getColumnHeader().down('#searchText').getValue();
            this.setMaskTarget(this.getContentCell());
            this.showMask();
            this._deactivatedCards = [];

            this.on('load', function() {
                this.fireEvent('filter', this);
                this.hideMask();
                this.searching = false;
            }, this, {single: true});

            this.refresh({
                storeConfig: {
                    search: searchValue ? Ext.String.trim(searchValue) : ""
                }
            });
        },

        getStoreFilter: function(model) {
            var filters = [];
            Ext.Array.push(filters, this.callParent(arguments));
            if (model.elementName === 'HierarchicalRequirement') {
                if (this.context.getSubscription().StoryHierarchyEnabled) {
                    filters.push({
                        property: 'DirectChildrenCount',
                        operator: '=',
                        value: 0
                    });
                }
            } else if (model.elementName === 'Defect') {
                Ext.Array.push(filters,
                    {
                        property: 'Requirement',
                        operator: '=',
                        value: null
                    },
                    {
                        property: 'State',
                        operator: '!=',
                        value: 'Closed'
                    });
            }

            return filters;
        },

        isMatchingRecord: function(record) {
            var isMatching = this.callParent(arguments);
            if (record.self.elementName === 'HierarchicalRequirement') {
                isMatching = isMatching && (!record.hasField('DirectChildrenCount') || record.get('DirectChildrenCount') === 0);
            } else if (record.self.elementName === 'Defect') {
                isMatching = isMatching && (!record.hasField('Requirement') || !record.get('Requirement'));
            }
            return isMatching;
        }
    });
})();
<|endoftext|>


<commit_before>// Opt-in repos (case sensitive)
// - These are all children of Shopify and visible at https://github.com/Shopify
var optInRepos = [
  'FunctionalTableData',
  'Intro_to_GraphQL_Powered_by_Shopify',
  'active_fulfillment',
  'active_merchant',
  'active_shipping',
  'active_utils',
  'app_profiler',
  'asset_cloud',
  'browser_sniffer',
  'connect-googleapps',
  'draggable',
  'dukpt',
  'ejson2env',
  'embedded-app-example',
  'go-lua',
  'goluago',
  'goreferrer',
  'grizzly_ber',
  'identity_cache',
  'js-buy-sdk',
  'kubeaudit',
  'liquid',
  'magnet',
  'minesweeper',
  'money',
  'omniauth-shopify-oauth2',
  'packwerk',
  'polaris-react',
  'polaris-icons',
  'pyreferrer',
  'rails_parallel',
  'rotoscope',
  'rubocop-sorbet',
  'sarama',
  'semian',
  'shipit-engine',
  'shopify-css-import',
  'shopify-fulfillment-integration',
  'shopify_api',
  'shopify_app',
  'shopify_django_app',
  'shopify_python_api',
  'shopify_theme',
  'skeleton-theme',
  'slate',
  'splunk-auth-proxy',
  'spoom',
  'starter-theme',
  'statsd-instrument',
  'superdb',
  'sync_app_demo',
  'sysv_mq',
  'tapioca',
  'themekit',
  'theme-scripts',
  'toxiproxy',
  'toxiproxy-ruby',
  'tslint-config-shopify',
  'turbograft',
  'twine',
  'verdict',
  'voucher',
  'vouch4cluster',
  'wolverine',
  'promise-kotlin',
  'promise-swift',
  'android-testify',
  'krane',
  'quilt',
  'graphql-tools-web'
];

// Add custom repos by full_name. Take the org/user and repo name
// - e.g. batmanjs/batman from https://github.com/batmanjs/batman
var customRepos = [];

// Custom repo language, different than that defined by GitHub
var customRepoLanguage = {
  liquid: 'Liquid',
  'starter-theme': 'Liquid',
  'skeleton-theme': 'Liquid',
  shopify_theme: 'Ruby',
  'Shopify-Developer-Book': 'Ruby',
  'offsite-gateway-sim': 'Ruby',
  'shopify.github.com': 'JavaScript',
  rotoscope: 'C'
};

// Custom repo avatars. Dimensions should be 40x40
// - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden
var customRepoAvatar = {
  slate: '/images/repo-avatars/slate.svg',
  draggable: '/images/repo-avatars/draggable.png',
  superdb: '/images/repo-avatars/super-debugger.gif'
};
<commit_msg>Remove Verdict (#95)<commit_after>// Opt-in repos (case sensitive)
// - These are all children of Shopify and visible at https://github.com/Shopify
var optInRepos = [
  'FunctionalTableData',
  'Intro_to_GraphQL_Powered_by_Shopify',
  'active_fulfillment',
  'active_merchant',
  'active_shipping',
  'active_utils',
  'app_profiler',
  'asset_cloud',
  'browser_sniffer',
  'connect-googleapps',
  'draggable',
  'dukpt',
  'ejson2env',
  'embedded-app-example',
  'go-lua',
  'goluago',
  'goreferrer',
  'grizzly_ber',
  'identity_cache',
  'js-buy-sdk',
  'kubeaudit',
  'liquid',
  'magnet',
  'minesweeper',
  'money',
  'omniauth-shopify-oauth2',
  'packwerk',
  'polaris-react',
  'polaris-icons',
  'pyreferrer',
  'rails_parallel',
  'rotoscope',
  'rubocop-sorbet',
  'sarama',
  'semian',
  'shipit-engine',
  'shopify-css-import',
  'shopify-fulfillment-integration',
  'shopify_api',
  'shopify_app',
  'shopify_django_app',
  'shopify_python_api',
  'shopify_theme',
  'skeleton-theme',
  'slate',
  'splunk-auth-proxy',
  'spoom',
  'starter-theme',
  'statsd-instrument',
  'superdb',
  'sync_app_demo',
  'sysv_mq',
  'tapioca',
  'themekit',
  'theme-scripts',
  'toxiproxy',
  'toxiproxy-ruby',
  'tslint-config-shopify',
  'turbograft',
  'twine',
  'voucher',
  'vouch4cluster',
  'wolverine',
  'promise-kotlin',
  'promise-swift',
  'android-testify',
  'krane',
  'quilt',
  'graphql-tools-web'
];

// Add custom repos by full_name. Take the org/user and repo name
// - e.g. batmanjs/batman from https://github.com/batmanjs/batman
var customRepos = [];

// Custom repo language, different than that defined by GitHub
var customRepoLanguage = {
  liquid: 'Liquid',
  'starter-theme': 'Liquid',
  'skeleton-theme': 'Liquid',
  shopify_theme: 'Ruby',
  'Shopify-Developer-Book': 'Ruby',
  'offsite-gateway-sim': 'Ruby',
  'shopify.github.com': 'JavaScript',
  rotoscope: 'C'
};

// Custom repo avatars. Dimensions should be 40x40
// - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden
var customRepoAvatar = {
  slate: '/images/repo-avatars/slate.svg',
  draggable: '/images/repo-avatars/draggable.png',
  superdb: '/images/repo-avatars/super-debugger.gif'
};
<|endoftext|>


<commit_before>'use strict';

var nconf = require('nconf');

var Settings = require('../../lib/Settings');

describe('loadRepositoriesSettings', function () {
    beforeEach(function () {
        spyOn(nconf, 'env').and.returnValue(nconf);
    });

    it('returns rejected Promise when config does not have `secret`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noSecret.json')
            .then(function () {
                done.fail();
            })
            .catch(function () {
                done();
            });
    });

    it('returns rejected Promise when config does not have `repositories`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noRepositories.json')
            .then(function () {
                done.fail();
            })
            .catch(function () {
                done();
            });
    });

    it('returns rejected Promise when `repositories` do not have names', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noRepositoryNames.json')
            .then(function () {
                done.fail();
            })
            .catch(function (err) {
                if (/repositories/.test(err)) {
                    return done();
                }
                done.fail(err);
            });
    });

    it('returns rejected Promise when `repositories` do not have `gitHubToken`s', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noGitHubToken.json')
            .then(function () {
                done.fail();
            })
            .catch(function (err) {
                if (/gitHubToken/.test(err)) {
                    return done();
                }
                done.fail(err);
            });
    });

    it('returns rejected Promise when repositories don\'t have a user prepended', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noUserBeforeRepository.json')
        .then(function () {
            done.fail();
        })
        .catch(function (err) {
            if (/must be in the form/.test(err)) {
                return done();
            }
            done.fail(err);
        });
    });

    it('removes `/` from `thirdPartyFolders` that begin with `/`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/slashWithThirdPartyFolders.json')
            .then(function () {
                expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('appends `/` to `thirdPartyFolders that don\'t end with `/`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noEndSlashThirdPartyFolders.json')
            .then(function () {
                expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('splits `thirdPartyFolders`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/multipleThirdPartyFolders.json')
            .then(function () {
                expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/', 'AnotherFolder/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('sets `bumpStalePullRequests` `url` correctly', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/bumpStalePullRequests_noUrl.json')
            .then(function () {
                expect(Settings.repositories['one'].bumpStalePullRequestsUrl).toEqual('https://api.github.com/repos/a/one/pulls');
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('correctly loads values', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noError.json')
            .then(function () {
                expect(Settings.repositories.one.gitHubToken).toEqual('bar');
                expect(Settings.repositories.one.someVal).toBe(true);
                expect(Settings.repositories.two.gitHubToken).toEqual('bar2');
                expect(Settings.repositories.two.someVal).toEqual(false);

                expect(Settings.port).toEqual(10);
                expect(Settings.listenPath).toEqual('/foo');
                expect(Settings.secret).toEqual('foo');
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });
});
<commit_msg>Fix Settings unit tests<commit_after>'use strict';

var nconf = require('nconf');

var Settings = require('../../lib/Settings');

describe('loadRepositoriesSettings', function () {
    beforeEach(function () {
        spyOn(nconf, 'env').and.returnValue(nconf);
    });

    it('returns rejected Promise when config does not have `secret`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noSecret.json')
            .then(function () {
                done.fail();
            })
            .catch(function () {
                done();
            });
    });

    it('returns rejected Promise when config does not have `repositories`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noRepositories.json')
            .then(function () {
                done.fail();
            })
            .catch(function () {
                done();
            });
    });

    it('returns rejected Promise when `repositories` do not have names', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noRepositoryNames.json')
            .then(function () {
                done.fail();
            })
            .catch(function (err) {
                if (/repositories/.test(err)) {
                    return done();
                }
                done.fail(err);
            });
    });

    it('returns rejected Promise when `repositories` do not have `gitHubToken`s', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noGitHubToken.json')
            .then(function () {
                done.fail();
            })
            .catch(function (err) {
                if (/gitHubToken/.test(err)) {
                    return done();
                }
                done.fail(err);
            });
    });

    it('returns rejected Promise when repositories don\'t have a user prepended', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noUserBeforeRepository.json')
        .then(function () {
            done.fail();
        })
        .catch(function (err) {
            if (/must be in the form/.test(err)) {
                return done();
            }
            done.fail(err);
        });
    });

    it('removes `/` from `thirdPartyFolders` that begin with `/`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/slashWithThirdPartyFolders.json')
            .then(function () {
                console.log(Settings.repositories);
                expect(Settings.repositories['a/one'].thirdPartyFolders).toEqual(['ThirdParty/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('appends `/` to `thirdPartyFolders that don\'t end with `/`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noEndSlashThirdPartyFolders.json')
            .then(function () {
                expect(Settings.repositories['a/one'].thirdPartyFolders).toEqual(['ThirdParty/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('splits `thirdPartyFolders`', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/multipleThirdPartyFolders.json')
            .then(function () {
                expect(Settings.repositories['a/one'].thirdPartyFolders).toEqual(['ThirdParty/', 'AnotherFolder/']);
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('sets `bumpStalePullRequests` `url` correctly', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/bumpStalePullRequests_noUrl.json')
            .then(function () {
                expect(Settings.repositories['a/one'].bumpStalePullRequestsUrl).toEqual('https://api.github.com/repos/a/one/pulls');
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });

    it('correctly loads values', function (done) {
        Settings.loadRepositoriesSettings('./specs/data/config/noError.json')
            .then(function () {
                expect(Settings.repositories['a/one'].gitHubToken).toEqual('bar');
                expect(Settings.repositories['a/one'].someVal).toBe(true);
                expect(Settings.repositories['a/two'].gitHubToken).toEqual('bar2');
                expect(Settings.repositories['a/two'].someVal).toEqual(false);

                expect(Settings.port).toEqual(10);
                expect(Settings.listenPath).toEqual('/foo');
                expect(Settings.secret).toEqual('foo');
                done();
            })
            .catch(function (err) {
                done.fail(err);
            });
    });
});
<|endoftext|>


<commit_before>import deleteValueForProperty from './deleteValueForProperty';
import setValueForProperty from './setValueForProperty';
import setValueForStyles from './setValueForStyles';
import eventManager from '../events/eventManager';
import events from '../events/shared/events';

/**
 * Detecting differences in property values and updating the DOM as necessary.
 * This function is probably the single most critical path for performance optimization.
 *
 * @param {DOMElement} node
 * @param {string} propKey
 * @param {object} lastProps
 * @param {object} nextProps
 */
function updateDOMProperties(element, propKey, lastProps, nextProps) {

    if (propKey === 'style') {

        let styleUpdates;
        let styleName;

        if (lastProps != null) {

            if (nextProps == null) {
                deleteValueForProperty(element, propKey);
            } else {

                // Unset styles on `lastProp` but not on `nextProp`.
                for (styleName in lastProps) {
                    if (lastProps[styleName] && (!nextProps || !nextProps[styleName])) {
                        styleUpdates = styleUpdates || {};
                        styleUpdates[styleName] = '';
                    }
                }
                // Update styles that changed since `lastProps`.
                for (styleName in nextProps) {
                    if (nextProps[styleName] && lastProps[styleName] !== nextProps[styleName]) {
                        styleUpdates = styleUpdates || {};
                        styleUpdates[styleName] = nextProps[styleName];
                    }
                }
            }
        } else if (nextProps != null) {
            styleUpdates = nextProps;
        }

        if (styleUpdates) {
            setValueForStyles(element, styleUpdates);
        }

    } else {

        // Check if there was a listener
        if (events[propKey] != null) {

            // TODO!! Is this working as it should? Add tests!!
            if (lastProps != null) {

                if (nextProps == null) {
                    eventManager.removeListener(element, propKey);
                } else {
                    if (nextProps && lastProps !== nextProps) {
                        eventManager.addListener(element, propKey, nextProps);
                    }
                }
            } else if (nextProps != null) {
                eventManager.addListener(element, propKey, nextProps);
            }
        } else {
            // TODO!! Should we no something here if lastProps or nextProps are null ???
            setValueForProperty(element, propKey, nextProps);
        }
    }
}

export default updateDOMProperties;<commit_msg>minor updates<commit_after>import deleteValueForProperty from './deleteValueForProperty';
import setValueForProperty from './setValueForProperty';
import setValueForStyles from './setValueForStyles';
import eventManager from '../events/eventManager';
import events from '../events/shared/events';

/**
 * Detecting differences in property values and updating the DOM as necessary.
 * This function is probably the single most critical path for performance optimization.
 *
 * @param {DOMElement} node
 * @param {string} propKey
 * @param {object} lastProps
 * @param {object} nextProps
 */
function updateDOMProperties(element, propKey, lastProps, nextProps) {

    if (propKey === 'style') {

        let styleUpdates;
        let styleName;

        if (lastProps != null) {

            if (nextProps == null) {
                deleteValueForProperty(element, propKey);
            } else {

                // Unset styles on `lastProp` but not on `nextProp`.
                for (styleName in lastProps) {
                    if (lastProps[styleName] && (!nextProps || !nextProps[styleName])) {
                        styleUpdates = styleUpdates || {};
                        styleUpdates[styleName] = '';
                    }
                }
                // Update styles that changed since `lastProps`.
                for (styleName in nextProps) {
                    if (nextProps[styleName] && lastProps[styleName] !== nextProps[styleName]) {
                        styleUpdates = styleUpdates || {};
                        styleUpdates[styleName] = nextProps[styleName];
                    }
                }
            }
        } else if (nextProps != null) {
            styleUpdates = nextProps;
        }

        if (styleUpdates) {
            setValueForStyles(element, styleUpdates);
        }

    } else {

        // Check if there was a listener
        if (events[propKey] != null) {

            // TODO!! Is this working as it should? Add tests!!
            if (lastProps != null) {

                if (nextProps == null) {
                    eventManager.removeListener(element, propKey);
                } else {
                    if (nextProps && lastProps !== nextProps) {
                        eventManager.addListener(element, propKey, nextProps);
                    }
                }
            } else if (nextProps != null) {
                eventManager.addListener(element, propKey, nextProps);
            }
        } else {

            if (lastProps != null) {

                if (nextProps == null) {
                    deleteValueForProperty(element, propKey);
                } else {

                    if (nextProps && lastProps !== nextProps) {
                        setValueForProperty(element, propKey, nextProps);
                    }
                }
            } else if (nextProps != null) {
                setValueForProperty(element, propKey, nextProps);
            }
        }
    }
}

export default updateDOMProperties;<|endoftext|>