<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Class = require('../../utils/Class');
var Components = require('../components');
var GameObject = require('../GameObject');
var IntegerToRGB = require('../../display/color/IntegerToRGB');
var PIPELINES_CONST = require('../../renderer/webgl/pipelines/const');
var Render = require('./PointLightRender');
var RGB = require('../../display/RGB');

/**
 * @classdesc
 *
 * TODO
 *
 * @class PointLight
 * @extends Phaser.GameObjects.GameObject
 * @memberof Phaser.GameObjects
 * @constructor
 * @since 3.50.0
 *
 * @extends Phaser.GameObjects.Components.AlphaSingle
 * @extends Phaser.GameObjects.Components.BlendMode
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.GetBounds
 * @extends Phaser.GameObjects.Components.Mask
 * @extends Phaser.GameObjects.Components.Pipeline
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 */
var PointLight = new Class({

    Extends: GameObject,

    Mixins: [
        Components.AlphaSingle,
        Components.BlendMode,
        Components.Depth,
        Components.GetBounds,
        Components.Mask,
        Components.Pipeline,
        Components.ScrollFactor,
        Components.Transform,
        Components.Visible,
        Render
    ],

    initialize:

    function PointLight (scene, x, y, color, radius, intensity, attenuation)
    {
        if (color === undefined) { color = 0xffffff; }
        if (radius === undefined) { radius = 128; }
        if (intensity === undefined) { intensity = 1; }
        if (attenuation === undefined) { attenuation = 0.1; }

        GameObject.call(this, scene, 'PointLight');

        this.initPipeline(PIPELINES_CONST.POINTLIGHT_PIPELINE);

        this.setPosition(x, y);

        var rgb = IntegerToRGB(color);

        this.color = new RGB(rgb.r, rgb.g, rgb.b);

        this.intensity = intensity;
        this.attenuation = attenuation;

        //  read only:
        this.width = radius * 2;
        this.height = radius * 2;

        this._radius = radius;
    },

    radius: {

        get: function ()
        {
            return this._radius;
        },

        set: function (value)
        {
            this._radius = value;
            this.width = value * 2;
            this.height = value * 2;
        }

    },

    originX: {

        get: function ()
        {
            return 0.5;
        }

    },

    originY: {

        get: function ()
        {
            return 0.5;
        }

    },

    displayOriginX: {

        get: function ()
        {
            return this._radius;
        }

    },

    displayOriginY: {

        get: function ()
        {
            return this._radius;
        }

    }

});

module.exports = PointLight;
<commit_msg>Swapped for Color component. Fix #5435<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Class = require('../../utils/Class');
var Components = require('../components');
var GameObject = require('../GameObject');
var IntegerToColor = require('../../display/color/IntegerToColor');
var PIPELINES_CONST = require('../../renderer/webgl/pipelines/const');
var Render = require('./PointLightRender');

/**
 * @classdesc
 *
 * TODO
 *
 * @class PointLight
 * @extends Phaser.GameObjects.GameObject
 * @memberof Phaser.GameObjects
 * @constructor
 * @since 3.50.0
 *
 * @extends Phaser.GameObjects.Components.AlphaSingle
 * @extends Phaser.GameObjects.Components.BlendMode
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.GetBounds
 * @extends Phaser.GameObjects.Components.Mask
 * @extends Phaser.GameObjects.Components.Pipeline
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 */
var PointLight = new Class({

    Extends: GameObject,

    Mixins: [
        Components.AlphaSingle,
        Components.BlendMode,
        Components.Depth,
        Components.GetBounds,
        Components.Mask,
        Components.Pipeline,
        Components.ScrollFactor,
        Components.Transform,
        Components.Visible,
        Render
    ],

    initialize:

    function PointLight (scene, x, y, color, radius, intensity, attenuation)
    {
        if (color === undefined) { color = 0xffffff; }
        if (radius === undefined) { radius = 128; }
        if (intensity === undefined) { intensity = 1; }
        if (attenuation === undefined) { attenuation = 0.1; }

        GameObject.call(this, scene, 'PointLight');

        this.initPipeline(PIPELINES_CONST.POINTLIGHT_PIPELINE);

        this.setPosition(x, y);

        this.color = IntegerToColor(color);

        this.intensity = intensity;
        this.attenuation = attenuation;

        //  read only:
        this.width = radius * 2;
        this.height = radius * 2;

        this._radius = radius;
    },

    radius: {

        get: function ()
        {
            return this._radius;
        },

        set: function (value)
        {
            this._radius = value;
            this.width = value * 2;
            this.height = value * 2;
        }

    },

    originX: {

        get: function ()
        {
            return 0.5;
        }

    },

    originY: {

        get: function ()
        {
            return 0.5;
        }

    },

    displayOriginX: {

        get: function ()
        {
            return this._radius;
        }

    },

    displayOriginY: {

        get: function ()
        {
            return this._radius;
        }

    }

});

module.exports = PointLight;
<|endoftext|>


<commit_before>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Sources.ScriptOriginPlugin = class extends Sources.UISourceCodeFrame.Plugin {
  /**
   * @param {!SourceFrame.SourcesTextEditor} textEditor
   * @param {!Workspace.UISourceCode} uiSourceCode
   */
  constructor(textEditor, uiSourceCode) {
    super();
    this._textEditor = textEditor;
    this._uiSourceCode = uiSourceCode;
  }

  /**
   * @override
   * @param {!Workspace.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  static accepts(uiSourceCode) {
    return uiSourceCode.contentType().hasScripts() || !!Sources.ScriptOriginPlugin._script(uiSourceCode);
  }

  /**
   * @override
   * @return {!Array<!UI.ToolbarItem>}
   */
  rightToolbarItems() {
    const originURL = Bindings.CompilerScriptMapping.uiSourceCodeOrigin(this._uiSourceCode);
    if (originURL) {
      const item = UI.formatLocalized('(source mapped from %s)', [Components.Linkifier.linkifyURL(originURL)]);
      return [new UI.ToolbarItem(item)];
    }

    // Handle anonymous scripts with an originStackTrace.
    const script = Sources.ScriptOriginPlugin._script(this._uiSourceCode);
    if (!script || !script.originStackTrace) {
      return [];
    }
    const link = Sources.ScriptOriginPlugin._linkifier.linkifyStackTraceTopFrame(
        script.debuggerModel.target(), script.originStackTrace);
    return [new UI.ToolbarItem(link)];
  }

  /**
   * @param {!Workspace.UISourceCode} uiSourceCode
   * @return {?SDK.Script}
   */
  static _script(uiSourceCode) {
    const locations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode, 0, 0);
    for (const location of locations) {
      const script = location.script();
      if (script.originStackTrace) {
        return script;
      }
    }
    return null;
  }
};

Sources.ScriptOriginPlugin._linkifier = new Components.Linkifier();<commit_msg>Fix access on undefined script object<commit_after>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Sources.ScriptOriginPlugin = class extends Sources.UISourceCodeFrame.Plugin {
  /**
   * @param {!SourceFrame.SourcesTextEditor} textEditor
   * @param {!Workspace.UISourceCode} uiSourceCode
   */
  constructor(textEditor, uiSourceCode) {
    super();
    this._textEditor = textEditor;
    this._uiSourceCode = uiSourceCode;
  }

  /**
   * @override
   * @param {!Workspace.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  static accepts(uiSourceCode) {
    return uiSourceCode.contentType().hasScripts() || !!Sources.ScriptOriginPlugin._script(uiSourceCode);
  }

  /**
   * @override
   * @return {!Array<!UI.ToolbarItem>}
   */
  rightToolbarItems() {
    const originURL = Bindings.CompilerScriptMapping.uiSourceCodeOrigin(this._uiSourceCode);
    if (originURL) {
      const item = UI.formatLocalized('(source mapped from %s)', [Components.Linkifier.linkifyURL(originURL)]);
      return [new UI.ToolbarItem(item)];
    }

    // Handle anonymous scripts with an originStackTrace.
    const script = Sources.ScriptOriginPlugin._script(this._uiSourceCode);
    if (!script || !script.originStackTrace) {
      return [];
    }
    const link = Sources.ScriptOriginPlugin._linkifier.linkifyStackTraceTopFrame(
        script.debuggerModel.target(), script.originStackTrace);
    return [new UI.ToolbarItem(link)];
  }

  /**
   * @param {!Workspace.UISourceCode} uiSourceCode
   * @return {?SDK.Script}
   */
  static _script(uiSourceCode) {
    const locations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode, 0, 0);
    for (const location of locations) {
      const script = location.script();
      if (script && script.originStackTrace) {
        return script;
      }
    }
    return null;
  }
};

Sources.ScriptOriginPlugin._linkifier = new Components.Linkifier();<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var restify = require('restify');
var crypto = require('crypto');
var dbox = require("dbox");
var anyfetchProvider = require('anyfetch-provider');

var config = require('../../config/configuration.js');

module.exports.get = function(req, res, next) {

  async.waterfall([
    function noMissingParameters(cb) {
      // All params must be here
      if(!req.params.oauth_token) {
        return cb(new restify.MissingParameterError("specify oauth_token"));
      }
      if(!req.params.path) {
        return cb(new restify.MissingParameterError("specify path"));
      }
      if(!req.params.hash) {
        return cb(new restify.MissingParameterError("specify hash"));
      }
      req.params.format = encodeURIComponent(req.params.format || 'jpeg');
      req.params.size = encodeURIComponent(req.params.size || 'm');

      cb();
    },
    function checkValidHash(cb) {
      // Hash params must be valid
      var shasum = crypto.createHash('sha1');
      shasum.update(req.params.oauth_token);
      shasum.update(req.params.path);
      shasum.update(config.appSecret);

      var validHash = shasum.digest('hex').toString();

      if(validHash !== req.params.hash) {
        return cb(new restify.InvalidArgumentError("invalid hash"));
      }

      cb();
    },
    function retrieveToken(cb) {
      anyfetchProvider.retrieveData({'data.oauth_token': req.params.oauth_token}, cb);
    },
    function retrieveThumbnail(oauthToken, cb) {
      var app = dbox.app({
        "app_key": config.dropboxId,
        "app_secret": config.dropboxSecret
      });

      var client = app.client(oauthToken);
      var options = {
        root: "dropbox",
        size: req.params.size,
        format: req.params.format
      };

      client.thumbnails(req.params.path, options, function(status, reply, metadata) {
        var err;
        if(status !== 200) {
          err = new Error("Invalid Dropbox status code:" + status);
          console.log("Failed to retrieve image", reply.toString());
        }

        cb(err, reply, metadata);
      });
    },
    function sendThumbnail(reply, metadata, cb) {
      res.writeHead(200, {
        'Content-Type': 'image/' + req.params.format
      });
      res.write(reply);
      res.end();

      cb();
    }
  ], next);

};
<commit_msg>Fix a bug with toString() of null<commit_after>'use strict';

var async = require('async');
var restify = require('restify');
var crypto = require('crypto');
var dbox = require("dbox");
var anyfetchProvider = require('anyfetch-provider');

var config = require('../../config/configuration.js');

