<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function initialize()
        //runs at onload of window
        {
        if (document.getElementById("articleBody") != null) initArticle(); //lays out the article in columns(if one exists)
        userEventsInit(); //set up all user events
        document.onmousemove = mousePosition; //moz
        }

var mouseX = mouseY =0;
menus = new Array("File","Search","Help","Debug")
var allEvents = new Array()
var activeMenu = null; //defines which menu is currently open

function screenObject()
        {

        this.bottom = function(){
                if (document.body.scrollHeight) return document.body.scrollHeight};

        this.height = function() {
                if (document.body.offsetHeight) return document.body.offsetHeight;}

        this.visHeight = function() {
                if (window.innerHeight) return window.innerHeight;
                if (document.body.clientHeight) return document.body.clientHeight;}

        this.width = function() {
                if (document.body.offsetWidth) return document.body.offsetWidth;}

        this.scrollTop = function() {
                if(document.body.scrollTop) return document.body.scrollTop
                if (window.pageYOffset) return window.pageYOffset;
                else return 0;};

        }

function mousePosition(e)
        {
        if (e) event = e;   //for Netscape
        mouseX = event.clientX;
        mouseY = event.clientY;
        }

function menuOver()
        {
        document.onclick = null;
        if (document.all) event.cancelBubble=true
        }
function menuOut()
        {
        document.onclick = eventHideMenu;
        if (document.all) event.cancelBubble=true
        }

function eventShowPopUp(target)
        //this will display info pop ups, for example art event details

        {
        if (activeMenu != null) eventHideMenu()
        activeMenu = target;
        obj = document.getElementById(activeMenu)
        obj.style.display = "block"
        if (event) event.cancelBubble=true
        }

function eventShowArtPopUp(target)
        //this will display info pop ups, for example art event details

        {

        if (activeMenu != null) eventHideMenu()
        activeMenu = target;
        obj = document.getElementById(activeMenu)
        obj.style.display = "block"
        obj.style.visibility = "visible"

        obj.style.top = -20+mouseY+ihtScreen.scrollTop()+"px"
        if (event) event.cancelBubble=true
        }

function eventShowMenu(e)
        //turns on the display for nav menus
        {
        if (activeMenu != null) eventHideMenu()
        activeMenu = "menu"+this.id.substring(3,this.id.length)
        obj = document.getElementById(activeMenu)
        if (obj) obj.style.visibility = "visible"
        if (document.all) document.onclick = eventHideMenu;
        event.cancelBubble=true

        }

function eventHideMenu()
        //hides nav menus and pop ups
        {
        document.onclick = null;
        if (activeMenu != null)
                {
                obj = document.getElementById(activeMenu)
                obj.style.visibility = "hidden"
                }
        }

function userEventsInit()
        {
        //nav events
                for (i=0; i < menus.length; i++)
                {
                obj = document.getElementById("nav"+menus[i])
                obj.onclick = eventShowMenu;

                obj = document.getElementById("menu"+menus[i])
                obj.onmouseover = menuOver;
                obj.onmouseout = menuOut;
                }

 }

<commit_msg>removed legacy initArticle() check. the function was not even defined..<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function initialize()
        //runs at onload of window
        {
        userEventsInit(); //set up all user events
        document.onmousemove = mousePosition; //moz
        }

var mouseX = mouseY =0;
menus = new Array("File","Search","Help","Debug")
var allEvents = new Array()
var activeMenu = null; //defines which menu is currently open

function screenObject()
        {

        this.bottom = function(){
                if (document.body.scrollHeight) return document.body.scrollHeight};

        this.height = function() {
                if (document.body.offsetHeight) return document.body.offsetHeight;}

        this.visHeight = function() {
                if (window.innerHeight) return window.innerHeight;
                if (document.body.clientHeight) return document.body.clientHeight;}

        this.width = function() {
                if (document.body.offsetWidth) return document.body.offsetWidth;}

        this.scrollTop = function() {
                if(document.body.scrollTop) return document.body.scrollTop
                if (window.pageYOffset) return window.pageYOffset;
                else return 0;};

        }

function mousePosition(e)
        {
        if (e) event = e;   //for Netscape
        mouseX = event.clientX;
        mouseY = event.clientY;
        }

function menuOver()
        {
        document.onclick = null;
        if (document.all) event.cancelBubble=true
        }
function menuOut()
        {
        document.onclick = eventHideMenu;
        if (document.all) event.cancelBubble=true
        }

function eventShowPopUp(target)
        //this will display info pop ups, for example art event details

        {
        if (activeMenu != null) eventHideMenu()
        activeMenu = target;
        obj = document.getElementById(activeMenu)
        obj.style.display = "block"
        if (event) event.cancelBubble=true
        }

function eventShowArtPopUp(target)
        //this will display info pop ups, for example art event details

        {

        if (activeMenu != null) eventHideMenu()
        activeMenu = target;
        obj = document.getElementById(activeMenu)
        obj.style.display = "block"
        obj.style.visibility = "visible"

        obj.style.top = -20+mouseY+ihtScreen.scrollTop()+"px"
        if (event) event.cancelBubble=true
        }

function eventShowMenu(e)
        //turns on the display for nav menus
        {
        if (activeMenu != null) eventHideMenu()
        activeMenu = "menu"+this.id.substring(3,this.id.length)
        obj = document.getElementById(activeMenu)
        if (obj) obj.style.visibility = "visible"
        if (document.all) document.onclick = eventHideMenu;
        event.cancelBubble=true

        }

function eventHideMenu()
        //hides nav menus and pop ups
        {
        document.onclick = null;
        if (activeMenu != null)
                {
                obj = document.getElementById(activeMenu)
                obj.style.visibility = "hidden"
                }
        }

function userEventsInit()
        {
        //nav events
                for (i=0; i < menus.length; i++)
                {
                obj = document.getElementById("nav"+menus[i])
                obj.onclick = eventShowMenu;

                obj = document.getElementById("menu"+menus[i])
                obj.onmouseover = menuOver;
                obj.onmouseout = menuOut;
                }

 }

<|endoftext|>


<commit_before>var express     = require('express')
  , Promise     = require('bluebird')
  , bodyParser  = require('body-parser')
  , winston     = require('winston')
  , config      = require('config')
  , _           = require('lodash')
  , crypto      = require('crypto')
  , express_jwt = require('express-jwt')
  // todo [akamel] remove this module
  , auth_header = require('auth-header')
  , mongoose    = require('mongoose')
  , morgan      = require('morgan')
  , ipfilter    = require('express-ipfilter').IpFilter
  //
  , mongodb     = require('./api/mongodb')
  , docusign    = require('./api/docusign')
  , secret      = require('./api/secret')
  , auth        = require('./auth/index')
  //
  , User        = require('./model/User')
  , Credential  = require('./model/Credential')
  , Repository  = require('./model/Repository')
  , Mongo       = require('./model/backend/Mongo')
  ;

mongoose.connect(config.getUrl('mongo'));

var app = express();

app.use(bodyParser.json());

