<commit_before>const DEFAULT_KEY_MODIFIERS = { shiftKey: false, ctrlKey: false, altKey: false }

export function keyPressed (keyCode, modifiers, callback) {
  if (typeof modifiers === 'function') {
    callback = modifiers
    modifiers = Object.assign({}, DEFAULT_KEY_MODIFIERS)
  } else {
    modifiers = Object.assign({}, DEFAULT_KEY_MODIFIERS, modifiers)
  }

  return function (event) {
    // proper event?
    if (!event) {
      return
    }
    // correct keyCode?
    if (event.keyCode !== keyCode) {
      return
    }

    // correct modifiers?
    if (Object.keys(modifiers).reduce((result, name) => result && event[name] === modifiers[name], true) !== true) {
      return
    }

    callback.apply(this, arguments)
  }
}

keyPressed.return = keyPressed.bind(null, 13)

export function matchesMedia (query, callback) {
  return function () {
    if (window.matchMedia(query).matches) {
      callback.apply(this, arguments)
    }
  }
}

matchesMedia.min = {}
matchesMedia.min.small = matchesMedia.bind(null, '(min-width: 768px)')
matchesMedia.min.medium = matchesMedia.bind(null, '(min-width: 992px)')
matchesMedia.min.large = matchesMedia.bind(null, '(min-width: 1200px)')
matchesMedia.min.hd = matchesMedia.bind(null, '(min-width: 1920px)')
matchesMedia.max = {}
matchesMedia.max.small = matchesMedia.bind(null, '(max-width: 767px)')
matchesMedia.max.medium = matchesMedia.bind(null, '(max-width: 991px)')
matchesMedia.max.large = matchesMedia.bind(null, '(max-width: 1199px)')
matchesMedia.max.hd = matchesMedia.bind(null, '(max-width: 1919px)')

export default { keyPressed, matchesMedia }
<commit_msg>add on event listener helper<commit_after>const DEFAULT_KEY_MODIFIERS = { shiftKey: false, ctrlKey: false, altKey: false }

export function keyPressed (keyCode, modifiers, callback) {
  if (typeof modifiers === 'function') {
    callback = modifiers
    modifiers = Object.assign({}, DEFAULT_KEY_MODIFIERS)
  } else {
    modifiers = Object.assign({}, DEFAULT_KEY_MODIFIERS, modifiers)
  }

  return function (event) {
    // proper event?
    if (!event) {
      return
    }
    // correct keyCode?
    if (event.keyCode !== keyCode) {
      return
    }

    // correct modifiers?
    if (Object.keys(modifiers).reduce((result, name) => result && event[name] === modifiers[name], true) !== true) {
      return
    }

    callback.apply(this, arguments)
  }
}

keyPressed.return = keyPressed.bind(null, 13)

export function matchesMedia (query, callback) {
  return function () {
    if (window.matchMedia(query).matches) {
      callback.apply(this, arguments)
    }
  }
}

matchesMedia.min = {}
matchesMedia.min.small = matchesMedia.bind(null, '(min-width: 768px)')
matchesMedia.min.medium = matchesMedia.bind(null, '(min-width: 992px)')
matchesMedia.min.large = matchesMedia.bind(null, '(min-width: 1200px)')
matchesMedia.min.hd = matchesMedia.bind(null, '(min-width: 1920px)')
matchesMedia.max = {}
matchesMedia.max.small = matchesMedia.bind(null, '(max-width: 767px)')
matchesMedia.max.medium = matchesMedia.bind(null, '(max-width: 991px)')
matchesMedia.max.large = matchesMedia.bind(null, '(max-width: 1199px)')
matchesMedia.max.hd = matchesMedia.bind(null, '(max-width: 1919px)')

export function on (el, event, callback, capture = false) {
  el.addEventListener(event, callback, capture)
  return { destroy: () => { el.removeEventListener(event, callback, capture) } }
}

export default { keyPressed, matchesMedia, on }
<|endoftext|>


<commit_before>/**
 * pubfood
 * Copyright (c) 2015 Yieldbot, Inc. - All rights reserved.
 *
 * Events live here..
 */

'use strict';

var util = require('./util');
var logger = require('./logger');
var EventEmitter = require('eventemitter3');

/**
 * Pubfood event class
 * @class
 * @memberof pubfood
 * @return {pubfood.PubfoodEvent}
 */
function PubfoodEvent() {
  // PubfoodEvent constructor
}

/**
 * @type {object}
 * @description Available event types
 */
PubfoodEvent.prototype.EVENT_TYPE = {
  /**
   * Api library load
   * @event pubfood.PubfoodEvent.PUBFOOD_API_LOAD
   */
  PUBFOOD_API_LOAD: 'pubfoodapiload',
  /**
   * Api library start
   * @event pubfood.PubfoodEvent.PUBFOOD_API_START
   */
  PUBFOOD_API_START: 'pubfoodapistart',
  /**
   * Bid provider library load started
   * @event pubfood.PubfoodEvent.BID_LIB_START
   */
  BID_LIB_START: 'bplibstart',
  /**
   * Bid provider library loaded
   * @event pubfood.PubfoodEvent.BID_LIB_LOADED
   */
  BID_LIB_LOADED: 'bplibloaded',
  /**
   * Action started.
e.g [BidProvider.init]{@link pubfood/provider.BidProvider#init}
   * @event pubfood.PubfoodEvent.BID_START
   */
  BID_START: 'bidstart',
  /**
   *  Next item in data stream ready.

   *  e.g [BidProvider.refresh]{@link pubfood/provider.BidProvider#init} raises
   *  a [BID_PUSH_NEXT]{@link pubfood/events.EVENT_TYPE.BID_PUSH_NEXT} event for each bid.
   * @event pubfood.PubfoodEvent.BID_PUSH_NEXT
   */
  BID_PUSH_NEXT: 'bidpushnext',
  /**
   * Action is complete
   * @event pubfood.PubfoodEvent.BID_COMPLETE
   */
  BID_COMPLETE: 'bidcomplete',
  /**
   * Start bid assembler
   * @event pubfood.PubfoodEvent.BID_ASSEMBLER
   */
  BID_ASSEMBLER: 'bidassembler',
  /**
   * Auction provider library load started
   * @event pubfood.PubfoodEvent.AUCTION_LIB_START
   */
  AUCTION_LIB_START: 'aplibstart',
  /**
   * Auction provider library loaded
   * @event pubfood.PubfoodEvent.AUCTION_LIB_LOADED
   */
  AUCTION_LIB_LOADED: 'aplibloaded',
  /**
   * Start the publisher auction
   * @event pubfood.PubfoodEvent.AUCTION_GO
   */
  AUCTION_GO: 'auctiongo',
  /**
   * Start the publisher auction from a business rule.
   * e.g. a bidder timeout
   * @event pubfood.PubfoodEvent.AUCTION_TRIGGER
   */
  AUCTION_TRIGGER: 'auctiontrigger',
  /**
   * The auction was restarted
   * @event pubfood.PubfoodEvent.AUCTION_REFRESH
   */
  AUCTION_REFRESH: 'auctionrefresh',
  /**
   * The auction has completed
   * @event pubfood.PubfoodEvent.AUCTION_COMPLETE
   */
  AUCTION_COMPLETE: 'auctioncomplete',
  /**
   * Error event raised
   * @event pubfood.PubfoodEvent.ERROR
   */
  ERROR: 'error',
  /**
   * Warn event raised
   * @event pubfood.PubfoodEvent.WARN
   */
  WARN: 'warn',
  /**
   * Invalid operation or data event raise
   * @event pubfood.PubfoodEvent.INVALID
   */
  INVALID: 'invalid'
};

/**
 * publish an event
 * @param {string} eventType The event type
 * @param {*} data the event data
 * @param {string} providerType The type of provider. ex: bid, auction
 * @return {boolean} Indication if we've emitted an event.
 */
PubfoodEvent.prototype.publish = function(eventType, data, providerType) {
  var ts = (+new Date());

  if(eventType === this.EVENT_TYPE.PUBFOOD_API_START && data){
    ts = data;
  }

  logger.logEvent(eventType, arguments);

  return this.emit(eventType, {
    ts: ts,
    type: eventType,
    provider: providerType || 'pubfood',
    data: data || ''
  });
};

/**
 * Emit an event to all registered event listeners.
 * @function emit
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Register a new EventListener for the given event.
 * @function on
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Add an EventListener that's only called once.
 * @function once
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Remove event listeners.
 * @function removeListener
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Remove all listeners or only the listeners for the specified event.
 * @function removeAllListeners
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Return a list of assigned event listeners.
 * @function listeners
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * @typedef {object} EventStructure
 * @memberof pubfood.PubfoodEvent
 * @property {string} ts The timestamp of the event
 * @property {string} type The event type
 * @property {string} provider The type of provider. Defaults to pubfood
 * @property {object|string} data Data structure for each event type
 * @property {string} data.PUBFOOD_API_LOAD
 * @property {string} data.PUBFOOD_API_START
 * @property {object} data.ERROR
 * @property {*} data.ERROR.stackTrace
 * @property {string} data.WARN warning message
 * @property {string} data.INVALID validation message
 * @property {object} data.AUCTION_LIB_START
 * @property {string} data.AUCTION_LIB_START.auctionProvider
 * @property {object} data.AUCTION_LIB_LOADED
 * @property {string} data.AUCTION_LIB_LOADED.auctionProvider
 * @property {string} data.AUCTION_GO
 * @property {string} data.AUCTION_TRIGGER
 * @property {string} data.AUCTION_REFRESH
 * @property {string} data.AUCTION_COMPLETE
 * @property {string} data.BID_LIB_START
 * @property {string} data.BID_LIB_LOADED
 * @property {object} data.BID_PUSH_NEXT @see [Bid]{@link pubfood#model.Bid}
 * @property {string} data.BID_PUSH_NEXT.id
 * @property {array.<number, number>} data.BID_PUSH_NEXT.sizes
 * @property {string} data.BID_PUSH_NEXT.value
 * @property {object} data.BID_PUSH_NEXT.targetting
 * @property {string} data.BID_START
 * @property {string} data.BID_COMPLETE
 * @property {string} data.BID_ASSEMBLER
 */

util.extends(PubfoodEvent, EventEmitter);
module.exports = new PubfoodEvent();
<commit_msg>use SCREAMING_SNAKE_CASE for event type values<commit_after>/**
 * pubfood
 * Copyright (c) 2015 Yieldbot, Inc. - All rights reserved.
 *
 * Events live here..
 */

'use strict';

var util = require('./util');
var logger = require('./logger');
var EventEmitter = require('eventemitter3');

/**
 * Pubfood event class
 * @class
 * @memberof pubfood
 * @return {pubfood.PubfoodEvent}
 */
function PubfoodEvent() {
  // PubfoodEvent constructor
}

/**
 * @type {object}
 * @description Available event types
 */