module.exports.get = function(req, res, next) {

  async.waterfall([
    function noMissingParameters(cb) {
      // All params must be here
      if(!req.params.oauth_token) {
        return cb(new restify.MissingParameterError("specify oauth_token"));
      }
      if(!req.params.path) {
        return cb(new restify.MissingParameterError("specify path"));
      }
      if(!req.params.hash) {
        return cb(new restify.MissingParameterError("specify hash"));
      }
      req.params.format = encodeURIComponent(req.params.format || 'jpeg');
      req.params.size = encodeURIComponent(req.params.size || 'm');

      cb();
    },
    function checkValidHash(cb) {
      // Hash params must be valid
      var shasum = crypto.createHash('sha1');
      shasum.update(req.params.oauth_token);
      shasum.update(req.params.path);
      shasum.update(config.appSecret);

      var validHash = shasum.digest('hex').toString();

      if(validHash !== req.params.hash) {
        return cb(new restify.InvalidArgumentError("invalid hash"));
      }

      cb();
    },
    function retrieveToken(cb) {
      anyfetchProvider.retrieveData({'data.oauth_token': req.params.oauth_token}, cb);
    },
    function retrieveThumbnail(oauthToken, cb) {
      var app = dbox.app({
        "app_key": config.dropboxId,
        "app_secret": config.dropboxSecret
      });

      var client = app.client(oauthToken);
      var options = {
        root: "dropbox",
        size: req.params.size,
        format: req.params.format
      };

      client.thumbnails(req.params.path, options, function(status, reply, metadata) {
        var err;
        if(status !== 200) {
          err = new Error("Invalid Dropbox status code:" + status);
          console.log("Failed to retrieve image", (reply) ? reply.toString() : '');
        }

        cb(err, reply, metadata);
      });
    },
    function sendThumbnail(reply, metadata, cb) {
      res.writeHead(200, {
        'Content-Type': 'image/' + req.params.format
      });
      res.write(reply);
      res.end();

      cb();
    }
  ], next);

};
<|endoftext|>