app.use(morgan('dev'));

var auth_middleware = express_jwt({
    secret          : config.get('jwt.public')
  // , getToken  : (req) => req.body.token
  , algorithm       : 'RS256'
  , requestProperty : 'jwt_payload'
});

var ipfilter_middleware = _.size(config.get('account.ip-whitelist'))
                            ? ipfilter(config.get('account.ip-whitelist'), { mode : 'allow', allowedHeaders : ['x-forwarded-for'] })
                            : (req, res, next) => next();

app.get('/mongodb/creds', auth_middleware, mongodb.creds)
app.get('/docusign/creds', auth_middleware, docusign.creds)

// todo [akamel] protect ? already protected by token in path?
app.get('/account/:id/secret/:key/token', secret.token);
app.put('/account/:id/secret/', ipfilter_middleware, secret.create);
app.delete('/account/:id/secret/:hash', ipfilter_middleware, secret.del);

app.use(auth.passport.initialize());
app.use(auth.passport.session());
app.get('/auth/logout', auth.logout);
app.get('/auth/:provider', auth.login);
app.get('/auth/:provider/callback', auth.callback);

app.get('/account', auth_middleware, (req, res, next) => {
  let _id = req.jwt_payload.sub;

  User
    .findById(_id)
    .exec()
    .then((account) => {
      res.send({ data : account.sanitize() });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:id/git_token', auth_middleware, (req, res, next) => {
  let _id = req.jwt_payload.sub
    , id  = req.params['id']
    ;

  Promise
    .try(() => {
      if (_id != id) {
        throw new Error('id mismatch');
      }

      return User.findOne({ _id }).exec();
    })
    .then((account) => {
      let rdns = User.reverseDNS(provider);

      res.send({ data : { token : _.get(account, `accounts.${rdns}._token`) } });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:id/token/', ipfilter_middleware, (req, res, next) => {
  var { id }          = req.params
    , { expires_in }  = req.query
    ;

  User
    .findById(id)
    .exec()
    .then((account) => {
      if (!account) {
        throw new Error('not found');
      }

      return account
              .issueJWT({ expiresIn : expires_in })
              .then((token) => {
                res.send({ data : token });
              });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:provider/:id/token', ipfilter_middleware, (req, res, next) => {
  var { id, provider }  = req.params
    , { expires_in }    = req.query
    , rdns              = User.reverseDNS(provider)
    , query             = {
          provider
        , [`accounts.${rdns}.username`] : id
      }
    ;

  User
    .findOne(query)
    .exec()
    .then((account) => {
      if (!account) {
        throw new Error('not found');
      }

      return account
              .issueJWT({ expiresIn : expires_in })
              .then((token) => {
                res.send({ data : token });
              });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:provider/:id/git_token', ipfilter_middleware, (req, res, next) => {
  var provider    = req.params['provider']
    , id          = req.params['id']
    , rdns        = User.reverseDNS(provider)
    , query       = {
          provider
        , [`accounts.${rdns}.username`] : id
      }
    ;

  Promise
    .try(() => {
      return User.findOne(query).exec();
    })
    .then((account) => {
      let rdns = User.reverseDNS(provider);

      res.send({ data : { token : _.get(account, `accounts.${rdns}._token`) } });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:_id/', ipfilter_middleware, (req, res, next) => {
  var _id = req.params['_id'];

  User
    .findById(_id)
    .exec()
    .then((account) => {
      res.send({ data : account.sanitize() });
    })
    .catch((err) => {
      next(err);
    });
});

app.use(function(err, req, res, next) {
  switch (err.message) {
    case 'not found':
    res.status(404);
    break;
    default:
    res.status(500);
  }

  if (err.name === 'UnauthorizedError') {
    res.status(401);
    err.message = 'unauthorized';
  }

  res.send({ message : err.message });
});

function listen(options, cb) {
  return Promise
          .promisify(app.listen, { context : app})(options.port)
          .nodeify(cb);
}

module.exports = {
    listen : listen
};<commit_msg>mongo crews is post<commit_after>var express     = require('express')
  , Promise     = require('bluebird')
  , bodyParser  = require('body-parser')
  , winston     = require('winston')
  , config      = require('config')
  , _           = require('lodash')
  , crypto      = require('crypto')
  , express_jwt = require('express-jwt')
  // todo [akamel] remove this module
  , auth_header = require('auth-header')
  , mongoose    = require('mongoose')
  , morgan      = require('morgan')
  , ipfilter    = require('express-ipfilter').IpFilter
  //
  , mongodb     = require('./api/mongodb')
  , docusign    = require('./api/docusign')
  , secret      = require('./api/secret')
  , auth        = require('./auth/index')
  //
  , User        = require('./model/User')
  , Credential  = require('./model/Credential')
  , Repository  = require('./model/Repository')
  , Mongo       = require('./model/backend/Mongo')
  ;

mongoose.connect(config.getUrl('mongo'));

var app = express();

app.use(bodyParser.json());

app.use(morgan('dev'));

var auth_middleware = express_jwt({
    secret          : config.get('jwt.public')
  // , getToken  : (req) => req.body.token
  , algorithm       : 'RS256'
  , requestProperty : 'jwt_payload'
});

var ipfilter_middleware = _.size(config.get('account.ip-whitelist'))
                            ? ipfilter(config.get('account.ip-whitelist'), { mode : 'allow', allowedHeaders : ['x-forwarded-for'] })
                            : (req, res, next) => next();

app.post('/mongodb/creds', auth_middleware, mongodb.creds)
app.get('/docusign/creds', auth_middleware, docusign.creds)

// todo [akamel] protect ? already protected by token in path?
app.get('/account/:id/secret/:key/token', secret.token);
app.put('/account/:id/secret/', ipfilter_middleware, secret.create);
app.delete('/account/:id/secret/:hash', ipfilter_middleware, secret.del);

app.use(auth.passport.initialize());
app.use(auth.passport.session());
app.get('/auth/logout', auth.logout);
app.get('/auth/:provider', auth.login);
app.get('/auth/:provider/callback', auth.callback);

app.get('/account', auth_middleware, (req, res, next) => {
  let _id = req.jwt_payload.sub;

  User
    .findById(_id)
    .exec()
    .then((account) => {
      res.send({ data : account.sanitize() });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:id/git_token', auth_middleware, (req, res, next) => {
  let _id = req.jwt_payload.sub
    , id  = req.params['id']
    ;

  Promise
    .try(() => {
      if (_id != id) {
        throw new Error('id mismatch');
      }

      return User.findOne({ _id }).exec();
    })
    .then((account) => {
      let rdns = User.reverseDNS(provider);

      res.send({ data : { token : _.get(account, `accounts.${rdns}._token`) } });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:id/token/', ipfilter_middleware, (req, res, next) => {
  var { id }          = req.params
    , { expires_in }  = req.query
    ;

  User
    .findById(id)
    .exec()
    .then((account) => {
      if (!account) {
        throw new Error('not found');
      }

      return account
              .issueJWT({ expiresIn : expires_in })
              .then((token) => {
                res.send({ data : token });
              });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:provider/:id/token', ipfilter_middleware, (req, res, next) => {
  var { id, provider }  = req.params
    , { expires_in }    = req.query
    , rdns              = User.reverseDNS(provider)
    , query             = {
          provider
        , [`accounts.${rdns}.username`] : id
      }
    ;

  User
    .findOne(query)
    .exec()
    .then((account) => {
      if (!account) {
        throw new Error('not found');
      }

      return account
              .issueJWT({ expiresIn : expires_in })
              .then((token) => {
                res.send({ data : token });
              });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:provider/:id/git_token', ipfilter_middleware, (req, res, next) => {
  var provider    = req.params['provider']
    , id          = req.params['id']
    , rdns        = User.reverseDNS(provider)
    , query       = {
          provider
        , [`accounts.${rdns}.username`] : id
      }
    ;

  Promise
    .try(() => {
      return User.findOne(query).exec();
    })
    .then((account) => {
      let rdns = User.reverseDNS(provider);

      res.send({ data : { token : _.get(account, `accounts.${rdns}._token`) } });
    })
    .catch((err) => {
      next(err);
    });
});

app.get('/account/:_id/', ipfilter_middleware, (req, res, next) => {
  var _id = req.params['_id'];

  User
    .findById(_id)
    .exec()
    .then((account) => {
      res.send({ data : account.sanitize() });
    })
    .catch((err) => {
      next(err);
    });
});

app.use(function(err, req, res, next) {
  switch (err.message) {
    case 'not found':
    res.status(404);
    break;
    default:
    res.status(500);
  }

  if (err.name === 'UnauthorizedError') {
    res.status(401);
    err.message = 'unauthorized';
  }

  res.send({ message : err.message });
});

function listen(options, cb) {
  return Promise
          .promisify(app.listen, { context : app})(options.port)
          .nodeify(cb);
}

module.exports = {
    listen : listen
};
<|endoftext|>


<commit_before>/*
* @Author: justinwebb
* @Date:   2015-06-03 15:30:09
* @Last Modified by:   justinwebb
* @Last Modified time: 2015-06-05 15:25:15
*/

'use strict';
(function (angular) {

  var GraphPanelCtrl = function () {

  };

  var link = function ($scope, elem) {
    console.log('GraphPanelDirective: ', elem);
  };

  var GraphPanelDirective = function () {

    return {
      restrict: 'E',
      scope: {
      },
      link: link,
      controller: GraphPanelCtrl,
      template:  [
        '
',
        '
This is the graph page!
',
        ' <svg id="canvas"><g/></svg>',
        '
'
      ].join(',')
    };
  };

  angular
    .module('cd-app.common')
    .directive('graphPanel', GraphPanelDirective);
})(angular);
<commit_msg>(refactor) Change the services and directives file name<commit_after><|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Jun 06 2016 11:19:28 GMT+0200 (Central European Daylight Time)

module.exports = function(config) {
  var configuration = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    coverageReporter: {
        type : 'lcovonly',
        dir : 'coverage/',
    },

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
		'https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js',
		'src/**/*.js',
		'ts/**/*.js',
		'tests/**/*.js',
        { pattern: 'configs/*.json', watched: true, served: true, included: false }
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        './src/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci'];
  }

  if (process.argv.indexOf('-w') >= 0) {
    configuration.singleRun = false;
    configuration.autoWatch = true;
  }

  config.set(configuration)
}
<commit_msg>change lcov location<commit_after>// Karma configuration
// Generated on Mon Jun 06 2016 11:19:28 GMT+0200 (Central European Daylight Time)

module.exports = function(config) {
  var configuration = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    coverageReporter: {
        type : 'lcovonly',
        dir : 'coverage/',
        subdir: '.'
    },

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
		'https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js',
		'src/**/*.js',
		'ts/**/*.js',
		'tests/**/*.js',
        { pattern: 'configs/*.json', watched: true, served: true, included: false }
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        './src/*.js': 'coverage'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci'];
  }

  if (process.argv.indexOf('-w') >= 0) {
    configuration.singleRun = false;
    configuration.autoWatch = true;
  }

  config.set(configuration)
}
<|endoftext|>


<commit_before>/* global _ */
/* eslint-disable more/no-then */

// eslint-disable-next-line func-names
(function() {
  'use strict';

  window.Whisper = window.Whisper || {};

  let ready = false;
  let items;
  let callbacks = [];

  reset();

  async function put(key, value) {
    if (value === undefined) {
      throw new Error('Tried to store undefined');
    }
    if (!ready) {
      window.log.warn('Called storage.put before storage is ready. key:', key);
    }

    const data = { id: key, value };

    items[key] = data;
    await window.Signal.Data.createOrUpdateItem(data);

    if (_.has(window, ['reduxActions', 'items', 'putItemExternal'])) {
      window.reduxActions.items.putItemExternal(key, value);
    }
  }

  function get(key, defaultValue) {
    if (!ready) {
      window.log.warn('Called storage.get before storage is ready. key:', key);
    }

    const item = items[key];
    if (!item) {
      return defaultValue;
    }

    return item.value;
  }

  async function remove(key) {
    if (!ready) {
      window.log.warn('Called storage.get before storage is ready. key:', key);
    }

    delete items[key];
    await window.Signal.Data.removeItemById(key);

    if (_.has(window, ['reduxActions', 'items', 'removeItemExternal'])) {
      window.reduxActions.items.removeItemExternal(key);
    }
  }

  function onready(callback) {
    if (ready) {
      callback();
    } else {
      callbacks.push(callback);
    }
  }

  function callListeners() {
    if (ready) {
      callbacks.forEach(callback => callback());
      callbacks = [];
    }
  }

  async function fetch() {
    this.reset();
    const array = await window.Signal.Data.getAllItems();

    for (let i = 0, max = array.length; i < max; i += 1) {
      const item = array[i];
      const { id } = item;
      items[id] = item;
    }

    ready = true;
    callListeners();
  }

  function getItemsState() {
    const data = _.clone(items);
    const ids = Object.keys(data);
    ids.forEach(id => {
      data[id] = data[id].value;
    });

    return data;
  }

  function reset() {
    ready = false;
    items = Object.create(null);
  }

  const storage = {
    fetch,
    put,
    get,
    getItemsState,
    remove,
    onready,
    reset,
  };

  // Keep a reference to this storage system, since there are scenarios where
  //   we need to replace it with the legacy storage system for a while.
  window.newStorage = storage;

  window.textsecure = window.textsecure || {};
  window.textsecure.storage = window.textsecure.storage || {};

  window.installStorage = newStorage => {
    window.storage = newStorage;
    window.textsecure.storage.impl = newStorage;
  };

  window.installStorage(storage);
})();
<commit_msg>Fix typo (#3345)<commit_after>/* global _ */
/* eslint-disable more/no-then */

// eslint-disable-next-line func-names
(function() {
  'use strict';

  window.Whisper = window.Whisper || {};

  let ready = false;
  let items;
  let callbacks = [];

  reset();

  async function put(key, value) {
    if (value === undefined) {
      throw new Error('Tried to store undefined');
    }
    if (!ready) {
      window.log.warn('Called storage.put before storage is ready. key:', key);
    }

    const data = { id: key, value };

    items[key] = data;
    await window.Signal.Data.createOrUpdateItem(data);

    if (_.has(window, ['reduxActions', 'items', 'putItemExternal'])) {
      window.reduxActions.items.putItemExternal(key, value);
    }
  }

  function get(key, defaultValue) {
    if (!ready) {
      window.log.warn('Called storage.get before storage is ready. key:', key);
    }

    const item = items[key];
    if (!item) {
      return defaultValue;
    }

    return item.value;
  }

  async function remove(key) {
    if (!ready) {
      window.log.warn('Called storage.remove before storage is ready. key:', key);
    }

    delete items[key];
    await window.Signal.Data.removeItemById(key);

    if (_.has(window, ['reduxActions', 'items', 'removeItemExternal'])) {
      window.reduxActions.items.removeItemExternal(key);
    }
  }

  function onready(callback) {
    if (ready) {
      callback();
    } else {
      callbacks.push(callback);
    }
  }

  function callListeners() {
    if (ready) {
      callbacks.forEach(callback => callback());
      callbacks = [];
    }
  }

  async function fetch() {
    this.reset();
    const array = await window.Signal.Data.getAllItems();

    for (let i = 0, max = array.length; i < max; i += 1) {
      const item = array[i];
      const { id } = item;
      items[id] = item;
    }

    ready = true;
    callListeners();
  }

  function getItemsState() {
    const data = _.clone(items);
    const ids = Object.keys(data);
    ids.forEach(id => {
      data[id] = data[id].value;
    });

    return data;
  }

  function reset() {
    ready = false;
    items = Object.create(null);
  }

  const storage = {
    fetch,
    put,
    get,
    getItemsState,
    remove,
    onready,
    reset,
  };

  // Keep a reference to this storage system, since there are scenarios where
  //   we need to replace it with the legacy storage system for a while.
  window.newStorage = storage;

  window.textsecure = window.textsecure || {};
  window.textsecure.storage = window.textsecure.storage || {};

  window.installStorage = newStorage => {
    window.storage = newStorage;
    window.textsecure.storage.impl = newStorage;
  };

  window.installStorage(storage);
})();
<|endoftext|>


<commit_before>if(typeof Merquery == "undefined" ) {
    Merquery = {};
}

Merquery.Queries = {
    //StandardQuery takes the fieldValue and fieldName and runs another query
    //parameters: {var fieldValue, var fieldName}
    standardQuery: function(fieldValue, fieldName, limit, callback) {
        var formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(fieldName);

        var queryString;
        var endString;

        queryString =  "SELECT Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, Demographics.ethnicity," +
            " Demographics.sexorient,Demographics.marital, Demographics.children, Address.Address1, Address.Address2, Address.City," +
            " Address.State, Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count, Behavior.id, Behavior.name, Behavior.last_seen," +
            " Behavior.count, Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, Device.operating_system," +
            " Device.last_seen, Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online," +
            " Purchase.ltv_offline " +

            "FROM (SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children FROM [formal-cascade-571:uci.demo_info] " +
            "where emailmd5 is not null ) AS Demographics " +

            "LEFT JOIN EACH (SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) "+
            "AS Address ON Address.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5 " +

        'where ' + formattedFieldName + ' like "' + fieldValue;

        endString = '" GROUP each BY Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, ' +
            "Demographics.city, Demographics.ethnicity, Demographics.sexorient, Demographics.marital, " +
            "Demographics.children, Address.Address1, Address.Address2, Address.City, Address.State, " +
            "Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, "+
            "Campaign.campaign_name, Campaign.impression_count,Campaign.click_count, Campaign.conversion_count, " +
            "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count, " +
            "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen, " +
            " Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online, Purchase.ltv_offline " +
            'ORDER BY Demographics.emailmd5 Limit ' + limit + ';';

        var request = gapi.client.bigquery.jobs.query({
            'projectId': Merquery.Constants.project_id,
            'timeoutMs': '30000',
            'query': queryString + endString

        });
        request.execute(callback || Merquery.renderResults);
    },

    //PopUpQuery takes the fieldValue and fieldName and runs another query
    //parameters: {var fieldValue, var fieldName}
    popupQuery: function(fieldValue, fieldName) {
        var formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(fieldName);

        var queryString;
        var endString;

        queryString =  "SELECT Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, Demographics.ethnicity," +
            " Demographics.sexorient,Demographics.marital, Demographics.children, Address.Address1, Address.Address2, Address.City," +
            " Address.State, Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count, Behavior.id, Behavior.name, Behavior.last_seen," +
            " Behavior.count, Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, Device.operating_system," +
            " Device.last_seen, Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online," +
            " Purchase.ltv_offline " +

            "FROM (SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children FROM [formal-cascade-571:uci.demo_info] " +
            "where emailmd5 is not null ) AS Demographics " +

            "LEFT JOIN EACH (SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) "+
            "AS Address ON Address.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5 " +

            'where ' + formattedFieldName + ' like "' + fieldValue;

        endString = '" GROUP each BY Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, ' +
            "Demographics.city, Demographics.ethnicity, Demographics.sexorient, Demographics.marital, " +
            "Demographics.children, Address.Address1, Address.Address2, Address.City, Address.State, " +
            "Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, "+
            "Campaign.campaign_name, Campaign.impression_count,Campaign.click_count, Campaign.conversion_count, " +
            "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count, " +
            "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen, " +
            " Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online, Purchase.ltv_offline " +
            'ORDER BY Demographics.emailmd5 Limit ' + '50' + ';';

        var request = gapi.client.bigquery.jobs.query({
            'projectId': Merquery.Constants.project_id,
            'timeoutMs': '30000',
            'query': queryString + endString
        });

        request.execute(Merquery.Popup.renderPopUp);

    },

    //Runs the query when the search button is clicked
    runQuery: function(userInputs) {
        //Merquery.Queries.createQueryArray();

        // For loading indicator
        Merquery.hideNav();
        Merquery.showLoad();
        Merquery.Paginator.hideResultsCount();
        Merquery.BreadCrumbs.hideBreadcrumbs();
        $('#export').empty();
        $('#result').empty();

        var request = gapi.client.bigquery.jobs.query({

            'projectId': Merquery.Constants.project_id,
            'timeoutMs': '30000',
            'query': Merquery.queryMaker.formQuery()

        });
        request.execute(Merquery.renderResults);
    },

};

<commit_msg>Fixed breadcrumbs - displays empty page when all breadcrumbs are deleted<commit_after>if(typeof Merquery == "undefined" ) {
    Merquery = {};
}

Merquery.Queries = {
    //StandardQuery takes the fieldValue and fieldName and runs another query
    //parameters: {var fieldValue, var fieldName}
    standardQuery: function(fieldValue, fieldName, limit, callback) {
        var formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(fieldName);

        var queryString;
        var endString;

        queryString =  "SELECT Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, Demographics.ethnicity," +
            " Demographics.sexorient,Demographics.marital, Demographics.children, Address.Address1, Address.Address2, Address.City," +
            " Address.State, Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count, Behavior.id, Behavior.name, Behavior.last_seen," +
            " Behavior.count, Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, Device.operating_system," +
            " Device.last_seen, Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online," +
            " Purchase.ltv_offline " +

            "FROM (SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children FROM [formal-cascade-571:uci.demo_info] " +
            "where emailmd5 is not null ) AS Demographics " +

            "LEFT JOIN EACH (SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) "+
            "AS Address ON Address.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5 " +

        'where ' + formattedFieldName + ' like "' + fieldValue;

        endString = '" GROUP each BY Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, ' +
            "Demographics.city, Demographics.ethnicity, Demographics.sexorient, Demographics.marital, " +
            "Demographics.children, Address.Address1, Address.Address2, Address.City, Address.State, " +
            "Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, "+
            "Campaign.campaign_name, Campaign.impression_count,Campaign.click_count, Campaign.conversion_count, " +
            "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count, " +
            "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen, " +
            " Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online, Purchase.ltv_offline " +
            'ORDER BY Demographics.emailmd5 Limit ' + limit + ';';

        var request = gapi.client.bigquery.jobs.query({
            'projectId': Merquery.Constants.project_id,
            'timeoutMs': '30000',
            'query': queryString + endString

        });
        request.execute(callback || Merquery.renderResults);
    },

    //PopUpQuery takes the fieldValue and fieldName and runs another query
    //parameters: {var fieldValue, var fieldName}
    popupQuery: function(fieldValue, fieldName) {
        var formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(fieldName);

        var queryString;
        var endString;

        queryString =  "SELECT Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, Demographics.ethnicity," +
            " Demographics.sexorient,Demographics.marital, Demographics.children, Address.Address1, Address.Address2, Address.City," +
            " Address.State, Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count, Behavior.id, Behavior.name, Behavior.last_seen," +
            " Behavior.count, Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, Device.operating_system," +
            " Device.last_seen, Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online," +
            " Purchase.ltv_offline " +

            "FROM (SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children FROM [formal-cascade-571:uci.demo_info] " +
            "where emailmd5 is not null ) AS Demographics " +

            "LEFT JOIN EACH (SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) "+
            "AS Address ON Address.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5 " +

            "LEFT JOIN EACH (SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5 " +

            'where ' + formattedFieldName + ' like "' + fieldValue;

        endString = '" GROUP each BY Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, ' +
            "Demographics.city, Demographics.ethnicity, Demographics.sexorient, Demographics.marital, " +
            "Demographics.children, Address.Address1, Address.Address2, Address.City, Address.State, " +
            "Address.Zip, Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, "+
            "Campaign.campaign_name, Campaign.impression_count,Campaign.click_count, Campaign.conversion_count, " +
            "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count, " +
            "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen, " +
            " Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, Purchase.ltv_online, Purchase.ltv_offline " +
            'ORDER BY Demographics.emailmd5 Limit ' + '50' + ';';

        var request = gapi.client.bigquery.jobs.query({
            'projectId': Merquery.Constants.project_id,
            'timeoutMs': '30000',
            'query': queryString + endString
        });

        request.execute(Merquery.Popup.renderPopUp);

    },

    //Runs the query when the search button is clicked
    runQuery: function(userInputs) {
        //Merquery.Queries.createQueryArray();

        // For loading indicator
        Merquery.hideNav();
        Merquery.showLoad();
        Merquery.Paginator.hideResultsCount();
        Merquery.BreadCrumbs.hideBreadcrumbs();
        $('#export').empty();
        $('#result').empty();

        if (Merquery.BreadCrumbs.crumbs.length ==0){
            Merquery.ClearHeader();
            Merquery.ClearMessage();
            Merquery.hideLoad();
        } else {
            var request = gapi.client.bigquery.jobs.query({

                'projectId': Merquery.Constants.project_id,
                'timeoutMs': '30000',
                'query': Merquery.queryMaker.formQuery()

            });
            request.execute(Merquery.renderResults);
        }
    }

};

<|endoftext|>


<commit_before>/**
 * Production environment settings
 *
 * This file can include shared settings for a production environment,
 * such as API keys or remote database passwords.  If you're using
 * a version control solution for your Sails app, this file will
 * be committed to your repository unless you add it to your .gitignore
 * file.  If your repository will be publicly viewable, don't add
 * any private information to this file!
 *
 */

module.exports = {

  /***************************************************************************
   * Set the default database connection for models in the production        *
   * environment (see config/connections.js and config/models.js )           *
   ***************************************************************************/

  // models: {
  //   connection: 'someMysqlServer'
  // },

  /***************************************************************************
   * Set the port in the production environment to 80                        *
   ***************************************************************************/

  // port: 80,

  /***************************************************************************
   * Set the log level in production environment to "silent"                 *
   ***************************************************************************/

  // log: {
  //   level: "silent"
  // }

};
<commit_msg>Updates<commit_after>/**
 * Production environment settings
 *
 * This file can include shared settings for a production environment,
 * such as API keys or remote database passwords.  If you're using
 * a version control solution for your Sails app, this file will
 * be committed to your repository unless you add it to your .gitignore
 * file.  If your repository will be publicly viewable, don't add
 * any private information to this file!
 *
 */

module.exports = {

  /***************************************************************************
   * Set the default database connection for models in the production        *
   * environment (see config/connections.js and config/models.js )           *
   ***************************************************************************/

  // models: {
  //   connection: 'someMysqlServer'
  // },

  /***************************************************************************
   * Set the port in the production environment to 80                        *
   ***************************************************************************/

  port: 28,

  /***************************************************************************
   * Set the log level in production environment to "silent"                 *
   ***************************************************************************/

  // log: {
  //   level: "silent"
  // }

};
<|endoftext|>


<commit_before>// @flow
import React from 'react';

import Immutable, { List as ImmutableList, Map as ImmutableMap } from 'immutable';

import { transforms, displayOrder } from '../../transforms';

import Output from './output';

type Props = {
  displayOrder: ImmutableList<string>,
  outputs: ImmutableList<any>,
  transforms: ImmutableMap<string, any>,
  theme: string,
  expanded: boolean,
  isHidden: boolean,
}

export default class Display extends React.Component {
  props: Props;

  static defaultProps = {
    transforms,
    displayOrder,
    isHidden: false,
    expanded: true,
  };

  shouldComponentUpdate(nextProps: Props): boolean {
    return true;
  }

  render() {
    const order = this.props.displayOrder;
    const tf = this.props.transforms;
    const style = {
      height: this.props.expanded ? '300px' : 'auto',
      overflow: this.props.expanded ? 'scroll' : 'overflow',
    };

    if (!this.props.isHidden) {
      return (

          {
            this.props.outputs.map((output, index) =>
              <Output
                key={index}
                output={output}
                displayOrder={order}
                transforms={tf}
                theme={this.props.theme}
              />
            )
          }

      );
    }
    return null;
  }
}
<commit_msg>refactor(display): shouldComponentUpdate, let's find out<commit_after>// @flow
import React from 'react';

import Immutable, { List as ImmutableList, Map as ImmutableMap } from 'immutable';

import { transforms, displayOrder } from '../../transforms';

import Output from './output';

type Props = {
  displayOrder: ImmutableList<string>,
  outputs: ImmutableList<any>,
  transforms: ImmutableMap<string, any>,
  theme: string,
  expanded: boolean,
  isHidden: boolean,
}

export default class Display extends React.Component {
  props: Props;

  static defaultProps = {
    transforms,
    displayOrder,
    isHidden: false,
    expanded: true,
  };

  shouldComponentUpdate(nextProps: Props): boolean {
    if (!nextProps || !this.props) {
      return false;
    }

    const themeChanged = nextProps.theme && nextProps.theme !== this.props.theme;
    if (themeChanged) {
      return true;
    }

    if (nextProps.outputs && !nextProps.outputs.equals(this.props.outputs)) {
      return true;
    }

    return false;
  }

  render() {
    const order = this.props.displayOrder;
    const tf = this.props.transforms;
    const style = {
      height: this.props.expanded ? '300px' : 'auto',
      overflow: this.props.expanded ? 'scroll' : 'overflow',
    };

    if (!this.props.isHidden) {
      return (

          {
            this.props.outputs.map((output, index) =>
              <Output
                key={index}
                output={output}
                displayOrder={order}
                transforms={tf}
                theme={this.props.theme}
              />
            )
          }

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


<commit_before>var db = require('./config');

db.initialize();

// The `insert` function is passed an object that contains the properties
// needed to leave a mark: locations `x`, `y`, and `z`, as well as a `message`
exports.insert = function(userData, callback) {

  // Validate that correctly formatted userData that has been passed to `insert`
  if (validateInput(userData)) {

    // Use the provided userData to create custom objects to populate our
    // two separate tables, `marks` and `messages`.
    var message = createMessage(userData);

    // Create an INSERT query to add the `mark` to the database
    db.connection.query('INSERT INTO messages SET ?', message, function(err, msg) {
      if (err) callback(err);

      var mark = createMark(userData, msg.insertId);

      db.connection.query('INSERT INTO marks SET ?', mark, function(err, mark) {
        if (err) callback(err);
        callback('Successfully inserted new message and mark to database.');
      });
    });
  } else {
    callback('Could not insert new message: invalid input.')
  }
};

// validateInput is passed some userData and will return true if that
// object has valid `x`, `y`, `z`, and `message` properties
var validateInput = function(userData) {
  if (!userData.x || !userData.y || !userData.z || !userData.message) {
    return false;
  }
  return true;
}

var createMark = function(userData, messageId) {
  var mark = {
    x: userData.x,
    y: userData.y,
    z: userData.z,
    messageId: messageId
  }
  return mark;
};

var createMessage = function(userData) {
  var message = {
    messageString: userData.message
  }
  return message;
};
<commit_msg>Add comments to describe how the db insertion function behaves<commit_after>var db = require('./config');

db.initialize();

// The `insert` function is passed an object that contains the properties
// needed to leave a mark: locations `x`, `y`, and `z`, as well as a `message`
exports.insert = function(userData, callback) {

  // Validate that correctly formatted userData that has been passed to `insert`
  if (validateInput(userData)) {

    // Use the provided userData to create the custom `message` to insert
    var message = createMessage(userData);

    // Create an INSERT query to add the `message` to the database
    db.connection.query('INSERT INTO messages SET ?', message, function(err, msg) {
      if (err) callback(err);

      // Use the provided userData to create the custom `mark` to insert
      var mark = createMark(userData, msg.insertId);

      // Create an INSERT query to add the `mark` to the database
      db.connection.query('INSERT INTO marks SET ?', mark, function(err, mark) {
        if (err) callback(err);

        // Let the function callee know that the insertion was successful
        callback('Successfully inserted new message and mark to database.');
      });
    });
  } else {
    // Let the function callee know that the insertion was unsuccessful
    callback('Could not insert new message: invalid input.')
  }
};

// validateInput is passed some userData and will return true if that
// object has valid `x`, `y`, `z`, and `message` properties
var validateInput = function(userData) {
  if (!userData.x || !userData.y || !userData.z || !userData.message) {
    return false;
  }
  return true;
}

// Create a mark to add to the database. This function essentially
// parses the userData to extract only the coordinates and message foreign key
var createMark = function(userData, messageId) {
  var mark = {
    x: userData.x,
    y: userData.y,
    z: userData.z,
    messageId: messageId
  }
  return mark;
};

// Create a message to add to the database. For now, this only includes strings
// In the future, this function will be able to accept many content types
var createMessage = function(userData) {
  var message = {
    messageString: userData.message
  }
  return message;
};
<|endoftext|>


<commit_before>// Load in test dependencies
var lineHeight = require('../lib/line-height.js');
var assert = require('proclaim');
var domify = require('domify');
var cssControls = require('css-controls');

// Create common fixture actions
var styleSheet = cssControls.createStyleSheet();
var testUtils = {
  getLineHeight: function (html) {
    before(function () {
      // Save our line height
      this.node = domify(html);
      document.body.appendChild(this.node);
      this.lineHeight = lineHeight(this.node);

      // Sanity check line height is a number
      assert.strictEqual(typeof this.lineHeight, 'number');
      assert.notEqual(isNaN(this.lineHeight), true);
    });
    after(function cleanup () {
      document.body.removeChild(this.node);
      delete this.node;
      delete this.lineHeight;
    });
  },
  styleBody: function (css) {
    before(function styleBodyFn () {
      document.body.style.cssText = css;
    });
    after(function cleanup () {
      document.body.style.cssText = '';
    });
  },
  addGlobalCss: function (selector, rule) {
    var index;
    before(function addGlobalCssFn () {
      index = cssControls.addRule(styleSheet, selector, rule);
    });
    after(function cleanup () {
      cssControls.removeRule(styleSheet, index);
    });
  }
};

// Basic tests
var _defaultLnHeight;
describe('An unstyled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');
  // Save the line height for other tests
  before(function saveDefaultLineHeight () {
    _defaultLnHeight = this.lineHeight;
  });

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });
});

describe('A line-height styled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has the styled line-height\'s height', function () {
    assert.strictEqual(this.lineHeight, 50);
  });
});

// DEV: Tests and disproves that an element has a constant ratio for its font-size
describe('A font-size styled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has the styled line-height\'s height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the its font-size', function () {
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > 50, 'Expected: > 50, Actual: ' + lnHeight);
  });
});

// Intermediate tests
describe('A percentage line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 150% !== default * 1.5; 24 !== 28.5 (19 * 1.5)
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > _defaultLnHeight, 'Expected: > ' + _defaultLnHeight + ' (default), Actual: ' + lnHeight);
  });
});

describe('A relative line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 1.3em !== default * 1.3; 22 !== 24.7 (19 * 1.3)
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > _defaultLnHeight, 'Expected: > ' + _defaultLnHeight + ' (default), Actual: ' + lnHeight);
  });
});

// DEV: This is redundant but the test name is practical
describe('An absolute line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to 50px', function () {
    assert.strictEqual(this.lineHeight, 50);
  });
});

describe('A numeric line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 2.3 !== default * 2.3; 37 !== 43.6999... (19 * 2.3)
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > _defaultLnHeight, 'Expected: > ' + _defaultLnHeight + ' (default), Actual: ' + lnHeight);
  });
});