PubfoodEvent.prototype.EVENT_TYPE = {
  /**
   * Api library load
   * @event pubfood.PubfoodEvent.PUBFOOD_API_LOAD
   */
  PUBFOOD_API_LOAD: 'PUBFOOD_API_LOAD',
  /**
   * Api library start
   * @event pubfood.PubfoodEvent.PUBFOOD_API_START
   */
  PUBFOOD_API_START: 'PUBFOOD_API_START',
  /**
   * Bid provider library load started
   * @event pubfood.PubfoodEvent.BID_LIB_START
   */
  BID_LIB_START: 'BID_LIB_START',
  /**
   * Bid provider library loaded
   * @event pubfood.PubfoodEvent.BID_LIB_LOADED
   */
  BID_LIB_LOADED: 'BID_LIB_LOADED',
  /**
   * Action started.
e.g [BidProvider.init]{@link pubfood/provider.BidProvider#init}
   * @event pubfood.PubfoodEvent.BID_START
   */
  BID_START: 'BID_START',
  /**
   *  Next item in data stream ready.

   *  e.g [BidProvider.refresh]{@link pubfood/provider.BidProvider#init} raises
   *  a [BID_PUSH_NEXT]{@link pubfood/events.EVENT_TYPE.BID_PUSH_NEXT} event for each bid.
   * @event pubfood.PubfoodEvent.BID_PUSH_NEXT
   */
  BID_PUSH_NEXT: 'BID_PUSH_NEXT',
  /**
   * Action is complete
   * @event pubfood.PubfoodEvent.BID_COMPLETE
   */
  BID_COMPLETE: 'BID_COMPLETE',
  /**
   * Start bid assembler
   * @event pubfood.PubfoodEvent.BID_ASSEMBLER
   */
  BID_ASSEMBLER: 'BID_ASSEMBLER',
  /**
   * Auction provider library load started
   * @event pubfood.PubfoodEvent.AUCTION_LIB_START
   */
  AUCTION_LIB_START: 'AUCTION_LIB_START',
  /**
   * Auction provider library loaded
   * @event pubfood.PubfoodEvent.AUCTION_LIB_LOADED
   */
  AUCTION_LIB_LOADED: 'AUCTION_LIB_LOADED',
  /**
   * Start the publisher auction
   * @event pubfood.PubfoodEvent.AUCTION_GO
   */
  AUCTION_GO: 'AUCTION_GO',
  /**
   * Start the publisher auction from a business rule.
   * e.g. a bidder timeout
   * @event pubfood.PubfoodEvent.AUCTION_TRIGGER
   */
  AUCTION_TRIGGER: 'AUCTION_TRIGGER',
  /**
   * The auction was restarted
   * @event pubfood.PubfoodEvent.AUCTION_REFRESH
   */
  AUCTION_REFRESH: 'AUCTION_REFRESH',
  /**
   * The auction has completed
   * @event pubfood.PubfoodEvent.AUCTION_COMPLETE
   */
  AUCTION_COMPLETE: 'AUCTION_COMPLETE',
  /**
   * Error event raised
   * @event pubfood.PubfoodEvent.ERROR
   */
  ERROR: 'ERROR',
  /**
   * Warn event raised
   * @event pubfood.PubfoodEvent.WARN
   */
  WARN: 'WARN',
  /**
   * Invalid operation or data event raise
   * @event pubfood.PubfoodEvent.INVALID
   */
  INVALID: 'INVALID'
};

/**
 * publish an event
 * @param {string} eventType The event type
 * @param {*} data the event data
 * @param {string} providerType The type of provider. ex: bid, auction
 * @return {boolean} Indication if we've emitted an event.
 */
PubfoodEvent.prototype.publish = function(eventType, data, providerType) {
  var ts = (+new Date());

  if(eventType === this.EVENT_TYPE.PUBFOOD_API_START && data){
    ts = data;
  }

  logger.logEvent(eventType, arguments);

  return this.emit(eventType, {
    ts: ts,
    type: eventType,
    provider: providerType || 'pubfood',
    data: data || ''
  });
};

/**
 * Emit an event to all registered event listeners.
 * @function emit
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Register a new EventListener for the given event.
 * @function on
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Add an EventListener that's only called once.
 * @function once
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Remove event listeners.
 * @function removeListener
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Remove all listeners or only the listeners for the specified event.
 * @function removeAllListeners
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * Return a list of assigned event listeners.
 * @function listeners
 * @memberof pubfood.PubfoodEvent
 * @see https://github.com/primus/eventemitter3
 */

/**
 * @typedef {object} EventStructure
 * @memberof pubfood.PubfoodEvent
 * @property {string} ts The timestamp of the event
 * @property {string} type The event type
 * @property {string} provider The type of provider. Defaults to pubfood
 * @property {object|string} data Data structure for each event type
 * @property {string} data.PUBFOOD_API_LOAD
 * @property {string} data.PUBFOOD_API_START
 * @property {object} data.ERROR
 * @property {*} data.ERROR.stackTrace
 * @property {string} data.WARN warning message
 * @property {string} data.INVALID validation message
 * @property {object} data.AUCTION_LIB_START
 * @property {string} data.AUCTION_LIB_START.auctionProvider
 * @property {object} data.AUCTION_LIB_LOADED
 * @property {string} data.AUCTION_LIB_LOADED.auctionProvider
 * @property {string} data.AUCTION_GO
 * @property {string} data.AUCTION_TRIGGER
 * @property {string} data.AUCTION_REFRESH
 * @property {string} data.AUCTION_COMPLETE
 * @property {string} data.BID_LIB_START
 * @property {string} data.BID_LIB_LOADED
 * @property {object} data.BID_PUSH_NEXT @see [Bid]{@link pubfood#model.Bid}
 * @property {string} data.BID_PUSH_NEXT.id
 * @property {array.<number, number>} data.BID_PUSH_NEXT.sizes
 * @property {string} data.BID_PUSH_NEXT.value
 * @property {object} data.BID_PUSH_NEXT.targetting
 * @property {string} data.BID_START
 * @property {string} data.BID_COMPLETE
 * @property {string} data.BID_ASSEMBLER
 */

util.extends(PubfoodEvent, EventEmitter);
module.exports = new PubfoodEvent();
<|endoftext|>


<commit_before>Posts = new Meteor.Collection('posts');

var postValidation = (function() {
	return {
		validate: validate
	};

	function validate(post) {
		var loggedInUser = Meteor.user();
		var postWithSameUrl = Posts.findOne({ url: post.url });

		if (!loggedInUser) {
			throw new Meteor.Error(HttpStatus.unauthorized,
				'You need to login to create new posts');
		}

		if (!post.url) {
			throw new Meteor.Error(HttpStatus.unprocessableEntity,
				'Please fill in the url');
		}

		if (!post.title) {
			throw new Meteor.Error(HttpStatus.unprocessableEntity,
				'Please fill in the title');
		}

		if (postWithSameUrl && post._id !== postWithSameUrl._id) {
			throw new Meteor.Error(HttpStatus.found,
				'This link has already been posted',
				postWithSameUrl._id);
		}
	}
}());

Posts.allow({
	remove: permissions.ownsDocument
});

Meteor.methods({
	insertPost: function(post) {
		var loggedInUser = Meteor.user();

		postValidation.validate(post);

		post = _.extend(_.pick(post, 'url', 'title'), {
			userId: loggedInUser._id,
			author: loggedInUser.username,
			createdAt: new Date().getTime()
		});

		var postId = Posts.insert(post);

		return postId;
	},
	updatePost: function(postAttributes) {
		console.log(postAttributes);

		var originalPost = Posts.findOne(postAttributes._id);

		postAttributes = _.extend(originalPost, postAttributes);
		postAttributes.updatedAt = new Date().getTime();

		postValidation.validate(postAttributes);

		var postId = Posts.update(postAttributes._id, { $set: postAttributes });

		return postId;
	}
});<commit_msg>removing debug console messages<commit_after>Posts = new Meteor.Collection('posts');

var postValidation = (function() {
	return {
		validate: validate
	};

	function validate(post) {
		var loggedInUser = Meteor.user();
		var postWithSameUrl = Posts.findOne({ url: post.url });

		if (!loggedInUser) {
			throw new Meteor.Error(HttpStatus.unauthorized,
				'You need to login to create new posts');
		}

		if (!post.url) {
			throw new Meteor.Error(HttpStatus.unprocessableEntity,
				'Please fill in the url');
		}

		if (!post.title) {
			throw new Meteor.Error(HttpStatus.unprocessableEntity,
				'Please fill in the title');
		}

		if (postWithSameUrl && post._id !== postWithSameUrl._id) {
			throw new Meteor.Error(HttpStatus.found,
				'This link has already been posted',
				postWithSameUrl._id);
		}
	}
}());

Posts.allow({
	remove: permissions.ownsDocument
});

Meteor.methods({
	insertPost: function(post) {
		var loggedInUser = Meteor.user();

		postValidation.validate(post);

		post = _.extend(_.pick(post, 'url', 'title'), {
			userId: loggedInUser._id,
			author: loggedInUser.username,
			createdAt: new Date().getTime()
		});

		var postId = Posts.insert(post);

		return postId;
	},
	updatePost: function(postAttributes) {
		var originalPost = Posts.findOne(postAttributes._id);

		postAttributes = _.extend(originalPost, postAttributes);
		postAttributes.updatedAt = new Date().getTime();

		postValidation.validate(postAttributes);

		var postId = Posts.update(postAttributes._id, { $set: postAttributes });

		return postId;
	}
});<|endoftext|>


<commit_before>Users = Meteor.users;

UserProfileSchema = new SimpleSchema({
    name:{
      type:String,
      label:"Full Name",
      max:64
    }
});

UserSchema = new SimpleSchema({
    _id: {
        type: String,
        regEx: SimpleSchema.RegEx.Id
    },
    username: {
        type: String,
        optional: true
    },
    emails: {
        type: [Object],
        // this must be optional if you also use other login services like facebook,
        // but if you use only accounts-password, then it can be required
        optional: true
    },
    "emails.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email,
        label:"Email Address"
    },
    "emails.$.verified": {
        type: Boolean,
        defaultValue:false
    },
    emailHash:{
        type:String,
        optional:true
    },
    isDeveloper:{
        type:Boolean,
        defaultValue:false
    },
    createdAt: {
        type: Date
    },
    profile: {
        type: UserProfileSchema,
        optional: true
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
    roles: {
        type: Array,
        optional: true
    },
    "roles.$": {
        type: String
    }
});

Users.attachSchema(UserSchema);

Users.allow({
  insert: function(userId, doc) {
    return false;
  },
  update: function(userId, doc, fieldNames, modifier) {
    return !_.contains(fieldNames, 'roles') && userId && doc && userId === doc.userId;
  },
  remove: function(userId, doc) {
    return Roles.userIsInRole(userId, ['admin']);
  },
  fetch: ['userId']
});
<commit_msg>fixes #24<commit_after>Users = Meteor.users;

UserProfileSchema = new SimpleSchema({
    name:{
      type:String,
      label:"Full Name",
      max:64,
      optional:true
    }
});