<commit_before>import Ember from 'ember';
import Session from 'simple-auth/session';
/* Abbreviations:
GID: Genre_id
CID: category_id
TID: topic_id
FTID: fact_type_id
------------------
GN: GenreName
CN: CategoryName
TN: Topicname
FTN: FactTypeName
PDN: PostingDateNaming
------------------
GP: GenrePartial
CP: CategoryPartial
FTP: FactTypePartial
PDP: PostingDatePartial
------------------
GPV: Genres Partial Visibility
CPV: Category Partial Visibility
FTPV: FactType Partial Visibility
PDPV: PostingDate Partial Visibility
*/
export default Ember.Controller.extend
({
	// Variables Section
	selectedGID: 0,
	selectedCID: 0,
	selectedTID: 0,
	selectedFTID: 0,
	selectedPDID: 0,
	selectedGN: 'None',
	selectedCN: 'None',
	selectedTN: 'None',
	selectedFTN: 'None',
	selectedPDN: 'None',
	topicInputText: '',
	showGP: true,
	showCP: true,
	showFTP: true,
	showPDP: true,
	// Paths to show central Panel and Sidebars Panels:
	centralPanelPaths: ['index',
	'posts.index', 'posts.create', 'posts.post.edit',
	'genres.index', 'genres.create', 'genres.genre.index', 'genres.genre.edit',
	'topics.index', 'topics.create', 'topics.topic.index', 'topics.topic.edit',
	'factTypes.index', 'factTypes.create', 'factTypes.factType.index', 'factTypes.factType.edit'],
	sidebarsPanelPaths: ['index',
	'posts.index', 'posts.create', 'posts.post.edit',
	'genres.index', 'genres.create', 'genres.genre.index', 'genres.genre.edit',
	'topics.index', 'topics.create', 'topics.topic.index', 'topics.topic.edit',
	'factTypes.index', 'factTypes.create', 'factTypes.factType.index', 'factTypes.factType.edit'],
	// Central Panel and Sidebars Visibility Boolean Check
	displayCentralPanel: Ember.computed('currentPath', function()
	{
		//console.log(this.get('currentPath'));
		if(this.get('centralPanelPaths').indexOf(this.get('currentPath')) !== -1)
		{return true;}
		else
		{return false;}
	}),
	displaySidebars: Ember.computed('currentPath', function()
	{
		if(this.get('sidebarsPanelPaths').indexOf(this.get('currentPath')) !== -1)
		{return true;}
		else
		{return false;}
	}),
	// Tags Selected Boolean check.
	isGenreSelected: Ember.computed('selectedGID', function()
	{
		if(this.get('selectedGID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isFactTypeSelected: Ember.computed('selectedFTID', function()
	{
		if(this.get('selectedFTID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isCategorySelected: Ember.computed('selectedCID', function()
	{
		if(this.get('selectedCID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isTopicSelected: Ember.computed('selectedTID', function()
	{
		if(this.get('selectedTID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isPostDateSelected: Ember.computed('selectedPDID', function()
	{
		if(this.get('selectedPDID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	topicStatus: Ember.computed('selectedTN', function()
	{
		if(this.get('selectedTN') === 'None')
		{
			return 'Search or manage topics';
		}
		if(this.get('selectedTN') === 'Invalid')
		{
			return 'Topic does not exist. Please create one >';
		}
		if(this.get('selectedTN') === '')
		{
			return 'Search or manage topics!';
		}
		else
		{
			return 'Topic is selected!';
		}
	}),
	// Partials Visibility Boolean Check
	displayGP: Ember.computed('showGP', function()
	{
		if(this.get('showGP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayCP: Ember.computed('showCP', function()
	{
		if(this.get('showCP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayFTP: Ember.computed('showFTP', function()
	{
		if(this.get('showFTP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayPDP: Ember.computed('showPDP', function()
	{
		if(this.get('showPDP') === true)
		{return true;}
		else
		{return false;}
	}),
	actions:
	{
		//Set ID Tag Methods
		setGID: function(genre)
		{
			this.set('selectedGID', genre.id);
			this.set('selectedGN', genre.get('name'));
		},
		setCID: function(category)
		{
			this.set('selectedCID', category.id);
			this.set('selectedCN', category.get('name'));
		},
		setFTID: function(factType)
		{
			this.set('selectedFTID', factType.id);
			this.set('selectedFTN', factType.get('name'));
		},
		setTID: function()
		{
			if(this.get('topicInputText') !== '')
			{
				var possibleTopic = this.model.get('topics').findBy('name', this.get('topicInputText').toLowerCase());
				if(possibleTopic === undefined)
				{
					this.set('selectedTN', 'Invalid');
					this.set('selectedTID', 0);
				}
				else
				{
					this.set('selectedTID', possibleTopic.id);
					this.set('selectedTN', possibleTopic.get('name'));
				}
			}
			else
			{
				this.set('selectedTN', '');
				this.set('selectedTID', 0);
			}
		},
		setPDID: function(varDayType)
		{
			this.set('selectedPDID', varDayType);
			if(varDayType === 1)
			{this.set('selectedPDN','Today');}
			else if(varDayType === 2)
			{this.set('selectedPDN','Yesterday');}
			else if(varDayType === 3)
			{this.set('selectedPDN','Past Week');}
			else if(varDayType === 4)
			{this.set('selectedPDN','Past Month');}
			else if(varDayType === 5)
			{this.set('selectedPDN','Past 6 Months');}
			else if(varDayType=== 6)
			{this.set('selectedPDN','Past Year');}
			else
			{this.set('selectedPDN','None');}
		},
		//Set Partial Visibility Methods
		setGPV: function(varBoolean)
		{
			this.set('showGP', varBoolean);
		},
		setCPV: function(varBoolean)
		{
			this.set('showCP', varBoolean);
		},
		setFTPV: function(varBoolean)
		{
			this.set('showFTP', varBoolean);
		},
		setPDPV: function(varBoolean)
		{
			this.set('showPDP', varBoolean);
		},
		//Clear Tag Methods
		clearGenre: function()
		{
			this.set('selectedGID', 0);
			this.set('selectedGN', 'None');
		},
		clearFactType: function()
		{
			this.set('selectedFTID', 0);
			this.set('selectedFTN', 'None');
		},
		clearCategory: function()
		{
			this.set('selectedCID', 0);
			this.set('selectedCN', 'None');
		},
		clearTopic: function()
		{
			this.set('selectedTID', 0);
			this.set('selectedTN', 'None');
		},
		clearPostDate: function()
		{
			this.set('selectedPDID', 0);
			this.set('selectedPDN', 'None');
		},
		//Logout method
		invalidateSession: function()
		{
			var shouldInvalidate = window.confirm('Really want to Logout? You will be returned to the homepage if you do.');
			if(shouldInvalidate)
			{
				this.get('session').invalidate();
				this.transitionToRoute('index');
			}
		}
	}
});
<commit_msg>TravisCI build fix<commit_after>import Ember from 'ember';
/* Abbreviations:
GID: Genre_id
CID: category_id
TID: topic_id
FTID: fact_type_id
------------------
GN: GenreName
CN: CategoryName
TN: Topicname
FTN: FactTypeName
PDN: PostingDateNaming
------------------
GP: GenrePartial
CP: CategoryPartial
FTP: FactTypePartial
PDP: PostingDatePartial
------------------
GPV: Genres Partial Visibility
CPV: Category Partial Visibility
FTPV: FactType Partial Visibility
PDPV: PostingDate Partial Visibility
*/
export default Ember.Controller.extend
({
	// Variables Section
	selectedGID: 0,
	selectedCID: 0,
	selectedTID: 0,
	selectedFTID: 0,
	selectedPDID: 0,
	selectedGN: 'None',
	selectedCN: 'None',
	selectedTN: 'None',
	selectedFTN: 'None',
	selectedPDN: 'None',
	topicInputText: '',
	showGP: true,
	showCP: true,
	showFTP: true,
	showPDP: true,
	// Paths to show central Panel and Sidebars Panels:
	centralPanelPaths: ['index',
	'posts.index', 'posts.create', 'posts.post.edit',
	'genres.index', 'genres.create', 'genres.genre.index', 'genres.genre.edit',
	'topics.index', 'topics.create', 'topics.topic.index', 'topics.topic.edit',
	'factTypes.index', 'factTypes.create', 'factTypes.factType.index', 'factTypes.factType.edit'],
	sidebarsPanelPaths: ['index',
	'posts.index', 'posts.create', 'posts.post.edit',
	'genres.index', 'genres.create', 'genres.genre.index', 'genres.genre.edit',
	'topics.index', 'topics.create', 'topics.topic.index', 'topics.topic.edit',
	'factTypes.index', 'factTypes.create', 'factTypes.factType.index', 'factTypes.factType.edit'],
	// Central Panel and Sidebars Visibility Boolean Check
	displayCentralPanel: Ember.computed('currentPath', function()
	{
		//console.log(this.get('currentPath'));
		if(this.get('centralPanelPaths').indexOf(this.get('currentPath')) !== -1)
		{return true;}
		else
		{return false;}
	}),
	displaySidebars: Ember.computed('currentPath', function()
	{
		if(this.get('sidebarsPanelPaths').indexOf(this.get('currentPath')) !== -1)
		{return true;}
		else
		{return false;}
	}),
	// Tags Selected Boolean check.
	isGenreSelected: Ember.computed('selectedGID', function()
	{
		if(this.get('selectedGID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isFactTypeSelected: Ember.computed('selectedFTID', function()
	{
		if(this.get('selectedFTID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isCategorySelected: Ember.computed('selectedCID', function()
	{
		if(this.get('selectedCID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isTopicSelected: Ember.computed('selectedTID', function()
	{
		if(this.get('selectedTID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	isPostDateSelected: Ember.computed('selectedPDID', function()
	{
		if(this.get('selectedPDID') !== 0)
		{return true;}
		else
		{return false;}
	}),
	topicStatus: Ember.computed('selectedTN', function()
	{
		if(this.get('selectedTN') === 'None')
		{
			return 'Search or manage topics';
		}
		if(this.get('selectedTN') === 'Invalid')
		{
			return 'Topic does not exist. Please create one >';
		}
		if(this.get('selectedTN') === '')
		{
			return 'Search or manage topics!';
		}
		else
		{
			return 'Topic is selected!';
		}
	}),
	// Partials Visibility Boolean Check
	displayGP: Ember.computed('showGP', function()
	{
		if(this.get('showGP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayCP: Ember.computed('showCP', function()
	{
		if(this.get('showCP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayFTP: Ember.computed('showFTP', function()
	{
		if(this.get('showFTP') === true)
		{return true;}
		else
		{return false;}
	}),
	displayPDP: Ember.computed('showPDP', function()
	{
		if(this.get('showPDP') === true)
		{return true;}
		else
		{return false;}
	}),
	actions:
	{
		//Set ID Tag Methods
		setGID: function(genre)
		{
			this.set('selectedGID', genre.id);
			this.set('selectedGN', genre.get('name'));
		},
		setCID: function(category)
		{
			this.set('selectedCID', category.id);
			this.set('selectedCN', category.get('name'));
		},
		setFTID: function(factType)
		{
			this.set('selectedFTID', factType.id);
			this.set('selectedFTN', factType.get('name'));
		},
		setTID: function()
		{
			if(this.get('topicInputText') !== '')
			{
				var possibleTopic = this.model.get('topics').findBy('name', this.get('topicInputText').toLowerCase());
				if(possibleTopic === undefined)
				{
					this.set('selectedTN', 'Invalid');
					this.set('selectedTID', 0);
				}
				else
				{
					this.set('selectedTID', possibleTopic.id);
					this.set('selectedTN', possibleTopic.get('name'));
				}
			}
			else
			{
				this.set('selectedTN', '');
				this.set('selectedTID', 0);
			}
		},
		setPDID: function(varDayType)
		{
			this.set('selectedPDID', varDayType);
			if(varDayType === 1)
			{this.set('selectedPDN','Today');}
			else if(varDayType === 2)
			{this.set('selectedPDN','Yesterday');}
			else if(varDayType === 3)
			{this.set('selectedPDN','Past Week');}
			else if(varDayType === 4)
			{this.set('selectedPDN','Past Month');}
			else if(varDayType === 5)
			{this.set('selectedPDN','Past 6 Months');}
			else if(varDayType=== 6)
			{this.set('selectedPDN','Past Year');}
			else
			{this.set('selectedPDN','None');}
		},
		//Set Partial Visibility Methods
		setGPV: function(varBoolean)
		{
			this.set('showGP', varBoolean);
		},
		setCPV: function(varBoolean)
		{
			this.set('showCP', varBoolean);
		},
		setFTPV: function(varBoolean)
		{
			this.set('showFTP', varBoolean);
		},
		setPDPV: function(varBoolean)
		{
			this.set('showPDP', varBoolean);
		},
		//Clear Tag Methods
		clearGenre: function()
		{
			this.set('selectedGID', 0);
			this.set('selectedGN', 'None');
		},
		clearFactType: function()
		{
			this.set('selectedFTID', 0);
			this.set('selectedFTN', 'None');
		},
		clearCategory: function()
		{
			this.set('selectedCID', 0);
			this.set('selectedCN', 'None');
		},
		clearTopic: function()
		{
			this.set('selectedTID', 0);
			this.set('selectedTN', 'None');
		},
		clearPostDate: function()
		{
			this.set('selectedPDID', 0);
			this.set('selectedPDN', 'None');
		},
		//Logout method
		invalidateSession: function()
		{
			var shouldInvalidate = window.confirm('Really want to Logout? You will be returned to the homepage if you do.');
			if(shouldInvalidate)
			{
				this.get('session').invalidate();
				this.transitionToRoute('index');
			}
		}
	}
});
<|endoftext|>


<commit_before>'use strict';

var all = require('../all');

exports.root = require('./root');
exports.text = require('./text');
exports.comment = require('./comment');

exports.caption =
exports.colgroup =
exports.head =
exports.math =
exports.script =
exports.style =
exports.svg =
exports.template =
exports.title = ignore;

exports.thead =
exports.tbody =
exports.tfoot = children;

exports.ol = exports.ul = require('./list');
exports.table = require('./table');
exports.tr = require('./table-row');
exports.th = exports.td = require('./table-cell');
exports.li = require('./list-item');
exports.strong = exports.b = require('./strong');
exports.em = exports.i = require('./emphasis');
exports.del = exports.s = exports.strike = require('./delete');
exports.code = exports.kbd = exports.samp = exports.var = require('./inline-code');
exports.img = require('./image');
exports.br = require('./break');

exports.p = require('./paragraph');
exports.hr = require('./thematic-break');
exports.pre = require('./code');
exports.blockquote = require('./blockquote');

exports.h1 = exports.h2 = exports.h3 =
  exports.h4 = exports.h5 = exports.h6 = require('./heading');

exports.a = require('./link');

function ignore() {}

function children(h, node) {
  return all(h, node);
}
<commit_msg>Refactor code-style<commit_after>'use strict';

var all = require('../all');

exports.root = require('./root');
exports.text = require('./text');
exports.comment = require('./comment');

exports.caption =
exports.colgroup =
exports.head =
exports.math =
exports.script =
exports.style =
exports.svg =
exports.template =
exports.title = ignore;

exports.thead =
exports.tbody =
exports.tfoot = children;

exports.ol = exports.ul = require('./list');
exports.table = require('./table');
exports.tr = require('./table-row');
exports.th = exports.td = require('./table-cell');
exports.li = require('./list-item');
exports.strong = exports.b = require('./strong');
exports.em = exports.i = require('./emphasis');
exports.del = exports.s = exports.strike = require('./delete');
exports.code = exports.kbd = exports.samp = exports.var = require('./inline-code');
exports.img = require('./image');
exports.br = require('./break');

exports.p = require('./paragraph');
exports.hr = require('./thematic-break');
exports.pre = require('./code');
exports.blockquote = require('./blockquote');

exports.h1 =
exports.h2 =
exports.h3 =
exports.h4 =
exports.h5 =
exports.h6 = require('./heading');

exports.a = require('./link');

function ignore() {}

function children(h, node) {
  return all(h, node);
}
<|endoftext|>


<commit_before>var debug = require('debug')('smp');

var events = require('events');
var util = require('util');

var crypto = require('./crypto');

var SMP_CID = 0x0006;

var SMP_PAIRING_REQUEST = 0x01;
var SMP_PAIRING_RESPONSE = 0x02;
var SMP_PAIRING_CONFIRM = 0x03;
var SMP_PAIRING_RANDOM = 0x04;
var SMP_PAIRING_FAILED = 0x05;
var SMP_ENCRYPT_INFO = 0x06;
var SMP_MASTER_IDENT = 0x07;

var LTK_INFO_SIZE = 36;

var MGMT_OP_LOAD_LONG_TERM_KEYS = 0x0013;

var Smp = function(aclStream, localAddressType, localAddress, remoteAddressType, remoteAddress) {
  this._aclStream = aclStream;
    this._ltkInfos = [];

//Bleno
  this._iat = new Buffer([(remoteAddressType === 'random') ? 0x01 : 0x00]);
  this._ia = new Buffer(remoteAddress.split(':').reverse().join(''), 'hex');
  this._rat = new Buffer([(localAddressType === 'random') ? 0x01 : 0x00]);
  this._ra = new Buffer(localAddress.split(':').reverse().join(''), 'hex');

/*
  this._iat = new Buffer([(localAddressType === 'random') ? 0x01 : 0x00]);
  this._ia = new Buffer(localAddress.split(':').reverse().join(''), 'hex');
  this._rat = new Buffer([(remoteAddressType === 'random') ? 0x01 : 0x00]);
  this._ra = new Buffer(remoteAddress.split(':').reverse().join(''), 'hex');
  */

  this.onAclStreamDataBinded = this.onAclStreamData.bind(this);
  this.onAclStreamEncryptChangeBinded = this.onAclStreamEncryptChange.bind(this);
  this.onAclStreamLtkNegReplyBinded = this.onAclStreamLtkNegReply.bind(this);
  this.onAclStreamEndBinded = this.onAclStreamEnd.bind(this);

  this._aclStream.on('data', this.onAclStreamDataBinded);
  this._aclStream.on('encryptChange', this.onAclStreamEncryptChangeBinded);
  this._aclStream.on('ltkNegReply', this.onAclStreamLtkNegReplyBinded);
  this._aclStream.on('end', this.onAclStreamEndBinded);
};

util.inherits(Smp, events.EventEmitter);

Smp.prototype.sendPairingRequest = function() {
  console.log("Sending pairing request");
  this._preq = new Buffer([
    SMP_PAIRING_REQUEST,
    0x03, //0x04, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x01, //0x05, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x00, //0x03, // Initiator key distribution: <none>
    0x01  //0x03  // Responder key distribution: EncKey
  ]);

  this.write(this._preq);
};

Smp.prototype.handlePairingRequest = function(data) {
  this._preq = data;
  console.log("Recieved a Pairing Request");
  this._pres = new Buffer([
    SMP_PAIRING_RESPONSE,
    0x03, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x05, //0x01, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x03, //0x00, // Initiator key distribution: <none>
    0x01  //0x01  // Responder key distribution: EncKey
  ]);
  debug('\tSending: ' + this._pres.toString('hex'));
  this.write(this._pres);
};

/*
Smp.prototype.handlePairingRequest = function(data) {
  this._preq = data;
  console.log("Recieved a Pairing Request");
  this._pres = new Buffer([
    SMP_PAIRING_RESPONSE,
    0x03, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x01, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x00, // Initiator key distribution: <none>
    0x01  // Responder key distribution: EncKey
  ]);

  this.write(this._pres);
};
*/

Smp.prototype.onAclStreamLtkNegReply = function() {
    debug("SMP recieved LtkNegReply");
    this.write(new Buffer([
      SMP_PAIRING_FAILED,
      SMP_UNSPECIFIED
    ]));

    this.emit('fail');
};

Smp.prototype.onAclStreamData = function(cid, data) {
  if (cid !== SMP_CID) {
    return;
  }

  var code = data.readUInt8(0);
  debug("SMP Data - code: 0x" + code.toString(16));
  if (SMP_PAIRING_REQUEST === code) {
    this.handlePairingRequest(data);
  } else if (SMP_PAIRING_RESPONSE === code) {
    this.handlePairingResponse(data);
  } else if (SMP_PAIRING_CONFIRM === code) {
    this.handlePairingConfirm(data);
  } else if (SMP_PAIRING_RANDOM === code) {
    this.handlePairingRandom(data);
  } else if (SMP_PAIRING_FAILED === code) {
    this.handlePairingFailed(data);
  } else if (SMP_ENCRYPT_INFO === code) {
    this.handleEncryptInfo(data);
  } else if (SMP_MASTER_IDENT === code) {
    this.handleMasterIdent(data);
  }
};

Smp.prototype.onAclStreamEnd = function() {
  this._aclStream.removeListener('data', this.onAclStreamDataBinded);
  this._aclStream.removeListener('end', this.onAclStreamEndBinded);
  this._aclStream.removeListener('encryptChange', this.onAclStreamEncryptChangeBinded);
  this._aclStream.removeListener('ltkNegReply', this.onAclStreamLtkNegReplyBinded);

  this.emit('end');
};

Smp.prototype.onAclStreamEncryptChange = function(encrypted) {
  if (encrypted) {
    if (this._stk && this._diversifier && this._random) {
      this.write(Buffer.concat([
        new Buffer([SMP_ENCRYPT_INFO]),
        this._stk
      ]));

      this.write(Buffer.concat([
        new Buffer([SMP_MASTER_IDENT]),
        this._diversifier,
        this._random
      ]));
    }
  }
};

Smp.prototype.handlePairingResponse = function(data) {
  this._pres = data;
  debug("Recieved a Pairing Response");
  debug('\t\tIO Capability: 0x' + data[1].toString(16));
  debug('\t\tOOB Data: 0x' + data[2].toString(16));
  debug('\t\tAuthentication Requirement: 0x' + data[3].toString(16));
  debug('\t\tMax Encryption Size: 0x' + data[4].toString(16));
  debug('\t\tInitiator Key: 0x' + data[5].toString(16));
  debug('\t\tResponder Key: 0x' + data[6].toString(16));

  this._tk = new Buffer('00000000000000000000000000000000', 'hex');
  this._r = crypto.r();
/*
  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));*/
  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));
};

//Bleno

Smp.prototype.handlePairingConfirm = function(data) {
  this._pcnf = data;

  this._tk = new Buffer('00000000000000000000000000000000', 'hex');
  this._r = crypto.r();
  debug("Recieved a Pairing Confirm");

  /*this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));*/
  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));
};
/*

//Noble
Smp.prototype.handlePairingConfirm = function(data) {
  this._pcnf = data;

  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_RANDOM]),
    this._r
  ]));
};*/

//Bleno

Smp.prototype.addLongTermKey = function(address, addressType, authenticated, master, ediv, rand, key) {
  var ltkInfo = new Buffer(LTK_INFO_SIZE);

  address.copy(ltkInfo, 0);
  ltkInfo.writeUInt8(addressType.readUInt8(0) + 1, 6); // BDADDR_LE_PUBLIC = 0x01, BDADDR_LE_RANDOM 0x02, so add one

  ltkInfo.writeUInt8(authenticated, 7);
  ltkInfo.writeUInt8(master, 8);
  ltkInfo.writeUInt8(key.length, 9);

  ediv.copy(ltkInfo, 10);
  rand.copy(ltkInfo, 12);
  key.copy(ltkInfo, 20);

  this._ltkInfos.push(ltkInfo);

  this.loadLongTermKeys();
};

Smp.prototype.clearLongTermKeys = function() {
  this._ltkInfos = [];

  this.loadLongTermKeys();
};

Smp.prototype.loadLongTermKeys = function() {
  var numLongTermKeys = this._ltkInfos.length;
  var op = new Buffer(2 + numLongTermKeys * LTK_INFO_SIZE);

  op.writeUInt16LE(numLongTermKeys, 0);

  debug("Adding Long Term Keys")
  for (var i = 0; i < numLongTermKeys; i++) {
    debug('\t\t'+this._ltkInfos[i]);
    this._ltkInfos[i].copy(op, 2 + i * LTK_INFO_SIZE);
  }

  //this.write(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op);
  this.mgmtWrite(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op);
};

Smp.prototype.mgmtWrite = function(opcode, index, data) {
  var length = 0;

  if (data) {
    length = data.length;
  }

  var pkt = new Buffer(6 + length);

  pkt.writeUInt16LE(opcode, 0);
  pkt.writeUInt16LE(index, 2);
  pkt.writeUInt16LE(length, 4);

  if (length) {
    data.copy(pkt, 6);
  }

  debug('Mgmt writing -> ' + pkt.toString('hex'));
  this.write(pkt);
};

Smp.prototype.handlePairingRandom = function(data) {
  var r = data.slice(1);

  debug("Handle Pairing Random: ");
  var pcnf = Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]);

  if (this._pcnf.toString('hex') === pcnf.toString('hex')) {
    debug('\t\tRandom Worked: ');
    this._diversifier = new Buffer('0000', 'hex');
    this._random = new Buffer('0000000000000000', 'hex');
    this._stk = crypto.s1(this._tk, this._r, r);

    this.addLongTermKey(this._ia, this._iat, 0, 0, this._diversifier, this._random, this._stk);

    this.write(Buffer.concat([
      new Buffer([SMP_PAIRING_RANDOM]),
      this._r
    ]));
  } else {
    debug('\t\tRandom failed: ');
    this.write(new Buffer([
      SMP_PAIRING_FAILED,
      SMP_PAIRING_CONFIRM
    ]));

    this.emit('fail');
  }

};

/*
//Noble
Smp.prototype.handlePairingRandom = function(data) {
  var r = data.slice(1);

  var pcnf = Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]);

  if (this._pcnf.toString('hex') === pcnf.toString('hex')) {
    var stk = crypto.s1(this._tk, r, this._r);

    this.emit('stk', stk);
  } else {
    this.write(new Buffer([
      SMP_PAIRING_RANDOM,
      SMP_PAIRING_CONFIRM
    ]));

    this.emit('fail');
  }
};

*/

Smp.prototype.handlePairingFailed = function(data) {
  debug('Pairing Failed!');
  debug('\t\tReason: ' + data[1].toString(16));
  this.emit('fail');
};

Smp.prototype.handleEncryptInfo = function(data) {
  var ltk = data.slice(1);
  debug("Encrypt Info")
  this.emit('ltk', ltk);
};

Smp.prototype.handleMasterIdent = function(data) {
  var ediv = data.slice(1, 3);
  var rand = data.slice(3);

  this.emit('masterIdent', ediv, rand);
};

Smp.prototype.write = function(data) {
  this._aclStream.write(SMP_CID, data);
};

module.exports = Smp;
<commit_msg>turned it off<commit_after>var debug = require('debug')('smp');

var events = require('events');
var util = require('util');

var crypto = require('./crypto');

var SMP_CID = 0x0006;

var SMP_PAIRING_REQUEST = 0x01;
var SMP_PAIRING_RESPONSE = 0x02;
var SMP_PAIRING_CONFIRM = 0x03;
var SMP_PAIRING_RANDOM = 0x04;
var SMP_PAIRING_FAILED = 0x05;
var SMP_ENCRYPT_INFO = 0x06;
var SMP_MASTER_IDENT = 0x07;

var LTK_INFO_SIZE = 36;

var MGMT_OP_LOAD_LONG_TERM_KEYS = 0x0013;

var Smp = function(aclStream, localAddressType, localAddress, remoteAddressType, remoteAddress) {
  this._aclStream = aclStream;
    this._ltkInfos = [];

//Bleno
  this._iat = new Buffer([(remoteAddressType === 'random') ? 0x01 : 0x00]);
  this._ia = new Buffer(remoteAddress.split(':').reverse().join(''), 'hex');
  this._rat = new Buffer([(localAddressType === 'random') ? 0x01 : 0x00]);
  this._ra = new Buffer(localAddress.split(':').reverse().join(''), 'hex');

/*
  this._iat = new Buffer([(localAddressType === 'random') ? 0x01 : 0x00]);
  this._ia = new Buffer(localAddress.split(':').reverse().join(''), 'hex');
  this._rat = new Buffer([(remoteAddressType === 'random') ? 0x01 : 0x00]);
  this._ra = new Buffer(remoteAddress.split(':').reverse().join(''), 'hex');
  */

  this.onAclStreamDataBinded = this.onAclStreamData.bind(this);
  this.onAclStreamEncryptChangeBinded = this.onAclStreamEncryptChange.bind(this);
  this.onAclStreamLtkNegReplyBinded = this.onAclStreamLtkNegReply.bind(this);
  this.onAclStreamEndBinded = this.onAclStreamEnd.bind(this);

  this._aclStream.on('data', this.onAclStreamDataBinded);
  this._aclStream.on('encryptChange', this.onAclStreamEncryptChangeBinded);
  this._aclStream.on('ltkNegReply', this.onAclStreamLtkNegReplyBinded);
  this._aclStream.on('end', this.onAclStreamEndBinded);
};

util.inherits(Smp, events.EventEmitter);

Smp.prototype.sendPairingRequest = function() {
  console.log("Sending pairing request");
  this._preq = new Buffer([
    SMP_PAIRING_REQUEST,
    0x03, //0x04, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x01, //0x05, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x00, //0x03, // Initiator key distribution: <none>
    0x01  //0x03  // Responder key distribution: EncKey
  ]);

  this.write(this._preq);
};

Smp.prototype.handlePairingRequest = function(data) {
  this._preq = data;
  console.log("Recieved a Pairing Request");
  this._pres = new Buffer([
    SMP_PAIRING_RESPONSE,
    0x03, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x05, //0x01, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x03, //0x00, // Initiator key distribution: <none>
    0x01  //0x01  // Responder key distribution: EncKey
  ]);
  debug('\tShould be Sending: ' + this._pres.toString('hex'));
  //this.write(this._pres);
};

/*
Smp.prototype.handlePairingRequest = function(data) {
  this._preq = data;
  console.log("Recieved a Pairing Request");
  this._pres = new Buffer([
    SMP_PAIRING_RESPONSE,
    0x03, // IO capability: NoInputNoOutput
    0x00, // OOB data: Authentication data not present
    0x01, // Authentication requirement: Bonding - No MITM
    0x10, // Max encryption key size
    0x00, // Initiator key distribution: <none>
    0x01  // Responder key distribution: EncKey
  ]);

  this.write(this._pres);
};
*/

Smp.prototype.onAclStreamLtkNegReply = function() {
    debug("SMP recieved LtkNegReply");
    this.write(new Buffer([
      SMP_PAIRING_FAILED,
      SMP_UNSPECIFIED
    ]));

    this.emit('fail');
};

Smp.prototype.onAclStreamData = function(cid, data) {
  if (cid !== SMP_CID) {
    return;
  }

  var code = data.readUInt8(0);
  debug("SMP Data - code: 0x" + code.toString(16));
  if (SMP_PAIRING_REQUEST === code) {
    this.handlePairingRequest(data);
  } else if (SMP_PAIRING_RESPONSE === code) {
    this.handlePairingResponse(data);
  } else if (SMP_PAIRING_CONFIRM === code) {
    this.handlePairingConfirm(data);
  } else if (SMP_PAIRING_RANDOM === code) {
    this.handlePairingRandom(data);
  } else if (SMP_PAIRING_FAILED === code) {
    this.handlePairingFailed(data);
  } else if (SMP_ENCRYPT_INFO === code) {
    this.handleEncryptInfo(data);
  } else if (SMP_MASTER_IDENT === code) {
    this.handleMasterIdent(data);
  }
};

Smp.prototype.onAclStreamEnd = function() {
  this._aclStream.removeListener('data', this.onAclStreamDataBinded);
  this._aclStream.removeListener('end', this.onAclStreamEndBinded);
  this._aclStream.removeListener('encryptChange', this.onAclStreamEncryptChangeBinded);
  this._aclStream.removeListener('ltkNegReply', this.onAclStreamLtkNegReplyBinded);

  this.emit('end');
};

Smp.prototype.onAclStreamEncryptChange = function(encrypted) {
  if (encrypted) {
    if (this._stk && this._diversifier && this._random) {
      this.write(Buffer.concat([
        new Buffer([SMP_ENCRYPT_INFO]),
        this._stk
      ]));

      this.write(Buffer.concat([
        new Buffer([SMP_MASTER_IDENT]),
        this._diversifier,
        this._random
      ]));
    }
  }
};

Smp.prototype.handlePairingResponse = function(data) {
  this._pres = data;
  debug("Recieved a Pairing Response");
  debug('\t\tIO Capability: 0x' + data[1].toString(16));
  debug('\t\tOOB Data: 0x' + data[2].toString(16));
  debug('\t\tAuthentication Requirement: 0x' + data[3].toString(16));
  debug('\t\tMax Encryption Size: 0x' + data[4].toString(16));
  debug('\t\tInitiator Key: 0x' + data[5].toString(16));
  debug('\t\tResponder Key: 0x' + data[6].toString(16));

  this._tk = new Buffer('00000000000000000000000000000000', 'hex');
  this._r = crypto.r();
/*
  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));*/
};

//Bleno

Smp.prototype.handlePairingConfirm = function(data) {
  this._pcnf = data;

  this._tk = new Buffer('00000000000000000000000000000000', 'hex');
  this._r = crypto.r();
  debug("Recieved a Pairing Confirm");

  /*this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, this._r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]));*/
};
/*

//Noble
Smp.prototype.handlePairingConfirm = function(data) {
  this._pcnf = data;

  this.write(Buffer.concat([
    new Buffer([SMP_PAIRING_RANDOM]),
    this._r
  ]));
};*/

//Bleno

Smp.prototype.addLongTermKey = function(address, addressType, authenticated, master, ediv, rand, key) {
  var ltkInfo = new Buffer(LTK_INFO_SIZE);

  address.copy(ltkInfo, 0);
  ltkInfo.writeUInt8(addressType.readUInt8(0) + 1, 6); // BDADDR_LE_PUBLIC = 0x01, BDADDR_LE_RANDOM 0x02, so add one

  ltkInfo.writeUInt8(authenticated, 7);
  ltkInfo.writeUInt8(master, 8);
  ltkInfo.writeUInt8(key.length, 9);

  ediv.copy(ltkInfo, 10);
  rand.copy(ltkInfo, 12);
  key.copy(ltkInfo, 20);

  this._ltkInfos.push(ltkInfo);

  this.loadLongTermKeys();
};

Smp.prototype.clearLongTermKeys = function() {
  this._ltkInfos = [];

  this.loadLongTermKeys();
};

Smp.prototype.loadLongTermKeys = function() {
  var numLongTermKeys = this._ltkInfos.length;
  var op = new Buffer(2 + numLongTermKeys * LTK_INFO_SIZE);

  op.writeUInt16LE(numLongTermKeys, 0);

  debug("Adding Long Term Keys")
  for (var i = 0; i < numLongTermKeys; i++) {
    debug('\t\t'+this._ltkInfos[i]);
    this._ltkInfos[i].copy(op, 2 + i * LTK_INFO_SIZE);
  }

  //this.write(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op);
  this.mgmtWrite(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op);
};

Smp.prototype.mgmtWrite = function(opcode, index, data) {
  var length = 0;

  if (data) {
    length = data.length;
  }

  var pkt = new Buffer(6 + length);

  pkt.writeUInt16LE(opcode, 0);
  pkt.writeUInt16LE(index, 2);
  pkt.writeUInt16LE(length, 4);

  if (length) {
    data.copy(pkt, 6);
  }

  debug('Mgmt writing -> ' + pkt.toString('hex'));
  this.write(pkt);
};

Smp.prototype.handlePairingRandom = function(data) {
  var r = data.slice(1);

  debug("Handle Pairing Random: ");
/*
  var pcnf = Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]);

  if (this._pcnf.toString('hex') === pcnf.toString('hex')) {
    debug('\t\tRandom Worked: ');
    this._diversifier = new Buffer('0000', 'hex');
    this._random = new Buffer('0000000000000000', 'hex');
    this._stk = crypto.s1(this._tk, this._r, r);

    this.addLongTermKey(this._ia, this._iat, 0, 0, this._diversifier, this._random, this._stk);

    this.write(Buffer.concat([
      new Buffer([SMP_PAIRING_RANDOM]),
      this._r
    ]));
  } else {
    debug('\t\tRandom failed: ');
    this.write(new Buffer([
      SMP_PAIRING_FAILED,
      SMP_PAIRING_CONFIRM
    ]));

    this.emit('fail');
  }
*/
};

/*
//Noble
Smp.prototype.handlePairingRandom = function(data) {
  var r = data.slice(1);

  var pcnf = Buffer.concat([
    new Buffer([SMP_PAIRING_CONFIRM]),
    crypto.c1(this._tk, r, this._pres, this._preq, this._iat, this._ia, this._rat, this._ra)
  ]);

  if (this._pcnf.toString('hex') === pcnf.toString('hex')) {
    var stk = crypto.s1(this._tk, r, this._r);

    this.emit('stk', stk);
  } else {
    this.write(new Buffer([
      SMP_PAIRING_RANDOM,
      SMP_PAIRING_CONFIRM
    ]));

    this.emit('fail');
  }
};

*/

Smp.prototype.handlePairingFailed = function(data) {
  debug('Pairing Failed!');
  debug('\t\tReason: ' + data[1].toString(16));
  this.emit('fail');
};

Smp.prototype.handleEncryptInfo = function(data) {
  var ltk = data.slice(1);
  debug("Encrypt Info")
  this.emit('ltk', ltk);
};

Smp.prototype.handleMasterIdent = function(data) {
  var ediv = data.slice(1, 3);
  var rand = data.slice(3);

  this.emit('masterIdent', ediv, rand);
};

Smp.prototype.write = function(data) {
  this._aclStream.write(SMP_CID, data);
};

module.exports = Smp;
<|endoftext|>


<commit_before>'use strict';

/**
 *  Logger helper, which allows keeping track of "tasks" and helps with nesting
 *  log statements
 */

const cursor = require('ansi')(process.stdout);
const newlines = require('./newlines.js');
const chalk = require('chalk');
const _ = require('lodash');
const tty = require('tty');
const Promise = require('bluebird');

// Helper for obtaining cursor position
function getPosition() {
    const ttyRaw = function(mode) {
        if (process.stdin.setRawMode) {
            process.stdin.setRawMode(mode);
        } else {
            tty.setRawMode(mode);
        }
    };

    return new Promise(function(resolve, reject) {
        // listen for the queryPosition report on stdin
        process.stdin.resume();
        ttyRaw(true);

        process.stdin.once('data', function (b) {
            // cleanup and close stdin
            ttyRaw(false);
            process.stdin.pause();

            const match = /\[(\d+)\;(\d+)R$/.exec(b.toString());
            if (match) {
                const xy = match.slice(1, 3).reverse().map(Number);
                resolve({ x: xy[0], y: xy[1] });
            } else {
                reject(new Error('Failed to obtain cursor position'));
            }
        });

        // Send the query position request code to stdout
        cursor.queryPosition();
    });
}

// Internal helper for logging stuff out
function log(fn, args, indent) {
    if (args.length === 0) {
        return;
    }

    // Assumes args are something you would pass into console.log
    // Applies appropriate nesting
    const indentation = _.repeat('\t', indent);

    // Prepend tabs to first arg (if string)
    if (_.isString(args[0])) {
        args[0] = indentation + args[0];
    } else {
        args.splice(0, 0, indentation);
    }

    fn.apply(this, args);
}

/**
 *  Creating a new logger
 */
const Logger = function() {
    // A stack, latest task is the last item in the array
    this.tasks = [];
    this.currentLine = 0;

    // Keeping track of current line in the log
    // Shadow stdout.write and stderr.write
    newlines(process.stdout);
    newlines(process.stderr);
    process.stderr.on('newline', function() {
        this.currentLine++;
    }.bind(this));
    process.stdout.on('newline', function() {
        this.currentLine++;
    }.bind(this));

    // Functions to expose
    this.log = function() {
        // Similar to console.log, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.log, args, this.tasks.length);
    };

    this.error = function() {
        // Similar to console.error, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.error, args, this.tasks.length);
    };

    /**
     *  Task tracking, acts almost like a wrapper around Promise(func(resolve, reject))
     *  If the passed in function takes no arguments, then it is assumed to be a sync
     *  call that may throw (reject) or return a value (resolve)
     *
     *  @returns Promise that resolves/rejects as if the contents, but adds some
     *  logging logic around it
     */
    this.task = function(taskName, taskFunction) {
        const indentation = this.tasks.length;
        const lines = indentation === 0 ? 1 : 0;

        // Push a simple task object to the queue
        const task = {
            name: taskName,
            line: this.currentLine + lines,
            indentation: indentation
        };

        const introLine = `${_.repeat('\t', indentation)}${taskName}`;

        const finish = function(t, succeed, err) {
            return new Promise(function(resolve, reject) {
                const idx = _.findIndex(this.tasks, t);
                if (idx === -1) {
                    return reject(new Error('Task is not part of the logger'));
                }

                // Calculate delta in number of rows we need to move up
                const delta = this.currentLine - t.line;
                let newIntroline;

                if (succeed) {
                    newIntroline = `${introLine} ${chalk.green('✔')}`;
                } else if (err) {
                    newIntroline = `${introLine} ${chalk.red('✖')} ${err.message}`;
                } else {
                    newIntroline = `${introLine} ${chalk.red('✖')}`;
                }

                return getPosition().then(function(pos) {
                    cursor.up(delta).eraseLine().write(newIntroline).down(delta).horizontalAbsolute(pos.x);

                    // Remove from tasks
                    this.tasks.splice(idx, 1);
                }.bind(this)).then(resolve);
            }.bind(this));
        }.bind(this);

        return new Promise(function(resolve, reject) {
            // If there are currently no tasks, add an empty line
            // (top-level or first tasks are separated by empty lines)
            if (this.tasks.length === 0) {
                cursor.write('\n');
            }

            // Print out the task name
            cursor.write(`${introLine}\n`);

            // Add to the tasks array
            this.tasks.push(task);

            if (taskFunction.length === 0) {
                // Sync task
                try {
                    const result = taskFunction();
                    finish(task, true, null).then(function() {
                        resolve(result);
                    });
                } catch (err) {
                    finish(task, false, err).then(function() {
                        reject(err);
                    });
                }
            } else {
                // Async task
                const res = function(value) {
                    finish(task, true, null).then(function() {
                        resolve(value);
                    });
                };

                const rej = function(err) {
                    finish(task, false, err).then(function() {
                        reject(err);
                    });
                };

                taskFunction(res, rej);
            }
        }.bind(this));
    };

    return this;
};

Logger.shared = new Logger();
module.exports = Logger;
<commit_msg>Drastically simplify logger<commit_after>'use strict';

/**
 *  Logger helper, which allows keeping track of "tasks" and helps with nesting
 *  log statements
 */

const cursor = require('ansi')(process.stdout);
const newlines = require('./newlines.js');
const chalk = require('chalk');
const _ = require('lodash');
const tty = require('tty');
const Promise = require('bluebird');

// Internal helper for logging stuff out
function log(fn, args, indent) {
    if (args.length === 0) {
        return;
    }

    // Assumes args are something you would pass into console.log
    // Applies appropriate nesting
    const indentation = _.repeat('\t', indent);

    // Prepend tabs to first arg (if string)
    if (_.isString(args[0])) {
        args[0] = indentation + args[0];
    } else {
        args.splice(0, 0, indentation);
    }

    fn.apply(this, args);
}

/**
 *  Creating a new logger
 */
const Logger = function() {
    // A stack, latest task is the last item in the array
    this.tasks = [];
    this.currentLine = 0;

    // Keeping track of current line in the log
    // Shadow stdout.write and stderr.write
    newlines(process.stdout);
    newlines(process.stderr);
    process.stderr.on('newline', function() {
        this.currentLine++;
    }.bind(this));
    process.stdout.on('newline', function() {
        this.currentLine++;
    }.bind(this));

    // Functions to expose
    this.log = function() {
        // Similar to console.log, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.log, args, this.tasks.length);
    };

    this.error = function() {
        // Similar to console.error, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.error, args, this.tasks.length);
    };

    /**
     *  Task tracking, acts almost like a wrapper around Promise(func(resolve, reject))
     *  If the passed in function takes no arguments, then it is assumed to be a sync
     *  call that may throw (reject) or return a value (resolve)
     *
     *  @returns Promise that resolves/rejects as if the contents, but adds some
     *  logging logic around it
     */
    this.task = function(taskName, taskFunction) {
        const indentation = this.tasks.length;
        const lines = indentation === 0 ? 1 : 0;

        // Push a simple task object to the queue
        const task = {
            name: taskName,
            line: this.currentLine + lines,
            indentation: indentation
        };

        const introLine = `${_.repeat('\t', indentation)}${taskName}`;

        const finish = function(t, succeed, err) {
            const idx = _.findIndex(this.tasks, t);
            if (idx === -1) {
                return reject(new Error('Task is not part of the logger'));
            }

            // Remove from tasks
            this.tasks.splice(idx, 1);

            // Create message to write, then decide where to write
            let message;
            if (succeed) {
                message = `${introLine} ${chalk.green('✔')}`;
            } else if (err) {
                message = `${introLine} ${chalk.red('✖')} ${err.message}`;
            } else {
                message = `${introLine} ${chalk.red('✖')}`;
            }

            // Simple check, if on next line of the task, append to previous line
            // otherwise add a new line
            if (this.currentLine === task.line + 1) {
                cursor.up(1).eraseLine().write(message).down(1).horizontalAbsolute(0);
            } else {
                cursor.write(message).write('\n\n');
            }
        }.bind(this);

        return new Promise(function(resolve, reject) {
            // If there are currently no tasks, add an empty line
            // (top-level or first tasks are separated by empty lines)
            if (this.tasks.length === 0) {
                cursor.write('\n');
            }

            // Print out the task name
            cursor.write(`${introLine}\n`);

            // Add to the tasks array
            this.tasks.push(task);

            if (taskFunction.length === 0) {
                // Sync task
                try {
                    const result = taskFunction();
                    finish(task, true, null);
                    resolve(result);
                } catch (err) {
                    finish(task, false, err);
                    reject(err);
                }
            } else {
                // Async task
                const res = function(value) {
                    finish(task, true, null);
                    resolve(value);
                };

                const rej = function(err) {
                    finish(task, false, err);
                    reject(err);
                };

                taskFunction(res, rej);
            }
        }.bind(this));
    };

    return this;
};

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


<commit_before>/*global Backbone, _, window, Promise, $ */
"use strict";
(function(NS) {
    //Filename: views/core-view.js
    NS = NS || {};
    var isInBrowser = typeof module === 'undefined' && typeof window !== 'undefined';
    var postRenderingBuilder = isInBrowser ? NS.Helpers.postRenderingBuilder : require('../helpers/post_rendering_builder');
    var ErrorHelper = isInBrowser ? NS.Helpers.errorHelper : require('../helpers/error_helper');
    var RefHelper = isInBrowser ? NS.Helpers.referenceHelper : require('../helpers/reference_helper');
    var ArgumentNullException = isInBrowser ? NS.Helpers.Exceptions.ArgumentNullException : require("../helpers/custom_exception").ArgumentNullException;
    var Model = isInBrowser ? NS.Models.Model : require("../models/model");
    var PaginatedCollection = isInBrowser ? NS.Models.PaginatedCollection : require("../models/paginatedCollection");
    var UtilHelper = isInBrowser ? NS.Helpers.utilHelper : require('../helpers/util_helper');
    var sessionHelper = isInBrowser ? NS.Helpers.sessionHelper : require('../helpers/session_helper');
    var templateSpinner = isInBrowser ? NS.templates.spinner : function() {
        return "Template spinner to define...";
    };
    //View which is the default view for each view.
    //This view is able to deal with errors and to render the default json moodel.
    var CoreView = Backbone.View.extend({
        toogleIsHidden: function(options) {
            this.isHidden = !this.isHidden;
            this.render(options);
        },
        //Reference lists names.
        //These _names_, must have been registered inside the the application to be used.
        referenceNames: undefined,

        //Options define by default for the view.
        defaultOptions: {
            isElementRedefinition: false, //This options is use in order to not have a tag container generated by Backbone arround the view.
            isReadyReferences: true
        },
        //Options overriden By the instanciate view.
        customOptions: {},

        //This property is use in order to create a new Model if no model are define in the view.
        modelName: undefined,

        //Initialization of the coreview.
        initialize: function initializeCoreView(options) {
            options = options || {};
            //Define default options foreach _core_ view, and override these options for each _project view_.
            //Then each view will have access to options in any methods.
            this.opts = _.extend({}, this.defaultOptions, this.customOptions, options);

            this.on('toogleIsHidden', this.toogleIsHidden);
            this.initializeModel();

            /*Register after renger.*/
            _.bindAll(this, 'render', 'afterRender');
            var _this = this;
            this.render = _.wrap(this.render, function(render, options) {
                //If the view is ready perform the standard render.
                if (_this.isReady()) {
                    render(options);
                    _this.afterRender();
                } else {
                    //Else render the spinner.
                    this.renderSpinner();
                }
                return _this;
            });

            //Listen to the reference list loading.
            this.listenTo(this.model, "references:loaded", this.render, this);

            //Load all the references lists which are defined in referenceNames.
            var currentView = this;
            if (_.isArray(this.referenceNames) && this.referenceNames.length > 0) {
                this.opts.isReadyReferences = false;
                Promise.all(RefHelper.loadMany(this.referenceNames)).then(function(results) {
                    currentView.opts.isReadyReferences = true;
                    //console.log('resultsreferenceNames', results);
                    var res = {}; //Container for all the results.
                    for (var i = 0, l = results.length; i < l; i++) {
                        res[currentView.referenceNames[i]] = results[i];
                        //The results are save into an object with a name for each reference list.
                    }
                    //Add the reference lists as model properties.
                    _.extend(currentView.model, res);
                    currentView.model.trigger('references:loaded');
                    //Inform the view that we are ready to render well.
                }).then(null, function(error) {
                    currentView.opts.isReadyReferences = true;
                    currentView.render();
                    ErrorHelper.manageResponseErrors(error, {
                        isDisplay: true
                    });
                });
            }

        },

        //Initialize the model of the view.
        //In order to be able to be initialize, a view must have a _model_ or a _modelName_.
        initializeModel: function initializeModelCoreView() {
            if (this.model) {
                return;
            } else if (this.opts.modelName) {
                //Création d'une collection et d'un model
                var ModelCreated = Model.extend({
                    modelName: this.opts.modelName
                });
                //Case of a collection.
                if (this.opts.modelType !== undefined && this.opts.modelType === "collection") {
                    var CollectionCreated = PaginatedCollection.extend({
                        modelName: this.opts.modelName,
                        model: ModelCreated
                    });
                    this.model = new CollectionCreated();
                } else {
                    //Case of a model.
                    this.model = new ModelCreated();

                }
            } else {
                throw new ArgumentNullException("The view must have a model or a model name.", this);
            }
        },
        //The handlebars template has to be defined here.
        template: function emptyTemplate(json) {
            console.log("templateData", json);
            return "
Your template has to be implemented.
";
        }, // Example: require('./templates/coreView'),
        templateSpinner: templateSpinner,
        //Defaults events.
        events: {
            "focus input": "inputFocus", //Deal with the focus in the field.
            "blur input": "inputBlur", //Deal with the focus out of the field.
            "click .panel-collapse.in": "hideCollapse",
            "click .panel-collapse:not('.in')": "showCollapse",
            "click button[data-loading]": "loadingButton"
        },
        //Input focus event.
        inputFocus: function coreViewInputFocus(event) {
            if (!this.model.has('errors')) {
                return;
            }
            //Remove the input hidden attribute.
            return event.target.parentElement.parentElement.childNodes[5].removeAttribute('hidden');
        },
        //Input blur event gestion
        inputBlur: function coreViewInputBlur(event) {
            if (!this.model.has('errors')) {
                return;
            }
            //If there is an error add the hidden attribute into it in odere to hide the errors.
            return event.target.parentElement.parentElement.childNodes[5].setAttribute("hidden", "hidden");
        },
        //This method is use in order to inject json data to the template. By default, the this.model.toJSON() is called.
        getRenderData: function getCoreViewRenderData() {
            return this.model.toJSON();
        },
        showCollapse: function showCollapseCoreView() {
            $('.collapse', this.$el).collapse('show');
        },
        hideCollapse: function hideCollapseCoreView() {
            $('.collapse', this.$el).collapse('hide');
        },
        toogleCollapse: function toogleCollapseCoreView(event) {
            $(".panel-collapse.in", event.target.parentNode.parentNode).collapse('hide'); //todo: change the selector
            $(".panel-collapse:not('.in')", event.target.parentNode.parentNode).collapse('show');
        },
        //Render function  by default call the getRenderData and inject it into the view dom element.
        render: function renderCoreView() {
            //If the view is not ready.
            this.$el.html(this.template(this.getRenderData()));

            //_.defer(this.afterRender, this);
            return this;
        },
        afterRender: function afterRenderCoreView() {
            //Eventually pass the currentview as argument for this binding.
            postRenderingBuilder({
                model: this.model,
                viewSelector: this.$el
            });
            $('.collapse', this.$el).collapse({
                toogle: true
            });
        },
        //Get the criteria from the session storage if exists.
        getSessionCriteria: function getCriteria() {
            return sessionHelper.getItem(this.getCriteriaId());
        },
        //Save the criteria in the session storage.
        saveSessionCriteria: function saveSessionCriteria(criteria) {
            return sessionHelper.saveItem(this.getCriteriaId(), criteria);
        },
        // Get the id of the criteria.
        getCriteriaId: function getCriteriaId() {
            var hash = window.location.hash;
            if (this.model.modelName !== undefined) {
                hash += this.model.modelName;
            }
            if (this.opts.criteriaId !== undefined) {
                hash += this.opts.criteriaId;
            }
            return hash;
        },
        //Call the history back.
        back: function back() {
            Backbone.history.history.back();
        },
        //Function which tells if the view is ready to be display.
        isReady: function isReady() {
            return this.opts.isReadyReferences === true;
        },
        //renderSpinner
        renderSpinner: function renderSpinner() {
            this.$el.html(this.templateSpinner(this.getRenderData()));
            return this;
        },
        /**
         * Change the button state (loading, reset) ...
         * @param  {string} selector - CSS selector for the button.
         * @param  {string} state    - The new state you want for the button.
         * @return {undefined}
         */
        changeButtonState: function changeButtonState(selector, state){
            $(selector, this.$el).button(state);
        }
    });

    // Differenciating export for node or browser.
    if (isInBrowser) {
        NS.Views = NS.Views || {};
        NS.Views.CoreView = CoreView;
    } else {
        module.exports = CoreView;
    }
})(typeof module === 'undefined' && typeof window !== 'undefined' ? window.Fmk : module.exports);
// ## Example calll:
// ```javascript
// var CoreView = require('./views/core-view');
// new CoreView({model: new Model({firstName: "first name", lastName: "last name"}).render().el //Get the dom element of the view.
//```<commit_msg>Add debug functinnality to the views #15.<commit_after>/*global Backbone, _, window, Promise, $ */
"use strict";
(function(NS) {
    //Filename: views/core-view.js
    NS = NS || {};
    var isInBrowser = typeof module === 'undefined' && typeof window !== 'undefined';
    var postRenderingBuilder = isInBrowser ? NS.Helpers.postRenderingBuilder : require('../helpers/post_rendering_builder');
    var ErrorHelper = isInBrowser ? NS.Helpers.errorHelper : require('../helpers/error_helper');
    var RefHelper = isInBrowser ? NS.Helpers.referenceHelper : require('../helpers/reference_helper');
    var ArgumentNullException = isInBrowser ? NS.Helpers.Exceptions.ArgumentNullException : require("../helpers/custom_exception").ArgumentNullException;
    var Model = isInBrowser ? NS.Models.Model : require("../models/model");
    var PaginatedCollection = isInBrowser ? NS.Models.PaginatedCollection : require("../models/paginatedCollection");
    var sessionHelper = isInBrowser ? NS.Helpers.sessionHelper : require('../helpers/session_helper');
    var templateSpinner = isInBrowser ? NS.templates.spinner : function() {
        return "Template spinner to define...";
    };
    //View which is the default view for each view.
    //This view is able to deal with errors and to render the default json moodel.
    var CoreView = Backbone.View.extend({
        toogleIsHidden: function(options) {
            this.isHidden = !this.isHidden;
            this.render(options);
        },
        //Reference lists names.
        //These _names_, must have been registered inside the the application to be used.
        referenceNames: undefined,

        //Options define by default for the view.
        defaultOptions: {
            isElementRedefinition: false, //This options is use in order to not have a tag container generated by Backbone arround the view.
            isReadyReferences: true
        },
        //Options overriden By the instanciate view.
        customOptions: {},

        //This property is use in order to create a new Model if no model are define in the view.
        modelName: undefined,

        //Initialization of the coreview.
        initialize: function initializeCoreView(options) {
            options = options || {};
            //Define default options foreach _core_ view, and override these options for each _project view_.
            //Then each view will have access to options in any methods.
            this.opts = _.extend({}, this.defaultOptions, this.customOptions, options);

            this.on('toogleIsHidden', this.toogleIsHidden);
            this.initializeModel();

            /*Register after renger.*/
            _.bindAll(this, 'render', 'afterRender');
            var _this = this;
            this.render = _.wrap(this.render, function(render, options) {
                //If the view is ready perform the standard render.
                if (_this.isReady()) {
                    render(options);
                    _this.afterRender();
                } else {
                    //Else render the spinner.
                    this.renderSpinner();
                }
                return _this;
            });

            //Listen to the reference list loading.
            this.listenTo(this.model, "references:loaded", this.render, this);

            //Load all the references lists which are defined in referenceNames.
            var currentView = this;
            if (_.isArray(this.referenceNames) && this.referenceNames.length > 0) {
                this.opts.isReadyReferences = false;
                Promise.all(RefHelper.loadMany(this.referenceNames)).then(function(results) {
                    currentView.opts.isReadyReferences = true;
                    //console.log('resultsreferenceNames', results);
                    var res = {}; //Container for all the results.
                    for (var i = 0, l = results.length; i < l; i++) {
                        res[currentView.referenceNames[i]] = results[i];
                        //The results are save into an object with a name for each reference list.
                    }
                    //Add the reference lists as model properties.
                    _.extend(currentView.model, res);
                    currentView.model.trigger('references:loaded');
                    //Inform the view that we are ready to render well.
                }).then(null, function(error) {
                    currentView.opts.isReadyReferences = true;
                    currentView.render();
                    ErrorHelper.manageResponseErrors(error, {
                        isDisplay: true
                    });
                });
            }

        },

        //Initialize the model of the view.
        //In order to be able to be initialize, a view must have a _model_ or a _modelName_.
        initializeModel: function initializeModelCoreView() {
            if (this.model) {
                return;
            } else if (this.opts.modelName) {
                //Création d'une collection et d'un model
                var ModelCreated = Model.extend({
                    modelName: this.opts.modelName
                });
                //Case of a collection.
                if (this.opts.modelType !== undefined && this.opts.modelType === "collection") {
                    var CollectionCreated = PaginatedCollection.extend({
                        modelName: this.opts.modelName,
                        model: ModelCreated
                    });
                    this.model = new CollectionCreated();
                } else {
                    //Case of a model.
                    this.model = new ModelCreated();

                }
            } else {
                throw new ArgumentNullException("The view must have a model or a model name.", this);
            }
        },
        //The handlebars template has to be defined here.
        template: function emptyTemplate(json) {
            console.log("templateData", json);
            return "
Your template has to be implemented.
";
        }, // Example: require('./templates/coreView'),
        templateSpinner: templateSpinner,
        //Defaults events.
        events: {
            "focus input": "inputFocus", //Deal with the focus in the field.
            "blur input": "inputBlur", //Deal with the focus out of the field.
            "click .panel-collapse.in": "hideCollapse",
            "click .panel-collapse:not('.in')": "showCollapse",
            "click button[data-loading]": "loadingButton"
        },
        //Input focus event.
        inputFocus: function coreViewInputFocus(event) {
            if (!this.model.has('errors')) {
                return;
            }
            //Remove the input hidden attribute.
            return event.target.parentElement.parentElement.childNodes[5].removeAttribute('hidden');
        },
        //Input blur event gestion
        inputBlur: function coreViewInputBlur(event) {
            if (!this.model.has('errors')) {
                return;
            }
            //If there is an error add the hidden attribute into it in odere to hide the errors.
            return event.target.parentElement.parentElement.childNodes[5].setAttribute("hidden", "hidden");
        },
        //This method is use in order to inject json data to the template. By default, the this.model.toJSON() is called.
        getRenderData: function getCoreViewRenderData() {
            return this.model.toJSON();
        },
        showCollapse: function showCollapseCoreView() {
            $('.collapse', this.$el).collapse('show');
        },
        hideCollapse: function hideCollapseCoreView() {
            $('.collapse', this.$el).collapse('hide');
        },
        toogleCollapse: function toogleCollapseCoreView(event) {
            $(".panel-collapse.in", event.target.parentNode.parentNode).collapse('hide'); //todo: change the selector
            $(".panel-collapse:not('.in')", event.target.parentNode.parentNode).collapse('show');
        },
        /**
         * Debug the core View. Display whatever you need in the console on render.
         * @return {undefined}
         */
        debug: function debugCoreView(){
            console.log("--------------CORE VIEW-----------------");
            console.log("View:     ",  this);
            console.log("Model:    ", this.model);
            console.log("Template: ",this.template(this.getRenderData)());
            console.log("--------------CORE VIEW-----------------");
        },
        //Render function  by default call the getRenderData and inject it into the view dom element.
        render: function renderCoreView() {
            if(this.opts.DEBUG){
                this.debug();
            }
            //If the view is not ready.
            this.$el.html(this.template(this.getRenderData()));

            //_.defer(this.afterRender, this);
            return this;
        },
        afterRender: function afterRenderCoreView() {
            //Eventually pass the currentview as argument for this binding.
            postRenderingBuilder({
                model: this.model,
                viewSelector: this.$el
            });
            $('.collapse', this.$el).collapse({
                toogle: true
            });
        },
        //Get the criteria from the session storage if exists.
        getSessionCriteria: function getCriteria() {
            return sessionHelper.getItem(this.getCriteriaId());
        },
        //Save the criteria in the session storage.
        saveSessionCriteria: function saveSessionCriteria(criteria) {
            return sessionHelper.saveItem(this.getCriteriaId(), criteria);
        },
        // Get the id of the criteria.
        getCriteriaId: function getCriteriaId() {
            var hash = window.location.hash;
            if (this.model.modelName !== undefined) {
                hash += this.model.modelName;
            }
            if (this.opts.criteriaId !== undefined) {
                hash += this.opts.criteriaId;
            }
            return hash;
        },
        //Call the history back.
        back: function back() {
            Backbone.history.history.back();
        },
        //Function which tells if the view is ready to be display.
        isReady: function isReady() {
            return this.opts.isReadyReferences === true;
        },
        //renderSpinner
        renderSpinner: function renderSpinner() {
            this.$el.html(this.templateSpinner(this.getRenderData()));
            return this;
        },
        /**
         * Change the button state (loading, reset) ...
         * @param  {string} selector - CSS selector for the button.
         * @param  {string} state    - The new state you want for the button.
         * @return {undefined}
         */
        changeButtonState: function changeButtonState(selector, state){
            $(selector, this.$el).button(state);
        }
    });

    // Differenciating export for node or browser.
    if (isInBrowser) {
        NS.Views = NS.Views || {};
        NS.Views.CoreView = CoreView;
    } else {
        module.exports = CoreView;
    }
})(typeof module === 'undefined' && typeof window !== 'undefined' ? window.Fmk : module.exports);
// ## Example calll:
// ```javascript
// var CoreView = require('./views/core-view');
// new CoreView({model: new Model({firstName: "first name", lastName: "last name"}).render().el //Get the dom element of the view.
//```<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import Portal from './portal';
import StubItem from '../atom-items/stub-item';

/**
 * `DockItem` adds its child to an Atom dock when rendered.
 * When the item is closed, the component's `onDidCloseItem` is called.
 * You should use this callback to set state so that the `DockItem` is no
 * longer rendered; you will get an error in your console if you forget.
 *
 * You may pass a `getItem` function that takes an object with `portal` and
 * `subtree` properties. `getItem` should return an item to be added to the
 * Dock. `portal` is an instance of th Portal component, and `subtree` is the
 * rendered subtree component built from the `children` prop. The default
 * implementation simply returns the Portal instance, which contains a
 * `getElement` method (to be compatible with Atom's view system).
 *
 * Unmounting the component when the item is open will close the item.
 */
export default class DockItem extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    children: PropTypes.element.isRequired,
    getItem: PropTypes.func,
    onDidCloseItem: PropTypes.func,
    stubItemSelector: PropTypes.string,
    activate: PropTypes.bool,
  }

  static defaultProps = {
    getItem: ({portal, subtree}) => portal.getView(),
    onDidCloseItem: dockItem => {},
  }

  componentDidMount() {
    this.setupDockItem();
  }

  componentWillReceiveProps() {
    if (this.didCloseItem) {
      // eslint-disable-next-line no-console
      console.error('Unexpected update in `DockItem`: the contained item has been closed');
    }
  }

  render() {
    let getDOMNode;
    if (this.props.stubItemSelector) {
      getDOMNode = () => StubItem.getElementBySelector(this.props.stubItemSelector);
    }

    return <Portal ref={c => { this.portal = c; }} getDOMNode={getDOMNode}>{this.props.children}</Portal>;
  }

  setupDockItem() {
    if (this.dockItem) { return; }

    const itemToAdd = this.props.getItem({portal: this.portal, subtree: this.portal.getRenderedSubtree()});
    let stub;
    if (this.props.stubItemSelector) {
      stub = StubItem.getBySelector(this.props.stubItemSelector);
    }

    if (stub) {
      stub.setRealItem(itemToAdd);
      this.dockItem = stub;
      if (this.props.activate) {
        this.activate();
      }
    } else {
      Promise.resolve(this.props.workspace.open(itemToAdd, {activatePane: false}))
        .then(item => {
          this.dockItem = item;
          if (this.props.activate) { this.activate(); }
        });
    }

    this.subscriptions = this.props.workspace.onDidDestroyPaneItem(({item}) => {
      if (item === this.dockItem) {
        this.didCloseItem = true;
        this.props.onDidCloseItem(this.dockItem);
      }
    });
  }

  getDockItem() {
    return this.dockItem;
  }

  componentWillUnmount() {
    this.subscriptions && this.subscriptions.dispose();
    if (this.dockItem && !this.didCloseItem) {
      const pane = this.props.workspace.paneForItem(this.dockItem);
      if (this.dockItem.destroy) {
        this.dockItem.destroy();
      }
      pane.destroyItem(this.dockItem);
    }
  }

  activate() {
    setTimeout(() => {
      if (!this.dockItem || this.didCloseItem || this.props.workspace.isDestroyed()) {
        return;
      }

      const pane = this.props.workspace.paneForItem(this.dockItem);
      if (pane) {
        pane.activateItem(this.dockItem);
      } else {
        throw new Error('Cannot find pane for item in `DockItem#activate`');
      }
    });
  }
}
<commit_msg>Ensure that activating a DockItem shows the corresponding Dock<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import Portal from './portal';
import StubItem from '../atom-items/stub-item';

/**
 * `DockItem` adds its child to an Atom dock when rendered.
 * When the item is closed, the component's `onDidCloseItem` is called.
 * You should use this callback to set state so that the `DockItem` is no
 * longer rendered; you will get an error in your console if you forget.
 *
 * You may pass a `getItem` function that takes an object with `portal` and
 * `subtree` properties. `getItem` should return an item to be added to the
 * Dock. `portal` is an instance of th Portal component, and `subtree` is the
 * rendered subtree component built from the `children` prop. The default
 * implementation simply returns the Portal instance, which contains a
 * `getElement` method (to be compatible with Atom's view system).
 *
 * Unmounting the component when the item is open will close the item.
 */
export default class DockItem extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    children: PropTypes.element.isRequired,
    getItem: PropTypes.func,
    onDidCloseItem: PropTypes.func,
    stubItemSelector: PropTypes.string,
    activate: PropTypes.bool,
  }

  static defaultProps = {
    getItem: ({portal, subtree}) => portal.getView(),
    onDidCloseItem: dockItem => {},
  }

  componentDidMount() {
    this.setupDockItem();
  }

  componentWillReceiveProps() {
    if (this.didCloseItem) {
      // eslint-disable-next-line no-console
      console.error('Unexpected update in `DockItem`: the contained item has been closed');
    }
  }

  render() {
    let getDOMNode;
    if (this.props.stubItemSelector) {
      getDOMNode = () => StubItem.getElementBySelector(this.props.stubItemSelector);
    }

    return <Portal ref={c => { this.portal = c; }} getDOMNode={getDOMNode}>{this.props.children}</Portal>;
  }

  setupDockItem() {
    if (this.dockItem) { return; }

    const itemToAdd = this.props.getItem({portal: this.portal, subtree: this.portal.getRenderedSubtree()});
    let stub;
    if (this.props.stubItemSelector) {
      stub = StubItem.getBySelector(this.props.stubItemSelector);
    }

    if (stub) {
      stub.setRealItem(itemToAdd);
      this.dockItem = stub;
      if (this.props.activate) {
        this.activate();
      }
    } else {
      Promise.resolve(this.props.workspace.open(itemToAdd, {activatePane: false}))
        .then(item => {
          this.dockItem = item;
          if (this.props.activate) { this.activate(); }
        });
    }

    this.subscriptions = this.props.workspace.onDidDestroyPaneItem(({item}) => {
      if (item === this.dockItem) {
        this.didCloseItem = true;
        this.props.onDidCloseItem(this.dockItem);
      }
    });
  }

  getDockItem() {
    return this.dockItem;
  }

  componentWillUnmount() {
    this.subscriptions && this.subscriptions.dispose();
    if (this.dockItem && !this.didCloseItem) {
      const pane = this.props.workspace.paneForItem(this.dockItem);
      if (this.dockItem.destroy) {
        this.dockItem.destroy();
      }
      pane.destroyItem(this.dockItem);
    }
  }

  activate() {
    setTimeout(() => {
      if (!this.dockItem || this.didCloseItem || this.props.workspace.isDestroyed()) {
        return;
      }

      const pane = this.props.workspace.paneForItem(this.dockItem);
      if (pane) {
        pane.activateItem(this.dockItem);
        const dock = this.props.workspace.getPaneContainers()
          .find(container => container.getPanes().find(p => p.getItems().includes(this.dockItem)));
        if (dock && dock.constructor.name === 'Dock') {
          dock.show();
        }
      } else {
        throw new Error('Cannot find pane for item in `DockItem#activate`');
      }
    });
  }
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var $ = require('jquery');
var DynamicLegendViewBase = require('../base/dynamic-legend-view-base');
var template = require('./legend-template.tpl');

var BubbleLegendView = DynamicLegendViewBase.extend({

  events: {
    'mouseover .js-bubbleItem': '_onBubbleHover',
    'mouseout .js-bubbleItem': '_onBubbleOut'
  },

  _onBubbleHover: function (event) {
    var bubble = $(event.target);
    this.$('.js-bubbleItem').addClass('is-filter');
    bubble.removeClass('is-filter');
  },

  _onBubbleOut: function (event) {
    this.$('.js-bubbleItem').removeClass('is-filter');
  },

  _getCompiledTemplate: function () {
    return template({
      labels: this.model.get('values').slice(0).reverse(),
      bubbleSizes: this._calculateBubbleSizes(),
      labelPositions: this._calculateLabelPositions(),
      avgSize: this._calculateAverageSize(),
      avgLabel: this.model.get('avg'),
      fillColor: this.model.get('fillColor')
    });
  },

  _calculateLabelPositions: function () {
    var sizes = this.model.get('sizes').slice(0).reverse();
    var maxSize = sizes[0];
    var labelPositions = _.map(sizes, function (size, index) {
      if (index === 0) {
        return '100';
      }
      return size * 100 / maxSize;
    });
    labelPositions.unshift(0);
    return labelPositions;
  },

  _calculateBubbleSizes: function () {
    var sizes = this.model.get('sizes').slice(0).reverse();
    var maxSize = sizes[0];
    return _.map(sizes, function (size, index) {
      if (index === 0) {
        return '100';
      }

      return size * 100 / maxSize;
    });
  },

  _calculateAverageSize: function () {
    var values = this.model.get('values').slice(0).reverse();
    var maxValue = values[0];
    return this.model.get('avg') * 100 / maxValue;
  }
});

module.exports = BubbleLegendView;
<commit_msg>Calculate label positions correctly<commit_after>var _ = require('underscore');
var $ = require('jquery');
var DynamicLegendViewBase = require('../base/dynamic-legend-view-base');
var template = require('./legend-template.tpl');

var BubbleLegendView = DynamicLegendViewBase.extend({

  events: {
    'mouseover .js-bubbleItem': '_onBubbleHover',
    'mouseout .js-bubbleItem': '_onBubbleOut'
  },

  _onBubbleHover: function (event) {
    var bubble = $(event.target);
    this.$('.js-bubbleItem').addClass('is-filter');
    bubble.removeClass('is-filter');
  },

  _onBubbleOut: function (event) {
    this.$('.js-bubbleItem').removeClass('is-filter');
  },

  _getCompiledTemplate: function () {
    return template({
      labels: this.model.get('values').slice(0).reverse(),
      bubbleSizes: this._calculateBubbleSizes(),
      labelPositions: this._calculateLabelPositions(),
      avgSize: this._calculateAverageSize(),
      avgLabel: this.model.get('avg'),
      fillColor: this.model.get('fillColor')
    });
  },

  _calculateLabelPositions: function () {
    var labelPositions = this._calculateBubbleSizes();
    labelPositions.push(0);
    return labelPositions;
  },

  _calculateBubbleSizes: function () {
    var sizes = this.model.get('sizes').slice(0).reverse();
    var maxSize = sizes[0];
    return _.map(sizes, function (size, index) {
      if (index === 0) {
        return '100';
      }

      return size * 100 / maxSize;
    });
  },

  _calculateAverageSize: function () {
    var values = this.model.get('values').slice(0).reverse();
    var maxValue = values[0];
    return this.model.get('avg') * 100 / maxValue;
  }
});

module.exports = BubbleLegendView;
<|endoftext|>