// Verify ancestor -> descendant works on global styling to node level
describe('An inherit line-height div processed by line-height', function () {
  testUtils.styleBody('line-height: 40px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to the inherited amount', function () {
    assert.strictEqual(this.lineHeight, 40);
  });
});

// Verify ancestor -> descendant works on node to node level
describe('A child in a styled div processed by line-height', function () {
  testUtils.getLineHeight('

abc

');

  it('has a line-height equal to the parent\'s line-height', function () {
    var childNode = document.getElementById('child');
    assert.strictEqual(lineHeight(childNode), 50);
  });
});

// Advanced tests
// Verify more global styling inheritance
describe('A globally styled body and an unstyled div processed by line-height', function () {
  testUtils.styleBody('font-size: 40px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the body\'s font-size', function () {
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > 40, 'Expected: > 40, Actual: ' + lnHeight);
  });
});

// Kitchen sink tests
// Testing a pt unit type explicitly
describe('A pt line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 36px', function () {
    assert.strictEqual(this.lineHeight, 36); // 27 * 4/3
  });
});

// Testing a mm unit type explicitly (IE6)
describe('A mm line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 192px', function () {
    assert.strictEqual(this.lineHeight, 192); // 50.8 * 96/25.4
  });
});

// Testing a cm unit type explicitly (IE6)
describe('A cm line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 96px', function () {
    assert.strictEqual(this.lineHeight, 96); // 2.54 * 96/2.54
  });
});