UserSchema = new SimpleSchema({
    _id: {
        type: String,
        regEx: SimpleSchema.RegEx.Id
    },
    username: {
        type: String,
        optional: true
    },
    emails: {
        type: [Object],
        // this must be optional if you also use other login services like facebook,
        // but if you use only accounts-password, then it can be required
        optional: true
    },
    "emails.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email,
        label:"Email Address"
    },
    "emails.$.verified": {
        type: Boolean,
        defaultValue:false
    },
    emailHash:{
        type:String,
        optional:true
    },
    isDeveloper:{
        type:Boolean,
        defaultValue:false
    },
    createdAt: {
        type: Date
    },
    profile: {
        type: UserProfileSchema,
        optional: true
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
    roles: {
        type: Array,
        optional: true
    },
    "roles.$": {
        type: String
    }
});

Users.attachSchema(UserSchema);

Users.allow({
  insert: function(userId, doc) {
    return false;
  },
  update: function(userId, doc, fieldNames, modifier) {
    return !_.contains(fieldNames, 'roles') && userId && doc && userId === doc.userId;
  },
  remove: function(userId, doc) {
    return Roles.userIsInRole(userId, ['admin']);
  },
  fetch: ['userId']
});
<|endoftext|>


<commit_before>
Meteor.users.allow({
  update: isAdminById,
  remove: isAdminById
});<commit_msg>fixed bug that prevented user profile updating<commit_after>Meteor.users.allow({
  update: function(userId, doc){
  	return isAdminById(userId) || userId == doc._id;
  },
  remove: function(userId, doc){
  	return isAdminById(userId) || userId == doc._id;
  }
});<|endoftext|>


<commit_before>/*
 * FRAME module/Object that consists of Core methods
 * @author Zafar Saleem
 */
var FRAME = {
	/**
	 * Main object that consists details for all modules upon registering.
	 * Modules are stored as
	 * modulesData: {
	 * 		modules: {
	 *			nameofmodule: object
	 * 		}
	 * }
	 */
	modulesData: {},

	/**
	 * Register method registers modules and stores them in
	 * modulesData object.
	 * @param {string} name of module
	 * @param {object} object of module
	 * @return {}
	 */
	register: function (module, obj) {
		if (this._isString(module) && this._isObject(obj)) {
			if (!this._isMethod(obj.init) && !this._isMethod(obj.destroy)) {
				this._log(3, 'Module does not have init and/or destroy methods');
				return;
			}
			// If modules object inside modulesData does not exist then create one
			if (typeof this.modulesData.modules === 'undefined') this.modulesData['modules'] = {};
			this.modulesData.modules[module] = obj; // Store module's object inside modulesData.modules

			if (typeof this.modulesData.$container === 'undefined') this.modulesData['$container'] = {};
			this.modulesData['$container'] = $('#' + module);

			if (obj.events && typeof obj.events === 'object') {
				FRAME.AggregatedEvents.init(obj);
			}
		} else {
			this._log(3, 'Module name should be String & obj should be Object');
		}
	},

	/**
	 * This method initialize single module stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	start: function (module) {
		if (this._isMethod(module)) return;
		module.init.bind(module).apply();
	},

	/**
	 * This method initializes all modules stored in modulesData: {}
	 * by calling start method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	startAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		if (Object.keys(modules).length <= 0) return; // if there are no modules registered then do nothing
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.start(modules[keys]);
		}
	},

	/**
	 * This method stop initialization of single modules stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stop: function (module) {
		if (this._isMethod(module)) return;
		module.destory.bind(module).apply();
	},

	/**
	 * This method stop initialization of all modules stored in modulesData: {}
	 * by calling stop method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stopAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		// if there are no modules registered then do nothing
		if (Object.keys(modules).length <= 0) return;
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.stop(modules[keys]);
		}
	},

	/**
	 * Creates new DOM element and apply all attributes such as
	 * Class name, id, href etc.
	 * @param {object} DOM element that will be created by this method
	 * @param {object} List of attributes i.e. id, class, href etc.
	 * @return {object} Created DOM element
	 */
	createElement: function (el, config) {
        var i, text, child,
        el = this._create(el);
        if (!config) return;
        if (config.children && this._isArray(config.children)) {
            i = 0;
            while(child = config.children[i]) {
                el.appendChild(child);
                i++;
            }
            delete config.children;
        }
        if (config.text) {
            el.appendChild(document.createTextNode(config.text));
            delete config.text;
        }
        this._applyAttrs(el, config);
        return el;
    },

	/**
	 * Object that adds events to selectors and call callback functions
	 * in a module. This modules is for following events object
	 * events: {
	 *		'click #selector': 'callback'
	 * }
	 */
	AggregatedEvents: {
		config: {
			context: null,
			callback: null
		},

		/**
		 * constructor function that initialize AggregatedEvents object,
		 * it gets callback function from events object and store it in config.callback,
		 * then calls applyEvents method.
		 * @param {object} context of modules where events object is defined
		 */
		init: function (context) {
			var events = context.events, keys;
			if (!FRAME._isObject(events)) return;

			this.config.context = context;
			for (keys in events) {
				if (!events.hasOwnProperty(keys)) return;
				this.config.callback = context[events[keys]];
	    		if (!FRAME._isMethod(this.config.callback)) return;
	    		this.applyEvents(keys);
			}
		},

		/**
		 * Checks for multiple selectors, if given then seperate them and put them
		 * in an array then bind events to all those selectors.
		 * If single selector is given then apply event to that selector.
		 * @param {string} properties of events object
		 * @return {}
		 */
		applyEvents: function (keys) {
			var i, len, selectors = this.getSelectors(keys.split(" "));

			if (selectors.length === 1) {
				this.bindEvents(keys.split(" ")[0], keys.split(" ")[1]);
				return;
			}

			for (i = 0, len = selectors.length; i < len; i++) {
				if (selectors[i] === 0) continue;
				this.bindEvents(keys.split(" ")[0], selectors[i]);
			}
		},

		/**
		 * It binds event to selector and call callback function
		 * @param {evt} event name e.g. click, hover etc that needs to attached to selector
		 * @param {string} selector on which event needs to be attached.
		 */
		bindEvents: function (evt, selector) {
	      	$(document).on(evt, selector, this.config.callback.bind(this.config.context));
	    },

		getSelectors: function (arr) {
			return arr.filter(function (item, index) {
				return (index !== 0) || item;
			});
	    }
	},

	/**
	 * Pub/Sub system that stores events in object and then triggers them when
	 * requires.
	 */
	Events: {
		eventsData: {}, // all events are stored here

		/**
		 * Stores events and context in eventsData object as key value pair
		 * @param {String} Event name
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		trigger: function (events, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				FRAME._log(2, 'This event name is already taken!');
				return;
			}
			this.eventsData[events] = context;
		},

		/**
		 * Calls events when required
		 * @param {String} Event name
		 * @param {Function} Callback function that needs to be called upon
		 * @param {Object} Context(this) to module from where listen() function id called
		 * @return {}
		 */
		listen: function (events, callback, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				if (typeof callback !== 'function') return;
				callback.bind(this.getContext(this.eventsData[events], context)).apply();
			}
		},

		/**
		 * Get context
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		getContext: function (context, module) {
			if (context && typeof context === 'object') return context;
			if (module && typeof module === 'object') return module;
		}
	},

	/**
	 * Creates DOM element.
	 * @param {object} DOM element that will be created by this method
	 * @return {object} Created DOM element
	 */
	_create: function (el) {
        return document.createElement(el);
    },

    /**
	 * Apply attributes i.e. id, class, href etc to created element.
	 * @param {object} DOM element to which attributes will be applied
	 * @param {object} attributes object that has id, class etc.
	 * @return {}
	 */
    _applyAttrs: function (el, attrs) {
        $(el).attr(attrs);
    },

    _isArray: function (arr) {
		return (Array.isArray(arr));
	},

	/**
	 * Check if paramter is a function
	 * @private
	 * @param {Function}
	 * @return {Boolean}
	 */
	_isMethod: function (method) {
		return (method && typeof method === 'function');
	},

	/**
	 * Check if paramter is an Object
	 * @private
	 * @param {Object}
	 * @return {Boolean}
	 */
	_isObject: function (object) {
		return (object && typeof object === 'object');
	},

	/**
	 * Check if paramter is a String
	 * @private
	 * @param {String}
	 * @return {Boolean}
	 */
	_isString: function (str) {
		return (str && typeof str === 'string');
	},

	/**
	 * Log function
	 * @private
	 * @param {Number} 1-3
	 * @param {String} Message
	 */
	_log: function (severity, message) {
		console[(severity === 1 ? 'log' : (severity === 2) ? 'warn' : 'error')](message);
	}
};
<commit_msg>Added comments to isArray method<commit_after>/*
 * FRAME module/Object that consists of Core methods
 * @author Zafar Saleem
 */