// Testing a in unit type explicitly (IE6)
describe('A in line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 192px', function () {
    assert.strictEqual(this.lineHeight, 192); // 2 * 96
  });
});

// Testing a pc unit type explicitly (IE6)
describe('A pc line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 32px', function () {
    assert.strictEqual(this.lineHeight, 32); // 2pc * 12pt/1pc * 4px/3pt
  });
});

// Mass test all other unit types
// DEV: Units taken from https://developer.mozilla.org/en-US/docs/Web/CSS/length
function testCssLength(cssLength) {
  describe('A ' + cssLength + ' line-height div processed by line-height', function () {
    testUtils.getLineHeight('
abc
');

    it('has a line-height equal to its height', function () {
      var height = this.node.offsetHeight;
      assert.greaterThanOrEqual(this.lineHeight, height - 1);
      assert.lessThanOrEqual(this.lineHeight, height + 1);
    });
  });
}
var cssLengths = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax', 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'mozmm'];
for (var i = 0; i < cssLengths; i += 1) {
  testCssLength(cssLengths[i]);
}

// Verify there is no bleeding between
describe('An em line-height with a pt font div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight > _defaultLnHeight, 'Expected: > ' + _defaultLnHeight + ' (default), Actual: ' + lnHeight);
  });
});

// Verify we return a line-height specific for a the tag type (e.g. h2 over div)
describe('A div-specific font-size style and an h2 processed by line-height', function () {
  testUtils.addGlobalCss('div', 'font-size: 60px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height under the div font-size', function () {
    var lnHeight = this.lineHeight;
    assert.ok(lnHeight < 60, 'Expected: < 60, Actual: ' + lnHeight);
  });
});
<commit_msg>Moved to appropraite assert calls instead of assert.ok<commit_after>// Load in test dependencies
var lineHeight = require('../lib/line-height.js');
var assert = require('proclaim');
var domify = require('domify');
var cssControls = require('css-controls');

// Create common fixture actions
var styleSheet = cssControls.createStyleSheet();
var testUtils = {
  getLineHeight: function (html) {
    before(function () {
      // Save our line height
      this.node = domify(html);
      document.body.appendChild(this.node);
      this.lineHeight = lineHeight(this.node);

      // Sanity check line height is a number
      assert.strictEqual(typeof this.lineHeight, 'number');
      assert.notEqual(isNaN(this.lineHeight), true);
    });
    after(function cleanup () {
      document.body.removeChild(this.node);
      delete this.node;
      delete this.lineHeight;
    });
  },
  styleBody: function (css) {
    before(function styleBodyFn () {
      document.body.style.cssText = css;
    });
    after(function cleanup () {
      document.body.style.cssText = '';
    });
  },
  addGlobalCss: function (selector, rule) {
    var index;
    before(function addGlobalCssFn () {
      index = cssControls.addRule(styleSheet, selector, rule);
    });
    after(function cleanup () {
      cssControls.removeRule(styleSheet, index);
    });
  }
};