var FRAME = {
	/**
	 * Main object that consists details for all modules upon registering.
	 * Modules are stored as
	 * modulesData: {
	 * 		modules: {
	 *			nameofmodule: object
	 * 		}
	 * }
	 */
	modulesData: {},

	/**
	 * Register method registers modules and stores them in
	 * modulesData object.
	 * @param {string} name of module
	 * @param {object} object of module
	 * @return {}
	 */
	register: function (module, obj) {
		if (this._isString(module) && this._isObject(obj)) {
			if (!this._isMethod(obj.init) && !this._isMethod(obj.destroy)) {
				this._log(3, 'Module does not have init and/or destroy methods');
				return;
			}
			// If modules object inside modulesData does not exist then create one
			if (typeof this.modulesData.modules === 'undefined') this.modulesData['modules'] = {};
			this.modulesData.modules[module] = obj; // Store module's object inside modulesData.modules

			if (typeof this.modulesData.$container === 'undefined') this.modulesData['$container'] = {};
			this.modulesData['$container'] = $('#' + module);

			if (obj.events && typeof obj.events === 'object') {
				FRAME.AggregatedEvents.init(obj);
			}
		} else {
			this._log(3, 'Module name should be String & obj should be Object');
		}
	},

	/**
	 * This method initialize single module stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	start: function (module) {
		if (this._isMethod(module)) return;
		module.init.bind(module).apply();
	},

	/**
	 * This method initializes all modules stored in modulesData: {}
	 * by calling start method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	startAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		if (Object.keys(modules).length <= 0) return; // if there are no modules registered then do nothing
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.start(modules[keys]);
		}
	},

	/**
	 * This method stop initialization of single modules stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stop: function (module) {
		if (this._isMethod(module)) return;
		module.destory.bind(module).apply();
	},

	/**
	 * This method stop initialization of all modules stored in modulesData: {}
	 * by calling stop method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stopAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		// if there are no modules registered then do nothing
		if (Object.keys(modules).length <= 0) return;
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.stop(modules[keys]);
		}
	},

	/**
	 * Creates new DOM element and apply all attributes such as
	 * Class name, id, href etc.
	 * @param {object} DOM element that will be created by this method
	 * @param {object} List of attributes i.e. id, class, href etc.
	 * @return {object} Created DOM element
	 */
	createElement: function (el, config) {
        var i, text, child,
        el = this._create(el);
        if (!config) return;
        if (config.children && this._isArray(config.children)) {
            i = 0;
            while(child = config.children[i]) {
                el.appendChild(child);
                i++;
            }
            delete config.children;
        }
        if (config.text) {
            el.appendChild(document.createTextNode(config.text));
            delete config.text;
        }
        this._applyAttrs(el, config);
        return el;
    },

	/**
	 * Object that adds events to selectors and call callback functions
	 * in a module. This modules is for following events object
	 * events: {
	 *		'click #selector': 'callback'
	 * }
	 */
	AggregatedEvents: {
		config: {
			context: null,
			callback: null
		},

		/**
		 * constructor function that initialize AggregatedEvents object,
		 * it gets callback function from events object and store it in config.callback,
		 * then calls applyEvents method.
		 * @param {object} context of modules where events object is defined
		 */
		init: function (context) {
			var events = context.events, keys;
			if (!FRAME._isObject(events)) return;

			this.config.context = context;
			for (keys in events) {
				if (!events.hasOwnProperty(keys)) return;
				this.config.callback = context[events[keys]];
	    		if (!FRAME._isMethod(this.config.callback)) return;
	    		this.applyEvents(keys);
			}
		},

		/**
		 * Checks for multiple selectors, if given then seperate them and put them
		 * in an array then bind events to all those selectors.
		 * If single selector is given then apply event to that selector.
		 * @param {string} properties of events object
		 * @return {}
		 */
		applyEvents: function (keys) {
			var i, len, selectors = this.getSelectors(keys.split(" "));

			if (selectors.length === 1) {
				this.bindEvents(keys.split(" ")[0], keys.split(" ")[1]);
				return;
			}

			for (i = 0, len = selectors.length; i < len; i++) {
				if (selectors[i] === 0) continue;
				this.bindEvents(keys.split(" ")[0], selectors[i]);
			}
		},

		/**
		 * It binds event to selector and call callback function
		 * @param {evt} event name e.g. click, hover etc that needs to attached to selector
		 * @param {string} selector on which event needs to be attached.
		 */
		bindEvents: function (evt, selector) {
	      	$(document).on(evt, selector, this.config.callback.bind(this.config.context));
	    },

		getSelectors: function (arr) {
			return arr.filter(function (item, index) {
				return (index !== 0) || item;
			});
	    }
	},

	/**
	 * Pub/Sub system that stores events in object and then triggers them when
	 * requires.
	 */
	Events: {
		eventsData: {}, // all events are stored here

		/**
		 * Stores events and context in eventsData object as key value pair
		 * @param {String} Event name
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		trigger: function (events, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				FRAME._log(2, 'This event name is already taken!');
				return;
			}
			this.eventsData[events] = context;
		},

		/**
		 * Calls events when required
		 * @param {String} Event name
		 * @param {Function} Callback function that needs to be called upon
		 * @param {Object} Context(this) to module from where listen() function id called
		 * @return {}
		 */
		listen: function (events, callback, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				if (typeof callback !== 'function') return;
				callback.bind(this.getContext(this.eventsData[events], context)).apply();
			}
		},

		/**
		 * Get context
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		getContext: function (context, module) {
			if (context && typeof context === 'object') return context;
			if (module && typeof module === 'object') return module;
		}
	},

	/**
	 * Creates DOM element.
	 * @private
	 * @param {object} DOM element that will be created by this method
	 * @return {object} Created DOM element
	 */
	_create: function (el) {
        return document.createElement(el);
    },

    /**
	 * Apply attributes i.e. id, class, href etc to create element.
	 * @private
	 * @param {object} DOM element to which attributes will be applied
	 * @param {object} attributes object that has id, class etc.
	 * @return {}
	 */
    _applyAttrs: function (el, attrs) {
        $(el).attr(attrs);
    },

    /**
	 * Check for array.
	 * @private
	 * @param {array} Array to check if it is array.
	 * @return {boolean} true/false
	 */
    _isArray: function (arr) {
		return (Array.isArray(arr));
	},

	/**
	 * Check if paramter is a function
	 * @private
	 * @param {Function}
	 * @return {Boolean} true/false
	 */
	_isMethod: function (method) {
		return (method && typeof method === 'function');
	},

	/**
	 * Check if paramter is an Object
	 * @private
	 * @param {Object}
	 * @return {Boolean} true/false
	 */
	_isObject: function (object) {
		return (object && typeof object === 'object');
	},

	/**
	 * Check if paramter is a String
	 * @private
	 * @param {String}
	 * @return {Boolean} true/false
	 */
	_isString: function (str) {
		return (str && typeof str === 'string');
	},

	/**
	 * Log function
	 * @private
	 * @param {Number} 1-3
	 * @param {String} Message
	 */
	_log: function (severity, message) {
		console[(severity === 1 ? 'log' : (severity === 2) ? 'warn' : 'error')](message);
	}
};
<|endoftext|>


<commit_before>'use strict';

import fs from 'fs';
import jpeg from 'jpeg-js';

function getPixel(x, y, channel, width, buff) {
	return buff[(x + y * width) * 4 + channel];
}

function convertPixelsToHistogram(img) {
	const createHistogramArray = function () {
		const ret = new Array(256);
		for (let i = 0; i < ret.length; i++) {
			ret[i] = 0;
		}
		return ret;
	};

	const width = img.width;
	const height = img.height;

	const histograms = [
		createHistogramArray(),
		createHistogramArray(),
		createHistogramArray()
	];

	for (let channel = 0; channel < histograms.length; channel++) {
		for (let i = 0; i < width; i++) {
			for (let j = 0; j < height; j++) {
				const pixelValue = getPixel(i, j, channel, width, img.data);

				// Erase pixels considered as white
				if (getPixel(i, j, 0, width, img.data) < 249 &&
						getPixel(i, j, 1, width, img.data) < 249 &&
						getPixel(i, j, 2, width, img.data) < 249) {
					histograms[channel][pixelValue]++;
				}
			}
		}
	}

	return histograms;
}

const screenshot_trace_category = 'disabled-by-default-devtools.screenshot';
function extractFramesFromTimeline(timeline) {
	let trace;
	trace = typeof timeline === 'string' ? fs.readFileSync(timeline, 'utf-8') : timeline;
	try {
		trace = typeof trace === 'string' ? JSON.parse(trace) : trace;
	} catch (e) {
		throw new Error('Speedline: Invalid JSON' + e.message);
	}
	let events = trace.traceEvents || trace;
	events = events.sort((a, b) => a.ts - b.ts).filter(e => e.ts !== 0);

	const start = events[0].ts / 1000;
	const end = events[events.length - 1].ts / 1000;

	const rawScreenshots = events.filter(e => e.cat.includes(screenshot_trace_category));
	const frames = rawScreenshots.map(function (evt) {
		const base64img = evt.args && evt.args.snapshot;
		const timestamp = evt.ts / 1000;

		const imgBuff = new Buffer(base64img, 'base64');
		return frame(imgBuff, timestamp);
	});

	const firstFrame = frame(frames[0].getImage(), start);
	const lastFrame = frame(frames[frames.length - 1].getImage(), end);
	return Promise.resolve([firstFrame, ...frames, lastFrame]);
}

function frame(imgBuff, ts) {
	let _histogram = null;
	let _progress = null;
	let _perceptualProgress = null;

	return {
		getHistogram: function () {
			if (_histogram) {
				return _histogram;
			}

			const pixels = jpeg.decode(imgBuff);
			_histogram = convertPixelsToHistogram(pixels);
			return _histogram;
		},

		getTimeStamp: function () {
			return ts;
		},

		setProgress: function (progress) {
			_progress = progress;
		},

		setPerceptualProgress: function (progress) {
			_perceptualProgress = progress;
		},

		getImage: function () {
			return imgBuff;
		},

		getParsedImage: function () {
			return jpeg.decode(imgBuff);
		},

		getProgress: function () {
			return _progress;
		},

		getPerceptualProgress: function () {
			return _perceptualProgress;
		}
	};
}

module.exports = {
	extractFramesFromTimeline,
	create: frame
};
<commit_msg>lint fixes.<commit_after>'use strict';

import fs from 'fs';
import jpeg from 'jpeg-js';

function getPixel(x, y, channel, width, buff) {
	return buff[(x + y * width) * 4 + channel];
}

function convertPixelsToHistogram(img) {
	const createHistogramArray = function () {
		const ret = new Array(256);
		for (let i = 0; i < ret.length; i++) {
			ret[i] = 0;
		}
		return ret;
	};

	const width = img.width;
	const height = img.height;

	const histograms = [
		createHistogramArray(),
		createHistogramArray(),
		createHistogramArray()
	];

	for (let channel = 0; channel < histograms.length; channel++) {
		for (let i = 0; i < width; i++) {
			for (let j = 0; j < height; j++) {
				const pixelValue = getPixel(i, j, channel, width, img.data);

				// Erase pixels considered as white
				if (getPixel(i, j, 0, width, img.data) < 249 &&
						getPixel(i, j, 1, width, img.data) < 249 &&
						getPixel(i, j, 2, width, img.data) < 249) {
					histograms[channel][pixelValue]++;
				}
			}
		}
	}

	return histograms;
}

const screenshotTraceCategory = 'disabled-by-default-devtools.screenshot';
function extractFramesFromTimeline(timeline) {
	let trace;
	trace = typeof timeline === 'string' ? fs.readFileSync(timeline, 'utf-8') : timeline;
	try {
		trace = typeof trace === 'string' ? JSON.parse(trace) : trace;
	} catch (e) {
		throw new Error('Speedline: Invalid JSON' + e.message);
	}
	let events = trace.traceEvents || trace;
	events = events.sort((a, b) => a.ts - b.ts).filter(e => e.ts !== 0);

	const start = events[0].ts / 1000;
	const end = events[events.length - 1].ts / 1000;

	const rawScreenshots = events.filter(e => e.cat.includes(screenshotTraceCategory));
	const frames = rawScreenshots.map(function (evt) {
		const base64img = evt.args && evt.args.snapshot;
		const timestamp = evt.ts / 1000;

		const imgBuff = new Buffer(base64img, 'base64');
		return frame(imgBuff, timestamp);
	});

	const firstFrame = frame(frames[0].getImage(), start);
	const lastFrame = frame(frames[frames.length - 1].getImage(), end);
	return Promise.resolve([firstFrame, ...frames, lastFrame]);
}

function frame(imgBuff, ts) {
	let _histogram = null;
	let _progress = null;
	let _perceptualProgress = null;

	return {
		getHistogram: function () {
			if (_histogram) {
				return _histogram;
			}

			const pixels = jpeg.decode(imgBuff);
			_histogram = convertPixelsToHistogram(pixels);
			return _histogram;
		},

		getTimeStamp: function () {
			return ts;
		},

		setProgress: function (progress) {
			_progress = progress;
		},

		setPerceptualProgress: function (progress) {
			_perceptualProgress = progress;
		},

		getImage: function () {
			return imgBuff;
		},

		getParsedImage: function () {
			return jpeg.decode(imgBuff);
		},

		getProgress: function () {
			return _progress;
		},

		getPerceptualProgress: function () {
			return _perceptualProgress;
		}
	};
}

module.exports = {
	extractFramesFromTimeline,
	create: frame
};
<|endoftext|>


<commit_before>/**
 * Created by ABuchholz on 2015-06-12.
 */
<commit_msg>fs_ms (WIP)<commit_after>/*#ifndef(UMD)*/
"use strict";
/*global _GPF_EVENT_ERROR*/ // gpf.events.EVENT_ERROR
/*global _GPF_EVENT_READY*/ // gpf.events.EVENT_READY
/*global _GPF_FS_TYPE_DIRECTORY*/ // _GPF_FS_TYPE_DIRECTORY
/*global _GPF_FS_TYPE_FILE*/ // _GPF_FS_TYPE_FILE
/*global _GPF_FS_TYPE_NOT_FOUND*/ // _GPF_FS_TYPE_NOT_FOUND
/*global _GPF_FS_TYPE_UNKNOWN*/ // _GPF_FS_TYPE_UNKNOWN
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfEventsFire*/ // gpf.events.fire (internal, parameters must match)
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _gpfInNode*/ // The current host is a nodeJS like
/*global _gpfMsFSO:true*/ // Scripting.FileSystemObject activeX
/*#endif*/

var
    /**
     * @type {gpf.fs.WScriptFileStorage}
     * @private
     */
    _gpfWScriptFileStorage;

_gpfDefine("gpf.fs.WScriptFileStorage", {

    public: {

        constructor: function () {
            if (!_gpfMsFSO) {
                _gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");
            }
        },

        //region IFileStorage

        /**
         * @inheritdoc IFileStorage#getInfo
         */
        getInfo: function (path, eventsHandler) {
            _gpfNodeFs.exists(path, function (exists) {
                if (exists) {
                    _gpfNodeFs.stat(path, function (err, stats) {
                        var result;
                        if (err) {
                            _gpfFireNodeError(err, eventsHandler);
                        } else {
                            result = {
                                fileName: _gpfNodePath.basename(path),
                                filePath: _gpfNodePath.resolve(path),
                                size: stats.size,
                                createdDateTime: stats.ctime,
                                modifiedDateTime: stats.mtime
                            };
                            if (stats.isDirectory()) {
                                result.type = _GPF_FS_TYPE_DIRECTORY;
                            } else if (stats.isFile()) {
                                result.type = _GPF_FS_TYPE_FILE;
                            } else {
                                result.type = _GPF_FS_TYPE_UNKNOWN;
                            }
                            _gpfEventsFire.apply(null, [
                                _GPF_EVENT_READY,
                                {
                                    info: result
                                },
                                eventsHandler
                            ]);
                        }
                    });
                } else {
                    _gpfEventsFire.apply(null, [
                        _GPF_EVENT_READY,
                        {
                            info: {
                                type: _GPF_FS_TYPE_NOT_FOUND
                            }
                        },
                        eventsHandler
                    ]);
                }
            });
        },

        /**
         * @inheritdoc IFileStorage#readAsBinaryStream
         */
        readAsBinaryStream: function (path, eventsHandler) {
            // TODO handle error
            var nodeStream = _gpfNodeFs.createReadStream(path);
            _gpfEventsFire.apply(null, [
                _GPF_EVENT_READY,
                {
                    stream: new gpf.node.ReadableStream(nodeStream)
                },
                eventsHandler
            ]);
        },

        /**
         * @inheritdoc IFileStorage#writeAsBinaryStream
         */
        writeAsBinaryStream: function (path, eventsHandler) {
            // TODO handle error
            var nodeStream = _gpfNodeFs.createWriteStream(path);
            _gpfEventsFire.apply(null, [
                _GPF_EVENT_READY,
                {
                    stream: new gpf.node.WritableStream(nodeStream)
                },
                eventsHandler
            ]);
        },

        /**
         * @inheritdoc IFileStorage#close
         */
        close: function (stream) {
            _gpfIgnore(stream);
            // TODO not sure what I should do with it...
        },

        /**
         * @inheritdoc IFileStorage#explore
         */
        explore: function (path, eventsHandler) {
            _gpfIgnore(path);
            _gpfIgnore(eventsHandler);
            // use _gpfNodeFs.readdir
        }

        //endregion

    }

});

if (_gpfInNode) {

    /**
     * @inheritdoc gpf.fs#host
     * WScript version
     */
    gpf.fs.host = function () {
        if (!_gpfWScriptFileStorage) {
            _gpfWScriptFileStorage = new gpf.fs.WScriptFileStorage();
        }
        return _gpfWScriptFileStorage;
    };

}
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const program = require('commander');
const semver = require('semver');
const chalk = require('chalk');
const inquirer = require('inquirer');

const pkg = require('../package.json');
const logger = require('../lib/logger');
const generate = require('../lib/generator');

if (semver.satisfies(process.version, pkg.engines.node) === false) {
    logger.fatal(`Your current version of Node.js doesn't satisfy the minimun requirement: ${pkg.engines.node}`);
    return;
}

/**
 * Usage.
 */

program
    .version(pkg.version)
    .usage('[<namespace>/]<template> [options]')
    .option('--verbose', 'Verbose output')
    .option('--log-level <n>', `Log levels: ${logger.asString()}`, parseInt);

/**
 * Help.
 */

program.on('--help', () => {
    console.log('  Examples:');
    console.log();
    console.log(chalk.gray('    # scaffold using template in ./scaffold/component/template'));
    console.log('    $ umeboshi scaffold component');
    console.log();
    console.log(chalk.gray('    # scaffold using template in ./scaffold/react/stateless/template'));
    console.log('    $ umeboshi scaffold react/stateless');
    console.log();
});

program.parse(process.argv);
if (program.args.length < 1) {
    return program.help();
}

if (!program.verbose && Number.isFinite(program.logLevel)) {
    logger.setLevel(program.logLevel);
} else if (program.verbose) {
    logger.setLevel(0);
}

logger.verbose(`Program started with arguments: ${program.args.join(', ')}`);

const input = program.args[0];
const [match, namespace, template = ''] = input.match(/^([^/]+)(?:\/([^/]+)|)$/) || [];

if (!namespace) {
    logger.fatal(`invalid namespace "${namespace}"`);
    return;
}

const folderList = [
    path.join(process.cwd(), 'scaffold', namespace, template),
    path.join(process.cwd(), 'node_modules', `umeboshi-scaffold-${namespace}`, template)
];

logger.verbose(`Looking for template in: ${folderList.join(', ')}`);

const workingFolder = folderList.find(fs.existsSync);

if (!workingFolder) {
    logger.fatal(`Template "${input}" not found`);
    return;
}

logger.verbose(`Template "${input}" resolved as "${workingFolder}"`);

try {
    const templateIndex = path.join(workingFolder, 'index.js');
    const customizer = fs.existsSync(templateIndex) ? require(templateIndex) : {};
    const { prompts = () => [] } = customizer;

    const completed = (err) => {
        if (err) {
            logger.fatal(`Scaffolding failed: ${err.message.trim()}`);
            return;
        }
        logger.message('Scaffolding completed!\n');
    };

    inquirer
        .prompt(prompts({ program, namespace, template }))
        .then((answers) => {
            if (!answers.to) {
                completed(new Error('You must provide a "to" path string as file destination folder'))
                return;
            }
            answers.to = path.resolve(process.cwd(), answers.to);
            logger.verbose(`Running with options "${JSON.stringify(answers)}`);
            generate(Object.assign({ command: 'scaffold' }, answers, {
                src: workingFolder
            }), completed);
        });
} catch (e) {
    logger.fatal(e);
}<commit_msg>refactor(scaffold): refactoring<commit_after>const fs = require('fs');
const path = require('path');

const program = require('commander');
const semver = require('semver');
const chalk = require('chalk');
const inquirer = require('inquirer');

const pkg = require('../package.json');
const logger = require('../lib/logger');
const generate = require('../lib/generator');

if (semver.satisfies(process.version, pkg.engines.node) === false) {
    logger.fatal(`[scaffold] Your current version of Node.js doesn't satisfy the minimun requirement: ${pkg.engines.node}`);
    return;
}

/**
 * Usage.
 */

program
    .version(pkg.version)
    .usage('[<namespace>/]<template> [options]')
    .option('--verbose', 'Verbose output')
    .option('--log-level <n>', `Log levels: ${logger.asString()}`, parseInt);

/**
 * Help.
 */

program.on('--help', () => {
    logger.log('  Examples:');
    logger.log();
    logger.log(chalk.gray('    # scaffold using template in ./scaffold/component/template'));
    logger.log('    $ umeboshi scaffold component');
    logger.log();
    logger.log(chalk.gray('    # scaffold using template in ./scaffold/react/stateless/template'));
    logger.log('    $ umeboshi scaffold react/stateless');
    logger.log();
});

program.parse(process.argv);
if (program.args.length < 1) {
    return program.help();
}

if (!program.verbose && Number.isFinite(program.logLevel)) {
    logger.setLevel(program.logLevel);
} else if (program.verbose) {
    logger.setLevel(0);
}

logger.verbose(`[scaffold] Program started with arguments: ${program.args.join(', ')}`);

const input = program.args[0];
const [match, namespace, template = ''] = input.match(/^([^/]+)(?:\/([^/]+)|)$/) || [];

if (!namespace) {
    logger.fatal(`[scaffold] Invalid namespace "${namespace}"`);
    return;
}

const folderList = [
    path.join(process.cwd(), 'scaffold', namespace, template),
    path.join(process.cwd(), 'node_modules', `umeboshi-scaffold-${namespace}`, template)
];

logger.verbose(`[scaffold] Looking for template in: ${folderList.join(', ')}`);

const workingFolder = folderList.find(fs.existsSync);

if (!workingFolder) {
    logger.fatal(`[scaffold] Template "${input}" not found`);
    return;
}

logger.verbose(`[scaffold] Template "${input}" resolved as "${workingFolder}"`);

try {
    const templateIndex = path.join(workingFolder, 'index.js');
    const customizer = fs.existsSync(templateIndex) ? require(templateIndex) : {};
    const { prompts = () => [] } = customizer;

    const completed = (err) => {
        if (err) {
            logger.fatal(`[scaffold] Scaffolding failed: ${err.message.trim()}`);
            return;
        }
        logger.message('[scaffold] Scaffolding completed!\n');
    };

    inquirer
        .prompt(prompts({ program, namespace, template }))
        .then((answers) => {
            if (!answers.to) {
                completed(new Error('You must provide a "to" path string as file destination folder'))
                return;
            }
            answers.to = path.resolve(process.cwd(), answers.to);
            logger.verbose(`[scaffold] Running with options "${JSON.stringify(answers)}`);
            generate(Object.assign({ command: 'scaffold' }, answers, {
                src: workingFolder
            }), completed);
        });
} catch (e) {
    logger.fatal(`[scaffold] ${e.toString()}`);
}<|endoftext|>