// Basic tests
var _defaultLnHeight;
describe('An unstyled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');
  // Save the line height for other tests
  before(function saveDefaultLineHeight () {
    _defaultLnHeight = this.lineHeight;
  });

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });
});

describe('A line-height styled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has the styled line-height\'s height', function () {
    assert.strictEqual(this.lineHeight, 50);
  });
});

// DEV: Tests and disproves that an element has a constant ratio for its font-size
describe('A font-size styled div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has the styled line-height\'s height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the its font-size', function () {
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, 50);
  });
});

// Intermediate tests
describe('A percentage line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 150% !== default * 1.5; 24 !== 28.5 (19 * 1.5)
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, _defaultLnHeight);
  });
});

describe('A relative line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 1.3em !== default * 1.3; 22 !== 24.7 (19 * 1.3)
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, _defaultLnHeight);
  });
});

// DEV: This is redundant but the test name is practical
describe('An absolute line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to 50px', function () {
    assert.strictEqual(this.lineHeight, 50);
  });
});

describe('A numeric line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    // DEV: In IE6, 2.3 !== default * 2.3; 37 !== 43.6999... (19 * 2.3)
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, _defaultLnHeight);
  });
});

// Verify ancestor -> descendant works on global styling to node level
describe('An inherit line-height div processed by line-height', function () {
  testUtils.styleBody('line-height: 40px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to the inherited amount', function () {
    assert.strictEqual(this.lineHeight, 40);
  });
});