<commit_before>const util = require("util");
const Command = require("../base/Command");

class Showconf extends Command {
    constructor(Bot) {
        super(Bot, {
            guildOnly: true,
            name: "showconf",
            aliases: ["showconfs", "showconfig", "showconfigs"],
            category: "Admin",
            permLevel: 3
        });
    }

    async run(Bot, message, args, options) {
        let guildID = message.guild.id;
        let guildName = "";
        const client = message.client;

        // If I or an adminHelper adds a guild ID here, pull up that instead
        if (args[0] && options && options.level >= 9) {
            let found = false;
            if (!client.guilds.cache.has(args[0]) && client.shard) {
                const names = await client.shard.broadcastEval(`
                    if (this.guilds.cache.has('${args[0]}')) {
                        this.guilds.cache.get('${args[0]}').name;
                    }
                `);
                names.forEach(gName => {
                    if (gName !== null) {
                        found = true;
                        guildName = gName;
                    }
                });
            } else {
                guildName = client.guilds.cache.get(guildID).name;
                found = true;
            }
            if (found) {
                guildID = args[0];
            } else {
                return super.error(message, `Sorry, but I don't seem to be in the guild ${args[0]}.`);
            }

        } else {
            guildName = message.guild.name;
        }

        const guildConf = await Bot.getGuildConf(guildID);

        var array = [];
        if (guildConf) {
            for (const key of Object.keys(Bot.config.defaultSettings)) {
                const value = key === "changelogWebhook" ? util.inspect(guildConf[key]).slice(0, 92) + "..." : util.inspect(guildConf[key]);
                array.push(`* ${key}: ${value}`);
            }
            var configKeys = array.join("\n");
            return message.channel.send({content: message.language.get("COMMAND_SHOWCONF_OUTPUT", configKeys, guildName)}); //TODO , {split: true});
        } else {
            Bot.logger.error("Something broke in showconf");
        }
    }
}

module.exports = Showconf;
<commit_msg>Updated showconf's broadcastEval<commit_after>const util = require("util");
const Command = require("../base/Command");

class Showconf extends Command {
    constructor(Bot) {
        super(Bot, {
            guildOnly: true,
            name: "showconf",
            aliases: ["showconfs", "showconfig", "showconfigs"],
            category: "Admin",
            permLevel: 3
        });
    }

    async run(Bot, message, args, options) {
        let guildID = message.guild.id;
        let guildName = "";
        const client = message.client;

        // If I or an adminHelper adds a guild ID here, pull up that instead
        if (args[0] && options && options.level >= 9) {
            let found = false;
            if (!client.guilds.cache.has(args[0]) && client.shard) {
                const names = await client.shard.broadcastEval((client, args) => {
                    if (client.guilds.cache.has(args[0])) {
                        return client.guilds.cache.get(args[0]).name;
                    }
                }, {context: args});
                names.forEach(gName => {
                    if (gName !== null) {
                        found = true;
                        guildName = gName;
                    }
                });
            } else {
                guildName = client.guilds.cache.get(guildID).name;
                found = true;
            }
            if (found) {
                guildID = args[0];
            } else {
                return super.error(message, `Sorry, but I don't seem to be in the guild ${args[0]}.`);
            }

        } else {
            guildName = message.guild.name;
        }

        const guildConf = await Bot.getGuildConf(guildID);

        var array = [];
        if (guildConf) {
            for (const key of Object.keys(Bot.config.defaultSettings)) {
                const value = key === "changelogWebhook" && guildConf[key]?.length ? util.inspect(guildConf[key]).slice(0, 92) + "..." : util.inspect(guildConf[key]);
                array.push(`* ${key}: ${value}`);
            }
            var configKeys = array.join("\n");
            return message.channel.send({content: message.language.get("COMMAND_SHOWCONF_OUTPUT", configKeys, guildName)}); //TODO , {split: true});
        } else {
            Bot.logger.error("Something broke in showconf");
        }
    }
}

module.exports = Showconf;
<|endoftext|>


<commit_before>module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.user.username, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Nome cadastrado: `, value: `${member.user.username}` /*value: "[link](http://google.com)."*/ },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Cargo: `, value: `${member.user.position}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    });
  }
};<commit_msg><commit_after>module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.user.username, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Nome cadastrado: `, value: `${member.user.username}` /*value: "[link](http://google.com)."*/ },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    });
  }
};<|endoftext|>


<commit_before>(function() {

  /**
   * Constants
   */
  var min = Math.min, max = Math.max;

  var Group = Two.Group = function() {

    Two.Shape.call(this, true);

    this._renderer.type = 'group';

    this.additions = [];
    this.subtractions = [];

    this.children = {};

  };

  _.extend(Group, {

    MakeObservable: function(object) {

      Two.Shape.MakeObservable(object);
      Group.MakeGetterSetters(object, Two.Polygon.Properties);

    },

    MakeGetterSetters: function(group, properties) {

      if (!_.isArray(properties)) {
        properties = [properties];
      }

      _.each(properties, function(k) {
        Group.MakeGetterSetter(group, k);
      });

    },

    MakeGetterSetter: function(group, k) {

      var secret = '_' + k;

      Object.defineProperty(group, k, {
        get: function() {
          return this[secret];
        },
        set: function(v) {
          this[secret] = v;
          _.each(this.children, function(child) { // Trickle down styles
            child[k] = v;
          });
        }
      });

    }

  });

  _.extend(Group.prototype, Two.Shape.prototype, {

    // Flags
    // http://en.wikipedia.org/wiki/Flag

    _flagAdditions: false,
    _flagSubtractions: false,

    // Underlying Properties

    _fill: '#fff',
    _stroke: '#000',
    _linewidth: 1.0,
    _opacity: 1.0,
    _visible: true,

    _cap: 'round',
    _join: 'round',
    _miter: 4,

    _closed: true,
    _curved: false,
    _automatic: true,
    _beginning: 0,
    _ending: 1.0,

    /**
     * Group has a gotcha in that it's at the moment required to be bound to
     * an instance of two in order to add elements correctly. This needs to
     * be rethought and fixed.
     */
    clone: function(parent) {

      parent = parent || this.parent;

      var group = new Group();
      parent.add(group);

      var children = _.map(this.children, function(child) {
        return child.clone(group);
      });

      group.translation.copy(this.translation);
      group.rotation = this.rotation;
      group.scale = this.scale;

      return group;

    },

    toObject: function() {

      var result = {
        children: {},
        translation: this.translation.toObject(),
        rotation: this.rotation,
        scale: this.scale
      };

      _.each(this.children, function(child, i) {
        result.children[i] = child.toObject();
      }, this);

      return result;

    },

    /**
     * Anchor all children to the upper left hand corner
     * of the group.
     */
    corner: function() {

      var rect = this.getBoundingClientRect(true),
       corner = { x: rect.left, y: rect.top };

      _.each(this.children, function(child) {
        child.translation.subSelf(corner);
      });

      return this;

    },

    /**
     * Anchors all children around the center of the group,
     * effectively placing the shape around the unit circle.
     */
    center: function() {

      var rect = this.getBoundingClientRect(true);

      rect.centroid = {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
      };

      _.each(this.children, function(child) {
        child.translation.subSelf(rect.centroid);
      });

      // this.translation.copy(rect.centroid);

      return this;

    },

    /**
     * Recursively search for id. Returns the first element found.
     * Returns null if none found.
     */
    getById: function (id) {
      var found;
      var search = function (node, id) {
        if (node.id == id) {
          found = node;
          return node;
        }
        for (var child in node.children) {
          if (found) return found;
          search(node.children[child], id);
        }
      };
      return search(this, id) || null;
    },

    /**
     * Recursively search for classes. Returns an array of matching elements.
     * Empty array if none found.
     */
    getByClassName: function (cl) {
      var found = [];
      var search = function (node, cl) {
        if (node.classList.indexOf(cl) != -1) {
          found.push(node);
        }
        for (var child in node.children) {
          search(node.children[child], cl);
        }
        return found;
      };
      return search(this, cl);
    },

    /**
     * Recursively search for children of a specific type,
     * e.g. Two.Polygon. Pass a reference to this type as the param.
     * Returns an empty array if none found.
     */
    getByType: function(type) {
      var found = [];
      var search = function (node, type) {
        for (var id in node.children) {
          if (node.children[id] instanceof type) {
            found.push(node.children[id]);
          } else if (node.children[id] instanceof Two.Group) {
            search(node.children[id], type);
          }
        }
        return found;
      };
      return search(this, type);
    },

    /**
     * Add objects to the group.
     */
    add: function(objects) {

      var l = arguments.length,
        children = this.children,
        grandparent = this.parent,
        ids = this.additions,
        id, parent, index;

      if (!_.isArray(objects)) {
        objects = _.toArray(arguments);
      }

      // Add the objects

      _.each(objects, function(object) {

        if (!object) {
          return;
        }

        id = object.id;
        parent = object.parent;

        if (_.isUndefined(children[id])) {
          // Release object from previous parent.
          if (parent) {
            delete parent.children[id];
            index = _.indexOf(parent.additions, id);
            if (index >= 0) {
              parent.additions.splice(index, 1);
            }
          }
          // Add it to this group and update parent-child relationship.
          children[id] = object;
          object.parent = this;
          ids.push(id);
          this._flagAdditions = true;
        }

      }, this);

      return this;

    },

    /**
     * Remove objects from the group.
     */
    remove: function(objects) {

      var l = arguments.length,
        children = this.children,
        grandparent = this.parent,
        ids = this.subtractions,
        id, parent, index, grandchildren;

      if (l <= 0 && grandparent) {
        grandparent.remove(this);
        return this;
      }

      if (!_.isArray(objects)) {
        objects = _.toArray(arguments);
      }

      _.each(objects, function(object) {

        id = object.id;
        grandchildren = object.children;
        parent = object.parent;

        if (!(id in children)) {
          return;
        }

        delete children[id];
        delete object.parent;

        index = _.indexOf(parent.additions, id);
        if (index >= 0) {
          parent.additions.splice(index, 1);
        }

        ids.push(id);
        this._flagSubtractions = true;

      }, this);

      return this;

    },

    /**
     * Return an object with top, left, right, bottom, width, and height
     * parameters of the group.
     */
    getBoundingClientRect: function() {
      var rect;

      // TODO: Update this to not __always__ update. Just when it needs to.
      this._update();

      // Variables need to be defined here, because of nested nature of groups.
      var left = Infinity, right = -Infinity,
          top = Infinity, bottom = -Infinity;

      _.each(this.children, function(child) {

        rect = child.getBoundingClientRect();

        if (!_.isNumber(rect.top)   || !_.isNumber(rect.left)   ||
            !_.isNumber(rect.right) || !_.isNumber(rect.bottom)) {
          return;
        }

        top = min(rect.top, top);
        left = min(rect.left, left);
        right = max(rect.right, right);
        bottom = max(rect.bottom, bottom);

      }, this);

      return {
        top: top,
        left: left,
        right: right,
        bottom: bottom,
        width: right - left,
        height: bottom - top
      };

    },

    /**
     * Trickle down of noFill
     */
    noFill: function() {
      _.each(this.children, function(child) {
        child.noFill();
      });
      return this;
    },

    /**
     * Trickle down of noStroke
     */
    noStroke: function() {
      _.each(this.children, function(child) {
        child.noStroke();
      });
      return this;
    },

    /**
     * Trickle down subdivide
     */
    subdivide: function() {
      var args = arguments;
      _.each(this.children, function(child) {
        child.subdivide.apply(child, args);
      });
      return this;
    },

    flagReset: function() {

      if (this._flagAdditions) {
        this.additions.length = 0;
        this._flagAdditions = false;
      }

      if (this._flagSubtractions) {
        this.subtractions.length = 0;
        this._flagSubtractions = false;
      }

      Two.Shape.prototype.flagReset.call(this);

      return this;

    }

  });

  Group.MakeObservable(Group.prototype);

})();
<commit_msg>Fix a bug in the recursive implementation of getById<commit_after>(function() {

  /**
   * Constants
   */
  var min = Math.min, max = Math.max;

  var Group = Two.Group = function() {

    Two.Shape.call(this, true);

    this._renderer.type = 'group';

    this.additions = [];
    this.subtractions = [];

    this.children = {};

  };

  _.extend(Group, {

    MakeObservable: function(object) {

      Two.Shape.MakeObservable(object);
      Group.MakeGetterSetters(object, Two.Polygon.Properties);

    },

    MakeGetterSetters: function(group, properties) {

      if (!_.isArray(properties)) {
        properties = [properties];
      }

      _.each(properties, function(k) {
        Group.MakeGetterSetter(group, k);
      });

    },

    MakeGetterSetter: function(group, k) {

      var secret = '_' + k;

      Object.defineProperty(group, k, {
        get: function() {
          return this[secret];
        },
        set: function(v) {
          this[secret] = v;
          _.each(this.children, function(child) { // Trickle down styles
            child[k] = v;
          });
        }
      });

    }

  });

  _.extend(Group.prototype, Two.Shape.prototype, {

    // Flags
    // http://en.wikipedia.org/wiki/Flag

    _flagAdditions: false,
    _flagSubtractions: false,

    // Underlying Properties

    _fill: '#fff',
    _stroke: '#000',
    _linewidth: 1.0,
    _opacity: 1.0,
    _visible: true,

    _cap: 'round',
    _join: 'round',
    _miter: 4,

    _closed: true,
    _curved: false,
    _automatic: true,
    _beginning: 0,
    _ending: 1.0,

    /**
     * Group has a gotcha in that it's at the moment required to be bound to
     * an instance of two in order to add elements correctly. This needs to
     * be rethought and fixed.
     */
    clone: function(parent) {

      parent = parent || this.parent;

      var group = new Group();
      parent.add(group);

      var children = _.map(this.children, function(child) {
        return child.clone(group);
      });

      group.translation.copy(this.translation);
      group.rotation = this.rotation;
      group.scale = this.scale;

      return group;

    },

    toObject: function() {

      var result = {
        children: {},
        translation: this.translation.toObject(),
        rotation: this.rotation,
        scale: this.scale
      };

      _.each(this.children, function(child, i) {
        result.children[i] = child.toObject();
      }, this);

      return result;

    },

    /**
     * Anchor all children to the upper left hand corner
     * of the group.
     */
    corner: function() {

      var rect = this.getBoundingClientRect(true),
       corner = { x: rect.left, y: rect.top };

      _.each(this.children, function(child) {
        child.translation.subSelf(corner);
      });

      return this;

    },

    /**
     * Anchors all children around the center of the group,
     * effectively placing the shape around the unit circle.
     */
    center: function() {

      var rect = this.getBoundingClientRect(true);

      rect.centroid = {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
      };

      _.each(this.children, function(child) {
        child.translation.subSelf(rect.centroid);
      });

      // this.translation.copy(rect.centroid);

      return this;

    },

    /**
     * Recursively search for id. Returns the first element found.
     * Returns null if none found.
     */
    getById: function (id) {
      var search = function (node, id) {
        if (node.id === id) {
          return node;
        }
        for (var child in node.children) {
          var found = search(node.children[child], id);
          if (found) return found;
        }
      };
      return search(this, id) || null;
    },

    /**
     * Recursively search for classes. Returns an array of matching elements.
     * Empty array if none found.
     */
    getByClassName: function (cl) {
      var found = [];
      var search = function (node, cl) {
        if (node.classList.indexOf(cl) != -1) {
          found.push(node);
        }
        for (var child in node.children) {
          search(node.children[child], cl);
        }
        return found;
      };
      return search(this, cl);
    },

    /**
     * Recursively search for children of a specific type,
     * e.g. Two.Polygon. Pass a reference to this type as the param.
     * Returns an empty array if none found.
     */
    getByType: function(type) {
      var found = [];
      var search = function (node, type) {
        for (var id in node.children) {
          if (node.children[id] instanceof type) {
            found.push(node.children[id]);
          } else if (node.children[id] instanceof Two.Group) {
            search(node.children[id], type);
          }
        }
        return found;
      };
      return search(this, type);
    },

    /**
     * Add objects to the group.
     */
    add: function(objects) {

      var l = arguments.length,
        children = this.children,
        grandparent = this.parent,
        ids = this.additions,
        id, parent, index;

      if (!_.isArray(objects)) {
        objects = _.toArray(arguments);
      }

      // Add the objects

      _.each(objects, function(object) {

        if (!object) {
          return;
        }

        id = object.id;
        parent = object.parent;

        if (_.isUndefined(children[id])) {
          // Release object from previous parent.
          if (parent) {
            delete parent.children[id];
            index = _.indexOf(parent.additions, id);
            if (index >= 0) {
              parent.additions.splice(index, 1);
            }
          }
          // Add it to this group and update parent-child relationship.
          children[id] = object;
          object.parent = this;
          ids.push(id);
          this._flagAdditions = true;
        }

      }, this);

      return this;

    },

    /**
     * Remove objects from the group.
     */
    remove: function(objects) {

      var l = arguments.length,
        children = this.children,
        grandparent = this.parent,
        ids = this.subtractions,
        id, parent, index, grandchildren;

      if (l <= 0 && grandparent) {
        grandparent.remove(this);
        return this;
      }

      if (!_.isArray(objects)) {
        objects = _.toArray(arguments);
      }

      _.each(objects, function(object) {

        id = object.id;
        grandchildren = object.children;
        parent = object.parent;

        if (!(id in children)) {
          return;
        }

        delete children[id];
        delete object.parent;

        index = _.indexOf(parent.additions, id);
        if (index >= 0) {
          parent.additions.splice(index, 1);
        }

        ids.push(id);
        this._flagSubtractions = true;

      }, this);

      return this;

    },

    /**
     * Return an object with top, left, right, bottom, width, and height
     * parameters of the group.
     */
    getBoundingClientRect: function() {
      var rect;

      // TODO: Update this to not __always__ update. Just when it needs to.
      this._update();

      // Variables need to be defined here, because of nested nature of groups.
      var left = Infinity, right = -Infinity,
          top = Infinity, bottom = -Infinity;

      _.each(this.children, function(child) {

        rect = child.getBoundingClientRect();

        if (!_.isNumber(rect.top)   || !_.isNumber(rect.left)   ||
            !_.isNumber(rect.right) || !_.isNumber(rect.bottom)) {
          return;
        }

        top = min(rect.top, top);
        left = min(rect.left, left);
        right = max(rect.right, right);
        bottom = max(rect.bottom, bottom);

      }, this);

      return {
        top: top,
        left: left,
        right: right,
        bottom: bottom,
        width: right - left,
        height: bottom - top
      };

    },

    /**
     * Trickle down of noFill
     */
    noFill: function() {
      _.each(this.children, function(child) {
        child.noFill();
      });
      return this;
    },

    /**
     * Trickle down of noStroke
     */
    noStroke: function() {
      _.each(this.children, function(child) {
        child.noStroke();
      });
      return this;
    },

    /**
     * Trickle down subdivide
     */
    subdivide: function() {
      var args = arguments;
      _.each(this.children, function(child) {
        child.subdivide.apply(child, args);
      });
      return this;
    },

    flagReset: function() {

      if (this._flagAdditions) {
        this.additions.length = 0;
        this._flagAdditions = false;
      }

      if (this._flagSubtractions) {
        this.subtractions.length = 0;
        this._flagSubtractions = false;
      }

      Two.Shape.prototype.flagReset.call(this);

      return this;

    }

  });

  Group.MakeObservable(Group.prototype);

})();
<|endoftext|>


<commit_before>const byID = {
	'0': 'checkmark', // green checkmark ✔
	'1': '?', // blue question mark ❓
	'2': '!', // red exclamation mark ❗
	'3': 'star', // orange star 🟊
	'4': 'crossmark', // bright red crossmark ❌
	'5': 'cross', // dark red cross 🕇
	'6': 'mouth', // mouth with red lips 👄
	'7': 'shovel', // shovel ⛏
	'8': 'sword', // sword ⚔
	'9': 'flag', // blue flag ⚑
	'10': 'lock', // golden lock 🔒
	'11': 'bag', // brown bag 👛
	'12': 'skull', // skull 💀
	'13': '$', // green dollar sign 💰💲
	'14': 'red up', // red arrow up ⬆🔺
	'15': 'red down', // red arrow down ⬇🔻
	'16': 'red right', // red arrow right ➡
	'17': 'red left', // red arrow left ⬅
	'18': 'up', // green arrow up ⬆
	'19': 'down' // green arrow down ⬇
};

const byName = {};
Object.keys(byID).forEach(function(id) {
	const name = byID[id];
	byName[name] = id;
});

module.exports = {
	byID: byID,
	byName: byName
};
<commit_msg>Ensure icon IDs are numeric<commit_after>const byID = {
	'0': 'checkmark', // green checkmark ✔
	'1': '?', // blue question mark ❓
	'2': '!', // red exclamation mark ❗
	'3': 'star', // orange star 🟊
	'4': 'crossmark', // bright red crossmark ❌
	'5': 'cross', // dark red cross 🕇
	'6': 'mouth', // mouth with red lips 👄
	'7': 'shovel', // shovel ⛏
	'8': 'sword', // sword ⚔
	'9': 'flag', // blue flag ⚑
	'10': 'lock', // golden lock 🔒
	'11': 'bag', // brown bag 👛
	'12': 'skull', // skull 💀
	'13': '$', // green dollar sign 💰💲
	'14': 'red up', // red arrow up ⬆🔺
	'15': 'red down', // red arrow down ⬇🔻
	'16': 'red right', // red arrow right ➡
	'17': 'red left', // red arrow left ⬅
	'18': 'up', // green arrow up ⬆
	'19': 'down' // green arrow down ⬇
};