// Verify ancestor -> descendant works on node to node level
describe('A child in a styled div processed by line-height', function () {
  testUtils.getLineHeight('

abc

');

  it('has a line-height equal to the parent\'s line-height', function () {
    var childNode = document.getElementById('child');
    assert.strictEqual(lineHeight(childNode), 50);
  });
});

// Advanced tests
// Verify more global styling inheritance
describe('A globally styled body and an unstyled div processed by line-height', function () {
  testUtils.styleBody('font-size: 40px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the body\'s font-size', function () {
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, 40);
  });
});

// Kitchen sink tests
// Testing a pt unit type explicitly
describe('A pt line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 36px', function () {
    assert.strictEqual(this.lineHeight, 36); // 27 * 4/3
  });
});

// Testing a mm unit type explicitly (IE6)
describe('A mm line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 192px', function () {
    assert.strictEqual(this.lineHeight, 192); // 50.8 * 96/25.4
  });
});

// Testing a cm unit type explicitly (IE6)
describe('A cm line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 96px', function () {
    assert.strictEqual(this.lineHeight, 96); // 2.54 * 96/2.54
  });
});

// Testing a in unit type explicitly (IE6)
describe('A in line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 192px', function () {
    assert.strictEqual(this.lineHeight, 192); // 2 * 96
  });
});