const byName = {};
Object.keys(byID).forEach(function(id) {
	const name = byID[id];
	byName[name] = Number(id);
});

module.exports = {
	byID: byID,
	byName: byName
};
<|endoftext|>


<commit_before>import {Origin} from 'aurelia-metadata';
import {Loader} from 'aurelia-loader';

let polyfilled = false;
let url = null;

if(!window.System || !window.System.import){
  var sys = window.System = window.System || {};

  sys.polyfilled = polyfilled = true;
  sys.isFake = false;
  sys.map = {};

  sys['import'] = function(moduleId){
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  sys.normalize = function(url){
    return Promise.resolve(url);
  };

  if(window.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    var defined = requirejs.s.contexts._.defined;
    sys.forEachModule = function(callback){
      for(var key in defined){
        if(callback(key, defined[key])) return;
      }
    };
  }else{
    sys.forEachModule = function(callback){};
  }
}else{
  var modules = System._loader.modules;
  url = typeof URL != 'undefined' ? URL : URLPolyfill;
  System.isFake = false;
  System.forEachModule = function(callback){
    for (var key in modules) {
      if(callback(key, modules[key].module)) return;
    }
  };
}

function ensureOriginOnExports(executed, name){
  var target = executed,
      key, exportedValue;

  if(target.__useDefault){
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === "function") {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

function getCanonicalName(loader, normalized) {
  // remove the plugin part first
  var pluginIndex = normalized.indexOf('!');
  var plugin;
  if (pluginIndex != -1) {
    plugin = normalized.substr(pluginIndex + 1);
    normalized = normalized.substr(0, pluginIndex);
  }

  // defaultJSExtensions handling
  if (loader.defaultJSExtensions && normalized.split('/').pop().split('.').pop() == 'js') {
    // if we're in a package that disables defaultJSExtensions, leave as-is
    var isDefaultExtensionPackage = false;
    for (var p in loader.packages) {
      if (normalized.substr(0, p.length) == p && (normalized.length == p.length || normalized[p.length] == '/')) {
        if ('defaultExtension' in loader.packages[p])
          isDefaultExtensionPackage = true;
      }
    }

    // remove defaultJSExtension
    if (!isDefaultExtensionPackage)
      normalized = normalized.substr(0, normalized.length - 3);
  }

  // now just reverse apply paths rules to get canonical name
  var pathMatch, pathMatchLength = 0;
  var curMatchlength;
  for (var p in loader.paths) {
    // normalize the output path
    var curPath = new url(loader.paths[p], loader.baseURL).href;

    // do reverse match
    var wIndex = curPath.indexOf('*');
    if (wIndex === -1) {
      if (normalized === curPath) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p;
          pathMatchLength = curMatchLength;
        }
      }
    }
    else {
      if (normalized.substr(0, wIndex) === curPath.substr(0, wIndex)
        && normalized.substr(normalized.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p.replace('*', normalized.substr(wIndex, normalized.length - curPath.length + 1));
          pathMatchLength = curMatchLength;
        }
      }
    }
  }

  // when no path was matched, act like the standard rule is *: baseURL/*
  if (!pathMatch) {
    if (normalized.substr(0, loader.baseURL.length) == loader.baseURL)
      pathMatch = normalized.substr(loader.baseURL.length);
    else
      pathMatch = normalized;
  }

  if (plugin)
    pathMatch += '!' + getCanonicalName(loader, plugin);

  return pathMatch;
}

export class DefaultLoader extends Loader {
  constructor(){
    super();

    this.moduleRegistry = {};
    var that = this;

    if(polyfilled){
      define('view', [], {
        'load': function (name, req, onload, config) {
          var entry = that.getOrCreateTemplateRegistryEntry(name),
              address;

          if(entry.templateIsLoaded){
            onload(entry);
            return;
          }

          that.findBundledTemplate(name, entry).then(found => {
            if(found){
              onload(entry);
            }else{
              address = req.toUrl(name);

              that.importTemplate(address).then(template => {
                entry.setTemplate(template);
                onload(entry);
              });
            }
          });
        }
      });
    }else{
      System.set('view', System.newModule({
        'fetch': function(load, _fetch) {
          let name = System.normalizeSync ? getCanonicalName(this, load.name) : load.name;
          let id = name.substring(0, name.indexOf('!'));
          let entry = load.metadata.templateRegistryEntry = that.getOrCreateTemplateRegistryEntry(id);

          if(entry.templateIsLoaded) {
            return '';
          }

          return that.findBundledTemplate(name, entry).then(found => {
            if(found) {
              return '';
            }

            return that.importTemplate(load.address).then(template => {
              entry.setTemplate(template);
              return '';
            });
          });
        },
        'instantiate': function(load) {
          return load.metadata.templateRegistryEntry;
        }
      }));
    }
  }

  loadModule(id){
    return System.normalize(id).then(newId => {
      var existing = this.moduleRegistry[newId];
      if(existing){
        return existing;
      }

      return System.import(newId).then(m => {
        this.moduleRegistry[newId] = m;
        return ensureOriginOnExports(m, newId);
      });
    });
  }

  loadAllModules(ids){
    var loads = [];

    for(var i = 0, ii = ids.length; i < ii; ++i){
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  loadTemplate(url){
    return polyfilled ? System.import('view!' + url) : System.import(url + '!view');
  }

  loadText(url){
    return polyfilled ? System.import('text!' + url) : System.import(url + '!text');
  }
}

window.AureliaLoader = DefaultLoader;
<commit_msg>fix(index): various url canonicalization bugs<commit_after>import {Origin} from 'aurelia-metadata';
import {Loader} from 'aurelia-loader';

let polyfilled = false;
let url = null;

if(!window.System || !window.System.import){
  var sys = window.System = window.System || {};

  sys.polyfilled = polyfilled = true;
  sys.isFake = false;
  sys.map = {};

  sys['import'] = function(moduleId){
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  sys.normalize = function(url){
    return Promise.resolve(url);
  };

  if(window.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    var defined = requirejs.s.contexts._.defined;
    sys.forEachModule = function(callback){
      for(var key in defined){
        if(callback(key, defined[key])) return;
      }
    };
  }else{
    sys.forEachModule = function(callback){};
  }
}else{
  var modules = System._loader.modules, hasURL = false;

  try {
    hasURL = typeof URLPolyfill != 'undefined' || new URL('test:///').protocol == 'test:';
  }
  catch(e) {}

  url = hasURL ? URL : URLPolyfill;

  System.isFake = false;
  System.forEachModule = function(callback){
    for (var key in modules) {
      if(callback(key, modules[key].module)) return;
    }
  };
}

function ensureOriginOnExports(executed, name){
  var target = executed,
      key, exportedValue;

  if(target.__useDefault){
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === "function") {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

function getCanonicalName(loader, normalized) {
  // remove the plugin part first
  var pluginIndex = normalized.indexOf('!');
  var plugin;
  if (pluginIndex != -1) {
    plugin = normalized.substr(pluginIndex + 1);
    normalized = normalized.substr(0, pluginIndex);
  }

  // defaultJSExtensions handling
  if (loader.defaultJSExtensions && normalized.split('/').pop().split('.').pop() == 'js') {
    // if we're in a package that disables defaultJSExtensions, leave as-is
    var isDefaultExtensionPackage = false;
    for (var p in loader.packages) {
      if (normalized.substr(0, p.length) == p && (normalized.length == p.length || normalized[p.length] == '/')) {
        if ('defaultExtension' in loader.packages[p])
          isDefaultExtensionPackage = true;
      }
    }

    // remove defaultJSExtension
    if (!isDefaultExtensionPackage)
      normalized = normalized.substr(0, normalized.length - 3);
  }

  // now just reverse apply paths rules to get canonical name
  var pathMatch, pathMatchLength = 0;
  var curMatchLength;
  for (var p in loader.paths) {
    // normalize the output path
    var curPath = new url(loader.paths[p], loader.baseURL).href;

    // do reverse match
    var wIndex = curPath.indexOf('*');
    if (wIndex === -1) {
      if (normalized === curPath) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p;
          pathMatchLength = curMatchLength;
        }
      }
    }
    else {
      if (normalized.substr(0, wIndex) === curPath.substr(0, wIndex)
        && normalized.substr(normalized.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) {
        curMatchLength = curPath.split('/').length;
        if (curMatchLength > pathMatchLength) {
          pathMatch = p.replace('*', normalized.substr(wIndex, normalized.length - curPath.length + 1));
          pathMatchLength = curMatchLength;
        }
      }
    }
  }

  // when no path was matched, act like the standard rule is *: baseURL/*
  if (!pathMatch) {
    if (normalized.substr(0, loader.baseURL.length) == loader.baseURL)
      pathMatch = normalized.substr(loader.baseURL.length);
    else
      pathMatch = normalized;
  }

  if (plugin)
    pathMatch += '!' + getCanonicalName(loader, plugin);

  return pathMatch;
}

export class DefaultLoader extends Loader {
  constructor(){
    super();

    this.moduleRegistry = {};
    var that = this;

    if(polyfilled){
      define('view', [], {
        'load': function (name, req, onload, config) {
          var entry = that.getOrCreateTemplateRegistryEntry(name),
              address;

          if(entry.templateIsLoaded){
            onload(entry);
            return;
          }

          that.findBundledTemplate(name, entry).then(found => {
            if(found){
              onload(entry);
            }else{
              address = req.toUrl(name);

              that.importTemplate(address).then(template => {
                entry.setTemplate(template);
                onload(entry);
              });
            }
          });
        }
      });
    }else{
      System.set('view', System.newModule({
        'fetch': function(load, _fetch) {
          let name = getCanonicalName(this, load.name);
          let id = name.substring(0, name.indexOf('!'));
          let entry = load.metadata.templateRegistryEntry = that.getOrCreateTemplateRegistryEntry(id);

          if(entry.templateIsLoaded) {
            return '';
          }

          return that.findBundledTemplate(name, entry).then(found => {
            if(found) {
              return '';
            }

            return that.importTemplate(load.address).then(template => {
              entry.setTemplate(template);
              return '';
            });
          });
        },
        'instantiate': function(load) {
          return load.metadata.templateRegistryEntry;
        }
      }));
    }
  }

  loadModule(id){
    return System.normalize(id).then(newId => {
      var existing = this.moduleRegistry[newId];
      if(existing){
        return existing;
      }

      return System.import(newId).then(m => {
        this.moduleRegistry[newId] = m;
        return ensureOriginOnExports(m, newId);
      });
    });
  }

  loadAllModules(ids){
    var loads = [];

    for(var i = 0, ii = ids.length; i < ii; ++i){
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  loadTemplate(url){
    return polyfilled ? System.import('view!' + url) : System.import(url + '!view');
  }

  loadText(url){
    return polyfilled ? System.import('text!' + url) : System.import(url + '!text');
  }
}

window.AureliaLoader = DefaultLoader;
<|endoftext|>