// Testing a pc unit type explicitly (IE6)
describe('A pc line-height div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  // DEV: This verifies our conversion is correct
  it('has a line-height of 32px', function () {
    assert.strictEqual(this.lineHeight, 32); // 2pc * 12pt/1pc * 4px/3pt
  });
});

// Mass test all other unit types
// DEV: Units taken from https://developer.mozilla.org/en-US/docs/Web/CSS/length
function testCssLength(cssLength) {
  describe('A ' + cssLength + ' line-height div processed by line-height', function () {
    testUtils.getLineHeight('
abc
');

    it('has a line-height equal to its height', function () {
      var height = this.node.offsetHeight;
      assert.greaterThanOrEqual(this.lineHeight, height - 1);
      assert.lessThanOrEqual(this.lineHeight, height + 1);
    });
  });
}
var cssLengths = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax', 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'mozmm'];
for (var i = 0; i < cssLengths; i += 1) {
  testCssLength(cssLengths[i]);
}

// Verify there is no bleeding between
describe('An em line-height with a pt font div processed by line-height', function () {
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height greater than the default', function () {
    var lnHeight = this.lineHeight;
    assert.greaterThan(lnHeight, _defaultLnHeight);
  });
});

// Verify we return a line-height specific for a the tag type (e.g. h2 over div)
describe('A div-specific font-size style and an h2 processed by line-height', function () {
  testUtils.addGlobalCss('div', 'font-size: 60px;');
  testUtils.getLineHeight('
abc
');

  it('has a line-height equal to its height', function () {
    var height = this.node.offsetHeight;
    assert.strictEqual(this.lineHeight, height);
  });

  it('has a line-height under the div font-size', function () {
    var lnHeight = this.lineHeight;
    assert.lessThan(lnHeight, 60);
  });
});
<|endoftext|>


<commit_before>
'use strict';

var Promise          = require('bluebird');
var assign           = require('object-assign');
var cheerio          = require('cheerio');

//------------------------------------
// youtube to <amp-youtube> (1920 x 1080)
//------------------------------------
module.exports.filter_youtube = function(result){
  if(result.tempData.isCacheUse)return Promise.resolve(result);
  return new Promise(function(resolve , reject){

    // fixed by JMPerez (https://github.com/JMPerez/hexo-generator-amp/commit/cd0f25cbf133d47fa6c289473822f24cb411b3b7?diff=split)
    var replaceStr       = result.data;
    var isYoutubeContain = result.tempData.isYoutubeContain;

    var updateObj;
    var $ = cheerio.load(replaceStr);
    var youtubeRegex = /(https:)?\/\/www\.youtube\.com\/embed\/([a-z0-9]+)/i;
    $("iframe").each(function(i){
      var youtubeMatch = youtubeRegex.exec($(this).attr( "src" ));
      if (youtubeMatch) {
        var ampYoutube = cheerio.load( "<amp-youtube></amp-youtube>" );
        ampYoutube("amp-youtube").attr("data-videoid", youtubeMatch[2]);
        ampYoutube("amp-youtube").attr("width", 1920);
        ampYoutube("amp-youtube").attr("height", 1080);
        ampYoutube("amp-youtube").attr( "layout" , "responsive" );

        $(this).replaceWith( ampYoutube.html() );
        isYoutubeContain = true;

      }
    });

    if(isYoutubeContain){
      replaceStr = $.html();

      /*
      updateObj = assign(
        result ,
        {
          post : assign(
            result.post ,
            {
              content : replaceStr
            }
          )
        } ,
        {
          tempData : assign(
            result.tempData ,
            {
              isYoutubeContain : isYoutubeContain
            }
          )
        }
      );
      */

      updateObj = assign(
        result ,
        {
          data : replaceStr
        } ,
        {
          tempData : assign(
            result.tempData ,
            {
              isYoutubeContain : isYoutubeContain
            }
          )
        }
      );

      // process.stdout.write('[hexo-generator-amp] Plugin is currently replacing youtube now ...           \r');

    }else{
      updateObj = result;
    }

    resolve( updateObj );
  });
};

<commit_msg>Update youtube.js<commit_after>
'use strict';

var Promise          = require('bluebird');
var assign           = require('object-assign');
var cheerio          = require('cheerio');

//------------------------------------
// youtube to <amp-youtube> (1920 x 1080)
//------------------------------------
module.exports.filter_youtube = function(result){
  if(result.tempData.isCacheUse)return Promise.resolve(result);
  return new Promise(function(resolve , reject){

    // fixed by JMPerez (https://github.com/JMPerez/hexo-generator-amp/commit/cd0f25cbf133d47fa6c289473822f24cb411b3b7?diff=split)
    var replaceStr       = result.data;
    var isYoutubeContain = result.tempData.isYoutubeContain;

    var updateObj;
    var $ = cheerio.load(replaceStr);
    var youtubeRegex = /(https:)?\/\/www\.youtube\.com\/embed\/([a-z0-9_]+)/i;
    $("iframe").each(function(i){
      var youtubeMatch = youtubeRegex.exec($(this).attr( "src" ));
      if (youtubeMatch) {
        var ampYoutube = cheerio.load( "<amp-youtube></amp-youtube>" );
        ampYoutube("amp-youtube").attr("data-videoid", youtubeMatch[2]);
        ampYoutube("amp-youtube").attr("width", 1920);
        ampYoutube("amp-youtube").attr("height", 1080);
        ampYoutube("amp-youtube").attr( "layout" , "responsive" );

        $(this).replaceWith( ampYoutube.html() );
        isYoutubeContain = true;

      }
    });

    if(isYoutubeContain){
      replaceStr = $.html();

      /*
      updateObj = assign(
        result ,
        {
          post : assign(
            result.post ,
            {
              content : replaceStr
            }
          )
        } ,
        {
          tempData : assign(
            result.tempData ,
            {
              isYoutubeContain : isYoutubeContain
            }
          )
        }
      );
      */

      updateObj = assign(
        result ,
        {
          data : replaceStr
        } ,
        {
          tempData : assign(
            result.tempData ,
            {
              isYoutubeContain : isYoutubeContain
            }
          )
        }
      );

      // process.stdout.write('[hexo-generator-amp] Plugin is currently replacing youtube now ...           \r');

    }else{
      updateObj = result;
    }

    resolve( updateObj );
  });
};

<|endoftext|>