<commit_before>Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import('resource://greasemonkey/util.js');

const Cc = Components.classes;
const Ci = Components.interfaces;
const schemeName = 'greasemonkey-script';
const ioService = Cc['@mozilla.org/network/io-service;1']
    .getService(Ci.nsIIOService);

function ScriptChannel(aUri, aScript) {
  // nsIRequest
  this.loadFlags = 0;
  this.loadGroup = null;
  this.name = aUri.spec;
  this.status = 200;

  this.content = '';
  if (aScript) {
    this.content = GM_util.getScriptSource(aScript);
  } else {
    this.status = 404;
  }

  if (aUri.spec.match(/\?.*wrapped=1/)) {
    this.content = GM_util.anonWrap(this.content);
  }

  // nsIChannel
  this.contentCharset = 'utf-8';
  this.contentLength = this.content.length;
  this.contentType = 'application/javascript';
  this.notificationCallbacks = null;
  this.originalURI = aUri;
  this.owner = null;
  this.securityInfo = null;
  this.URI = aUri;

  this.pipe = Cc['@mozilla.org/pipe;1'].createInstance(Ci.nsIPipe);
  this.pipe.init(true, true, 0, 0, null);

  var inputStreamChannel = Cc['@mozilla.org/network/input-stream-channel;1']
      .createInstance(Ci.nsIInputStreamChannel);
  inputStreamChannel.setURI(aUri);
  inputStreamChannel.contentStream = this.pipe.inputStream;
  this.channel = inputStreamChannel.QueryInterface(Ci.nsIChannel);
}

// nsIChannel
ScriptChannel.prototype.asyncOpen = function(aListener, aContext) {
  this.channel.asyncOpen(aListener, aContext);
  this.pipe.outputStream.write(this.content, this.content.length);
  this.pipe.outputStream.close();
};

function ScriptProtocol() {}

// XPCOMUtils generation
ScriptProtocol.prototype.classDescription =
    'Protocol handler for greasemonkey-script:';
ScriptProtocol.prototype.classID =
    Components.ID('{20d898f3-2fb8-4b3a-b8c7-7ad6c2c48598}');
ScriptProtocol.prototype.contractID =
    '@mozilla.org/network/protocol;1?name=' + schemeName;
ScriptProtocol.prototype.QueryInterface = XPCOMUtils.generateQI([
    Components.interfaces.nsIProtocolHandler,
    Components.interfaces.nsISupports,
    ]);

// nsIProtocolHandler
ScriptProtocol.prototype.scheme = schemeName;
ScriptProtocol.prototype.defaultPort = -1;
ScriptProtocol.prototype.protocolFlags = 0
    | Ci.nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT
    | Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE
    | Ci.nsIProtocolHandler.URI_LOADABLE_BY_ANYONE
    | Ci.nsIProtocolHandler.URI_NOAUTH
    | Ci.nsIProtocolHandler.URI_NON_PERSISTABLE
    | Ci.nsIProtocolHandler.URI_NORELATIVE
    ;

// nsIProtocolHandler
ScriptProtocol.prototype.allowPort = function(aPort, aScheme) {
  return false;
};

// nsIProtocolHandler
ScriptProtocol.prototype.newURI = function(aSpec, aCharset, aBaseUri) {
  var uri = Cc['@mozilla.org/network/simple-uri;1'].createInstance(Ci.nsIURI);
  uri.spec = aSpec;
  return uri;
};

// nsIProtocolHandler
ScriptProtocol.prototype.newChannel = function(aUri) {
  var m = aUri.spec.match(/greasemonkey-script:([-0-9a-f]+)\/(.*)/);
  var script = GM_util.getService().config.getMatchingScripts(function(script) {
    return script.uuid == m[1];
  })[0];
  if (aUri.spec.match(/\.user\.js($|\?)/)) {
    return new ScriptChannel(aUri, script);
  } else if (script) {
    for (var i = 0, resource = null; resource = script.resources[i]; i++) {
      if (resource.name == m[2]) {
        return ioService.newChannelFromURI(
            GM_util.getUriFromFile(resource.file));
      }
    }
  } else {
    return new ScriptChannel(aUri, script);
  }
};

const components = [ScriptProtocol];
if ("generateNSGetFactory" in XPCOMUtils) {
  var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // Gecko 2.0+
} else {
  var NSGetModule = XPCOMUtils.generateNSGetModule(components); // Gecko 1.9.x
}
<commit_msg>Fix crashes with a nonexistent greasemonkey-script: URL.<commit_after>Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import('resource://greasemonkey/util.js');

const Cc = Components.classes;
const Ci = Components.interfaces;
const schemeName = 'greasemonkey-script';
const ioService = Cc['@mozilla.org/network/io-service;1']
    .getService(Ci.nsIIOService);

function ScriptChannel(aUri, aScript) {
  // nsIRequest
  this.loadFlags = 0;
  this.loadGroup = null;
  this.name = aUri.spec;
  this.status = 200;

  this.content = '';
  if (aScript) {
    this.content = GM_util.getScriptSource(aScript);
  } else {
    this.status = 404;
  }

  if (aUri.spec.match(/\?.*wrapped=1/)) {
    this.content = GM_util.anonWrap(this.content);
  }

  // nsIChannel
  this.contentCharset = 'utf-8';
  this.contentLength = this.content.length;
  this.contentType = 'application/javascript';
  this.notificationCallbacks = null;
  this.originalURI = aUri;
  this.owner = null;
  this.securityInfo = null;
  this.URI = aUri;

  this.pipe = Cc['@mozilla.org/pipe;1'].createInstance(Ci.nsIPipe);
  this.pipe.init(true, true, 0, 0, null);

  var inputStreamChannel = Cc['@mozilla.org/network/input-stream-channel;1']
      .createInstance(Ci.nsIInputStreamChannel);
  inputStreamChannel.setURI(aUri);
  inputStreamChannel.contentStream = this.pipe.inputStream;
  this.channel = inputStreamChannel.QueryInterface(Ci.nsIChannel);
}

// nsIChannel
ScriptChannel.prototype.asyncOpen = function(aListener, aContext) {
  this.channel.asyncOpen(aListener, aContext);
  this.pipe.outputStream.write(this.content, this.content.length);
  this.pipe.outputStream.close();
};

function ScriptProtocol() {}

// XPCOMUtils generation
ScriptProtocol.prototype.classDescription =
    'Protocol handler for greasemonkey-script:';
ScriptProtocol.prototype.classID =
    Components.ID('{20d898f3-2fb8-4b3a-b8c7-7ad6c2c48598}');
ScriptProtocol.prototype.contractID =
    '@mozilla.org/network/protocol;1?name=' + schemeName;
ScriptProtocol.prototype.QueryInterface = XPCOMUtils.generateQI([
    Components.interfaces.nsIProtocolHandler,
    Components.interfaces.nsISupports,
    ]);

// nsIProtocolHandler
ScriptProtocol.prototype.scheme = schemeName;
ScriptProtocol.prototype.defaultPort = -1;
ScriptProtocol.prototype.protocolFlags = 0
    | Ci.nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT
    | Ci.nsIProtocolHandler.URI_IS_LOCAL_RESOURCE
    | Ci.nsIProtocolHandler.URI_LOADABLE_BY_ANYONE
    | Ci.nsIProtocolHandler.URI_NOAUTH
    | Ci.nsIProtocolHandler.URI_NON_PERSISTABLE
    | Ci.nsIProtocolHandler.URI_NORELATIVE
    ;

// nsIProtocolHandler
ScriptProtocol.prototype.allowPort = function(aPort, aScheme) {
  return false;
};

// nsIProtocolHandler
ScriptProtocol.prototype.newURI = function(aSpec, aCharset, aBaseUri) {
  var uri = Cc['@mozilla.org/network/simple-uri;1'].createInstance(Ci.nsIURI);
  uri.spec = aSpec;
  return uri;
};

// nsIProtocolHandler
ScriptProtocol.prototype.newChannel = function(aUri) {
  var m = aUri.spec.match(/greasemonkey-script:([-0-9a-f]+)\/(.*)/);
  var script = GM_util.getService().config.getMatchingScripts(function(script) {
    return script.uuid == m[1];
  })[0];
  if (aUri.spec.match(/\.user\.js($|\?)/)) {
    return new ScriptChannel(aUri, script);
  } else if (script) {
    for (var i = 0, resource = null; resource = script.resources[i]; i++) {
      if (resource.name == m[2]) {
        return ioService.newChannelFromURI(
            GM_util.getUriFromFile(resource.file));
      }
    }
  } else {
    return new ScriptChannel(aUri, script);
  }

  // Default fall-through case, send a 404.  (By using a script channel
  // w/out any script object.)(
  return new ScriptChannel(aUri);
};

const components = [ScriptProtocol];
if ("generateNSGetFactory" in XPCOMUtils) {
  var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // Gecko 2.0+
} else {
  var NSGetModule = XPCOMUtils.generateNSGetModule(components); // Gecko 1.9.x
}
<|endoftext|>


<commit_before>/*
 eslint-disable no-param-reassign, no-underscore-dangle
*/

import { Router } from 'express';
import { ObjectId } from 'mongodb';
import expressJwt from 'express-jwt';
import { SUCCESS, UNAUTHORIZED, SERVER_FAILED } from 'nagu-validates';
import { secret, mongoUrl } from '../config';
import { getToken, isMockVersion } from '../utils';

const CeeInfoManager = require('../models/cee').default;

const cim = new CeeInfoManager(mongoUrl);
const router = new Router();

router.put('/',
    // 返回mock数据
    (req, res, next) => {
      if (isMockVersion(req)) {
        res.json({
          ret: SUCCESS,
          data: {
            _id: '592e61700000000000000000',
          },
        });
      } else next();
    },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以添加数据
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const _id = await cim.insert(req.body);
    res.json({
      ret: SUCCESS,
      data: { _id },
    });
  }
);

router.get('/list/:pageIndex',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      const list = [{
        name: '张三',
        fromSchool: '通海一中',
        toSchool: '玉溪一中',
        parentName: '张二',
        homeAddress: '纳古纳家营二组',
        phone: '18909879987',
        examTypeText: '中考',
        point: 536,
      }];
      res.json({
        ret: SUCCESS,
        data: {
          list,
          totalCount: list.length,
        },
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  (req, res, next) => {
    req.pageIndex = parseInt(req.params.pageIndex, 10);
    req.pageSize = parseInt(req.query.pageSize || 200, 10);
    if (isNaN(req.pageIndex) || isNaN(req.pageSize)) throw new Error('pageIndex or pageSize is wrong.');
    next();
  },
  async (req, res) => {
    const list = await cim.list({
      pageSize: req.pageSize,
      pageIndex: req.pageIndex,
    });
    const totalCount = await cim.count();
    res.json({
      ret: SUCCESS,
      data: {
        list,
        totalCount,
      },
    });
  }
);

// 根据用户信息获取录取信息
router.get('/app/:appId/user/:userId',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      const data = {
        _id: '592e61700000000000000000',
        name: '张三',
        fromSchool: '通海一中',
        toSchool: '玉溪一中',
        parentName: '张二',
        homeAddress: '纳古纳家营二组',
        phone: '18909879987',
        examTypeText: '中考',
        point: 536,
        user: {
          [req.params.appId]: req.params.userId,
        },
      };
      res.json({
        ret: SUCCESS,
        data,
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { appId, userId } = req.params;
    const data = await cim.findByUser(appId, userId);
    res.json({
      ret: SUCCESS,
      data,
    });
  }
);

// 删除指定Id的数据
router.delete('/:iId',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      res.json({
        ret: SUCCESS,
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { id } = req.params;
    try {
      const _id = new ObjectId(id);
      await cim.removeById(_id);
      res.json({
        ret: SUCCESS,
      });
    } catch (e) {
      res.status(500).json({
        ret: SERVER_FAILED,
        msg: e.message,
      });
    }
  }
);

router.post('/:id',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      res.json({
        ret: SUCCESS,
        data: {
          _id: '592e61700000000000000000',
        },
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { id } = req.params;
    try {
      const _id = new ObjectId(id);
      await cim.updateyId({
        ...req.body,
        _id,
      });
      res.json({
        ret: SUCCESS,
        data: {
          _id,
        },
      });
    } catch (e) {
      res.status(500).json({
        ret: SERVER_FAILED,
        msg: e.message,
      });
    }
  }
);
export default router;
<commit_msg>update<commit_after>/*
 eslint-disable no-param-reassign, no-underscore-dangle
*/

import { Router } from 'express';
import { ObjectId } from 'mongodb';
import expressJwt from 'express-jwt';
import { SUCCESS, UNAUTHORIZED, SERVER_FAILED } from 'nagu-validates';
import { secret, mongoUrl } from '../config';
import { getToken, isMockVersion } from '../utils';

const CeeInfoManager = require('../models/cee').default;

const cim = new CeeInfoManager(mongoUrl);
const router = new Router();

router.put('/',
    // 返回mock数据
    (req, res, next) => {
      if (isMockVersion(req)) {
        res.json({
          ret: SUCCESS,
          data: {
            _id: '592e61700000000000000000',
          },
        });
      } else next();
    },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以添加数据
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const _id = await cim.insert(req.body);
    res.json({
      ret: SUCCESS,
      data: { _id },
    });
  }
);

router.get('/list/:pageIndex',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      const list = [{
        name: '张三',
        fromSchool: '通海一中',
        toSchool: '玉溪一中',
        parentName: '张二',
        homeAddress: '纳古纳家营二组',
        phone: '18909879987',
        examTypeText: '中考',
        point: 536,
      }];
      res.json({
        ret: SUCCESS,
        data: {
          list,
          totalCount: list.length,
        },
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  (req, res, next) => {
    req.pageIndex = parseInt(req.params.pageIndex, 10);
    req.pageSize = parseInt(req.query.pageSize || 200, 10);
    if (isNaN(req.pageIndex) || isNaN(req.pageSize)) throw new Error('pageIndex or pageSize is wrong.');
    next();
  },
  async (req, res) => {
    const list = await cim.list({
      pageSize: req.pageSize,
      pageIndex: req.pageIndex,
    });
    const totalCount = await cim.count();
    res.json({
      ret: SUCCESS,
      data: {
        list,
        totalCount,
      },
    });
  }
);

// 根据用户信息获取录取信息
router.get('/app/:appId/user/:userId',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      const data = {
        _id: '592e61700000000000000000',
        name: '张三',
        fromSchool: '通海一中',
        toSchool: '玉溪一中',
        parentName: '张二',
        homeAddress: '纳古纳家营二组',
        phone: '18909879987',
        examTypeText: '中考',
        examType: 4,
        point: 536,
        user: {
          [req.params.appId]: req.params.userId,
        },
      };
      res.json({
        ret: SUCCESS,
        data,
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { appId, userId } = req.params;
    const data = await cim.findByUser(appId, userId);
    res.json({
      ret: SUCCESS,
      data,
    });
  }
);

// 删除指定Id的数据
router.delete('/:iId',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      res.json({
        ret: SUCCESS,
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { id } = req.params;
    try {
      const _id = new ObjectId(id);
      await cim.removeById(_id);
      res.json({
        ret: SUCCESS,
      });
    } catch (e) {
      res.status(500).json({
        ret: SERVER_FAILED,
        msg: e.message,
      });
    }
  }
);

router.post('/:id',
  // 返回mock数据
  (req, res, next) => {
    if (isMockVersion(req)) {
      res.json({
        ret: SUCCESS,
        data: {
          _id: '592e61700000000000000000',
        },
      });
    } else next();
  },
  // 确保用户已登录
  expressJwt({
    secret,
    credentialsRequired: true,
    getToken,
  }),
  // 判断是否是Manager，只有这种角色可以读取列表
  (req, res, next) => {
    if (req.user.isManager) next();
    else res.send({ ret: UNAUTHORIZED, msg: 'only manager can go next.' });
  },
  async (req, res) => {
    const { id } = req.params;
    try {
      const _id = new ObjectId(id);
      await cim.updateyId({
        ...req.body,
        _id,
      });
      res.json({
        ret: SUCCESS,
        data: {
          _id,
        },
      });
    } catch (e) {
      res.status(500).json({
        ret: SERVER_FAILED,
        msg: e.message,
      });
    }
  }
);
export default router;
<|endoftext|>


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

const resolve = (dir) => {
  return path.join(__dirname, '..', dir)
};

const isProduction = process.env.NODE_ENV === 'production';

const config = {
  output: {
    path: path.join(__dirname, '..', 'dist'),
    filename: '[name].[hash].js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '~': resolve('src'),
      'vue$': 'vue/dist/vue.runtime.esm.js',
      'vuex$': 'vuex/dist/vuex.esm.js',
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          resolve('src'),
          resolve('node_modules/@material'),
        ],
        use: ['babel-loader'],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          extractCSS: isProduction,
          postcss: [
            require('autoprefixer')({
              browsers: ['IE 9', 'IE 10', 'IE 11', 'last 2 versions'],
            }),
          ],
        },
      },
    ],
  },
};

module.exports = config;
<commit_msg>hashからchunkhashに変更<commit_after>const path = require('path');

const resolve = (dir) => {
  return path.join(__dirname, '..', dir)
};

const isProduction = process.env.NODE_ENV === 'production';

const config = {
  output: {
    path: path.join(__dirname, '..', 'dist'),
    filename: '[name].[chunkhash].js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '~': resolve('src'),
      'vue$': 'vue/dist/vue.runtime.esm.js',
      'vuex$': 'vuex/dist/vuex.esm.js',
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          resolve('src'),
          resolve('node_modules/@material'),
        ],
        use: ['babel-loader'],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          extractCSS: isProduction,
          postcss: [
            require('autoprefixer')({
              browsers: ['IE 9', 'IE 10', 'IE 11', 'last 2 versions'],
            }),
          ],
        },
      },
    ],
  },
};

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

define(['ol', 'toolbar', 'layermanager', 'geojson', 'pois', 'olus', 'stations', 'character', 'sidebar', 'query', 'print', 'permalink', 'measure', 'geolocation', 'api', 'cesium', 'ows', 'cesiumjs', 'bootstrap'],

    function (ol, toolbar, layermanager, geojson, pois, olus, stations, character) {
        var module = angular.module('hs', [
            'hs.layermanager',
            'hs.query',
            'hs.print', 'hs.permalink',
            'hs.geolocation',
            'hs.cesium',
            'hs.sidebar'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', '$timeout', function (OlMap, Core, $compile, $timeout) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function (scope, element) {
                    angular.element('.page-content', element).append($compile('

')(scope));
                    $timeout(function () { Core.fullScreenMap(element) }, 0);
                }
            };
        }]);

        module.directive('hs.enddialog', function () {
            function link(scope, element, attrs) {
                setTimeout(function () {
                    $('#end-dialog').modal('show');
                }, 1500);
            }
            return {
                templateUrl: './end.html?bust=' + gitsha,
                link: link
            };
        });

        module.directive('hs.hud', function () {
            return {
                templateUrl: './hud.html?bust=' + gitsha,
                link: function (scope, element, attrs) {

                }
            };
        })

        module.directive('hs.foodiezones.infoDirective', function () {
            return {
                templateUrl: './info.html?bust=' + gitsha,
                link: function (scope, element, attrs) {
                    $('#zone-info-dialog').modal('show');
                }
            };
        })

        module.directive('description', ['$compile', 'hs.utils.service', function ($compile, utils) {
            return {
                templateUrl: './description.html?bust=' + gitsha,
                scope: {
                    object: '=',
                    url: '@'
                },
                link: function (scope, element, attrs) {
                    scope.describe = function (e, attribute) {
                        if (angular.element(e.target).parent().find('table').length > 0) {
                            angular.element(e.target).parent().find('table').remove();
                        } else {
                            var table = angular.element('

');
                            angular.element(e.target).parent().append(table);
                            $compile(table)(scope.$parent);
                        }
                    }
                    if (angular.isUndefined(scope.object) && angular.isDefined(attrs.url) && typeof attrs.url == 'string') {
                        scope.object = { attributes: [] };
                        var q = 'https://www.foodie-cloud.org/sparql?default-graph-uri=&query=' + encodeURIComponent('describe <' + attrs.url + '>') + '&should-sponge=&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on';
                        $.ajax({
                            url: utils.proxify(q)
                        })
                            .done(function (response) {
                                if (angular.isUndefined(response.results)) return;
                                for (var i = 0; i < response.results.bindings.length; i++) {
                                    var b = response.results.bindings[i];
                                    var short_name = b.p.value;
                                    if (short_name.indexOf('#') > -1)
                                        short_name = short_name.split('#')[1];
                                    scope.object.attributes.push({ short_name: short_name, value: b.o.value });
                                    if (!scope.$$phase) scope.$apply();
                                }
                            })
                    }
                }
            };
        }]);

        module.value('config', {
            terrain_provider: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
            terrain_providers: [{
                title: 'EU-DEM',
                url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
                active: true
            }],
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "OpenStreetMap",
                    base: true,
                    visible: false,
                    minimumTerrainLevel: 15
                }),
                //pois.createPoiLayer(),
                olus.createOluLayer(),
                stations.createLayer()
            ],
            default_view: new ol.View({
                center: ol.proj.transform([1208534.8815206578, 5761821.705531779], 'EPSG:3857', 'EPSG:4326'),
                zoom: 16,
                units: "m",
                projection: 'EPSG:4326'
            })
        });

        module.controller('Main', ['$scope', '$compile', '$element', 'Core', 'hs.map.service', 'config', '$rootScope', 'hs.utils.service', '$sce', '$timeout',
            function ($scope, $compile, $element, Core, hs_map, config, $rootScope, utils, $sce, $timeout) {
                var map;
                var viewer;
                var last_time = 0;
                var last_hud_updated = 0;
                var zero_date = new Date(2000, 1, 0, 0, 0, 0, 0, 1);
                var full_date = new Date(2000, 1, 0, 4, 30, 0, 0);
                var running_start_date = new Date(2000, 1, 0, 4, 0, 0, 0);
                var time_game_started;
                var last_measure_pick;

                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;
                Core.singleDatasources = true;
                Core.panelEnabled('compositions', false);
                Core.panelEnabled('status_creator', false);
                Core.panelEnabled('print', false);
                $scope.Core.setDefaultPanel('layermanager');
                Core.sidebarExpanded = false;
                $scope.time_remaining = new Date(2000, 1, 0, 4, 30, 0, 0);
                $scope.points_collected = 0;
                pois.init($scope, $compile);
                stations.init($scope, $compile, olus);
                $scope.game_state = 'before_game';
                $scope.time_penalty = 0;
                $scope.ajax_loader = hsl_path + 'img/ajax-loader.gif';

                function createHud() {
                    var el = angular.element('

');
                    $(".page-content").append(el);
                    $compile(el)($scope);
                }

                function disableRightMouse(scene) {
                    var screenSpaceEventHandler = viewer.screenSpaceEventHandler;
                    screenSpaceEventHandler.setInputAction(function () {
                        scene.screenSpaceCameraController.enableZoom = false;
                    }, Cesium.ScreenSpaceEventType.RIGHT_DOWN);

                    screenSpaceEventHandler.setInputAction(function () {
                        scene.screenSpaceCameraController.enableZoom = true;
                    }, Cesium.ScreenSpaceEventType.RIGHT_UP);
                }

                function tick(timestamp) {
                    if (timestamp) {
                        var time_ellapsed = timestamp - last_time;
                        if ($scope.game_started) {
                            $scope.time_remaining = full_date - (timestamp - time_game_started) * 10;
                            if ($scope.time_remaining <= running_start_date && $scope.game_state == 'planning') {
                                $scope.game_state = 'running';
                                character.flyToInitialLocation();
                                playGo();
                            }
                            if ($scope.time_remaining <= zero_date) {
                                $scope.time_remaining = zero_date;
                                $scope.time_penalty = Math.ceil((zero_date - (full_date - (timestamp - time_game_started) * 10)) / 60000);
                            }
                        }

                        character.positionCharacter(time_ellapsed, timestamp);
                        updHud();
                        last_time = timestamp;
                    }
                    Cesium.requestAnimationFrame(tick);
                }

                function updHud() {
                    if (last_time - last_hud_updated < 500) return;
                    last_hud_updated = last_time;
                    if (!$scope.$$phase) $scope.$apply();
                }

                createHud();

                $scope.createNewMap = function (hours) {
                    $scope.game_started = true;
                    $scope.game_state = 'generating';
                    if (!$scope.$$phase) $scope.$apply();
                    $timeout(function(){
                        $scope.points_collected = 0;
                        full_date = new Date(2000, 1, 0, hours, 30, 0, 0);
                        running_start_date = new Date(2000, 1, 0, hours, 0, 0, 0);
                        time_game_started = last_time;
                        stations.createStations(map, utils, character.currentPos(), function () {
                            $scope.game_state = 'planning';
                            last_measure_pick = character.currentPos();
                            flyToWholeMapView();
                        }, hours);
                    }, 0)
                }

                function flyToWholeMapView() {
                    var pos_lon_lat = character.currentPos();
                    viewer.camera.flyTo({
                        destination: Cesium.Cartesian3.fromDegrees(pos_lon_lat[0] + stations.getMapWidth() / 0.016 * 0.0001 * 14, pos_lon_lat[1] - stations.getMapWidth() / 0.016 * 0.0006 * 14, pos_lon_lat[2] + stations.getMapWidth() / 0.016 * 60 * 18),
                        orientation: {
                            heading: Cesium.Math.toRadians(0.0),
                            pitch: Cesium.Math.toRadians(-45.0),
                            roll: 0.0
                        }
                    })
                }

                $rootScope.$on('cesium_position_clicked', function (event, lon_lat) {
                    console.log('click');
                    if (last_measure_pick == null)
                        last_measure_pick = character.currentPos();
                    if ($scope.game_state == 'running') {
                        character.changeTargetPosition(lon_lat, last_time);
                    }
                    if ($scope.game_state == 'planning') {
                        addMeasurementPosition(lon_lat);
                    }
                });

                $scope.total_distance = 0;
                var planning_line_segments = [];
                function addMeasurementPosition(lon_lat) {
                    var distance = Cesium.Cartesian3.distance(Cesium.Cartesian3.fromDegrees(last_measure_pick[0], last_measure_pick[1]), Cesium.Cartesian3.fromDegrees(lon_lat[0], lon_lat[1]));
                    $scope.total_distance += distance;
                    var rectangleInstance = new Cesium.GeometryInstance({
                        geometry: new Cesium.CorridorGeometry({
                            positions: Cesium.Cartesian3.fromDegreesArray([last_measure_pick[0], last_measure_pick[1], lon_lat[0], lon_lat[1]]),
                            width: 5
                        }),
                        attributes: {
                            color: new Cesium.ColorGeometryInstanceAttribute(0.9, .2, .2, 0.8)
                        }
                    });
                    var line = viewer.scene.primitives.add(new Cesium.GroundPrimitive({
                        geometryInstances: rectangleInstance
                    }));
                    line.distance = distance;
                    planning_line_segments.push(line);
                    last_measure_pick = lon_lat;
                }

                function playGo() {
                    var audio = new Audio('go.mp3');
                    audio.play();
                }

                $rootScope.$on('map.loaded', function () {
                    map = hs_map.map;
                });

                $rootScope.$on('cesiummap.loaded', function (event, _viewer) {
                    viewer = _viewer;
                    var scene = viewer.scene;
                    scene.globe.depthTestAgainstTerrain = true;
                    disableRightMouse(scene);
                    character.currentPos([hs_map.map.getView().getCenter()[0], hs_map.map.getView().getCenter()[1], 0]);
                    character.init($scope, $compile, olus, viewer, stations);
                    olus.init($scope, $compile, map, utils, _viewer, character);
                    tick();
                });

                $rootScope.$on('map.sync_center', function (e, center, bounds) {
                    if($scope.game_state == 'before_game')
                        character.currentPos(center);
                })

                $scope.$on('infopanel.updated', function (event) { });

                $scope.donePlanning = function () {
                    $scope.game_started = true;
                    $scope.game_state = 'running';
                    time_game_started = last_time;
                    full_date = running_start_date;
                    playGo();
                    character.flyToInitialLocation();
                }

                $scope.endGame = function(){
                    var el = angular.element('

');
                    $("#hs-dialog-area").append(el);
                    $compile(el)($scope);
                    $scope.game_started = false;
                    var audio = new Audio('fanfare.mp3');
                    audio.play();
                }
            }
        ]);

        return module;
    });
<commit_msg>the same<commit_after>'use strict';

define(['ol', 'toolbar', 'layermanager', 'geojson', 'pois', 'olus', 'stations', 'character', 'sidebar', 'query', 'print', 'permalink', 'measure', 'geolocation', 'api', 'cesium', 'ows', 'cesiumjs', 'bootstrap'],

    function (ol, toolbar, layermanager, geojson, pois, olus, stations, character) {
        var module = angular.module('hs', [
            'hs.layermanager',
            'hs.query',
            'hs.print', 'hs.permalink',
            'hs.geolocation',
            'hs.cesium',
            'hs.sidebar'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', '$timeout', function (OlMap, Core, $compile, $timeout) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function (scope, element) {
                    angular.element('.page-content', element).append($compile('

')(scope));
                    $timeout(function () { Core.fullScreenMap(element) }, 0);
                }
            };
        }]);

        module.directive('hs.enddialog', function () {
            function link(scope, element, attrs) {
                setTimeout(function () {
                    $('#end-dialog').modal('show');
                }, 1500);
            }
            return {
                templateUrl: './end.html?bust=' + gitsha,
                link: link
            };
        });

        module.directive('hs.hud', function () {
            return {
                templateUrl: './hud.html?bust=' + gitsha,
                link: function (scope, element, attrs) {

                }
            };
        })

        module.directive('hs.foodiezones.infoDirective', function () {
            return {
                templateUrl: './info.html?bust=' + gitsha,
                link: function (scope, element, attrs) {
                    $('#zone-info-dialog').modal('show');
                }
            };
        })

        module.directive('description', ['$compile', 'hs.utils.service', function ($compile, utils) {
            return {
                templateUrl: './description.html?bust=' + gitsha,
                scope: {
                    object: '=',
                    url: '@'
                },
                link: function (scope, element, attrs) {
                    scope.describe = function (e, attribute) {
                        if (angular.element(e.target).parent().find('table').length > 0) {
                            angular.element(e.target).parent().find('table').remove();
                        } else {
                            var table = angular.element('

');
                            angular.element(e.target).parent().append(table);
                            $compile(table)(scope.$parent);
                        }
                    }
                    if (angular.isUndefined(scope.object) && angular.isDefined(attrs.url) && typeof attrs.url == 'string') {
                        scope.object = { attributes: [] };
                        var q = 'https://www.foodie-cloud.org/sparql?default-graph-uri=&query=' + encodeURIComponent('describe <' + attrs.url + '>') + '&should-sponge=&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on';
                        $.ajax({
                            url: utils.proxify(q)
                        })
                            .done(function (response) {
                                if (angular.isUndefined(response.results)) return;
                                for (var i = 0; i < response.results.bindings.length; i++) {
                                    var b = response.results.bindings[i];
                                    var short_name = b.p.value;
                                    if (short_name.indexOf('#') > -1)
                                        short_name = short_name.split('#')[1];
                                    scope.object.attributes.push({ short_name: short_name, value: b.o.value });
                                    if (!scope.$$phase) scope.$apply();
                                }
                            })
                    }
                }
            };
        }]);

        module.value('config', {
            terrain_provider: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
            terrain_providers: [{
                title: 'EU-DEM',
                url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
                active: true
            }],
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "OpenStreetMap",
                    base: true,
                    visible: false,
                    minimumTerrainLevel: 15
                }),
                //pois.createPoiLayer(),
                olus.createOluLayer(),
                stations.createLayer()
            ],
            default_view: new ol.View({
                center: ol.proj.transform([1208534.8815206578, 5761821.705531779], 'EPSG:3857', 'EPSG:4326'),
                zoom: 16,
                units: "m",
                projection: 'EPSG:4326'
            })
        });

        module.controller('Main', ['$scope', '$compile', '$element', 'Core', 'hs.map.service', 'config', '$rootScope', 'hs.utils.service', '$sce', '$timeout',
            function ($scope, $compile, $element, Core, hs_map, config, $rootScope, utils, $sce, $timeout) {
                var map;
                var viewer;
                var last_time = 0;
                var last_hud_updated = 0;
                var zero_date = new Date(2000, 1, 0, 0, 0, 0, 0, 1);
                var full_date = new Date(2000, 1, 0, 4, 30, 0, 0);
                var running_start_date = new Date(2000, 1, 0, 4, 0, 0, 0);
                var time_game_started;
                var last_measure_pick;

                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;
                Core.singleDatasources = true;
                Core.panelEnabled('compositions', false);
                Core.panelEnabled('status_creator', false);
                Core.panelEnabled('print', false);
                $scope.Core.setDefaultPanel('layermanager');
                Core.sidebarExpanded = false;
                $scope.time_remaining = new Date(2000, 1, 0, 4, 30, 0, 0);
                $scope.points_collected = 0;
                pois.init($scope, $compile);
                stations.init($scope, $compile, olus);
                $scope.game_state = 'before_game';
                $scope.time_penalty = 0;
                $scope.ajax_loader = hsl_path + 'img/ajax-loader.gif';

                function createHud() {
                    var el = angular.element('

');
                    $(".page-content").append(el);
                    $compile(el)($scope);
                }

                function disableRightMouse(scene) {
                    var screenSpaceEventHandler = viewer.screenSpaceEventHandler;
                    screenSpaceEventHandler.setInputAction(function () {
                        scene.screenSpaceCameraController.enableZoom = false;
                    }, Cesium.ScreenSpaceEventType.RIGHT_DOWN);

                    screenSpaceEventHandler.setInputAction(function () {
                        scene.screenSpaceCameraController.enableZoom = true;
                    }, Cesium.ScreenSpaceEventType.RIGHT_UP);
                }

                function tick(timestamp) {
                    if (timestamp) {
                        var time_ellapsed = timestamp - last_time;
                        if ($scope.game_started) {
                            $scope.time_remaining = full_date - (timestamp - time_game_started) * 10;
                            if ($scope.time_remaining <= running_start_date && $scope.game_state == 'planning') {
                                $scope.game_state = 'running';
                                character.flyToInitialLocation();
                                playGo();
                            }
                            if ($scope.time_remaining <= zero_date) {
                                $scope.time_remaining = zero_date;
                                $scope.time_penalty = Math.ceil((zero_date - (full_date - (timestamp - time_game_started) * 10)) / 60000);
                            }
                        }

                        character.positionCharacter(time_ellapsed, timestamp);
                        updHud();
                        last_time = timestamp;
                    }
                    Cesium.requestAnimationFrame(tick);
                }

                function updHud() {
                    if (last_time - last_hud_updated < 500) return;
                    last_hud_updated = last_time;
                    if (!$scope.$$phase) $scope.$apply();
                }

                createHud();

                $scope.createNewMap = function (hours) {
                    $scope.game_started = true;
                    $scope.game_state = 'generating';
                    if (!$scope.$$phase) $scope.$apply();
                    $timeout(function(){
                        $scope.points_collected = 0;
                        full_date = new Date(2000, 1, 0, hours, 30, 0, 0);
                        running_start_date = new Date(2000, 1, 0, hours, 0, 0, 0);
                        time_game_started = last_time;
                        stations.createStations(map, utils, character.currentPos(), function () {
                            $scope.game_state = 'planning';
                            last_measure_pick = character.currentPos();
                            flyToWholeMapView();
                        }, hours);
                    }, 0)
                }

                function flyToWholeMapView() {
                    var pos_lon_lat = character.currentPos();
                    viewer.camera.flyTo({
                        destination: Cesium.Cartesian3.fromDegrees(pos_lon_lat[0] + stations.getMapWidth() / 0.016 * 0.0001 * 14, pos_lon_lat[1] - stations.getMapWidth() / 0.016 * 0.0006 * 14, pos_lon_lat[2] + stations.getMapWidth() / 0.016 * 60 * 18),
                        orientation: {
                            heading: Cesium.Math.toRadians(0.0),
                            pitch: Cesium.Math.toRadians(-45.0),
                            roll: 0.0
                        }
                    })
                }

                $rootScope.$on('cesium_position_clicked', function (event, lon_lat) {
                    console.log('click');
                    if (last_measure_pick == null)
                        last_measure_pick = character.currentPos();
                    if ($scope.game_state == 'running') {
                        character.changeTargetPosition(lon_lat, last_time);
                    }
                    if ($scope.game_state == 'planning') {
                        addMeasurementPosition(lon_lat);
                    }
                });

                $scope.total_distance = 0;
                var planning_line_segments = [];
                function addMeasurementPosition(lon_lat) {
                    var distance = Cesium.Cartesian3.distance(Cesium.Cartesian3.fromDegrees(last_measure_pick[0], last_measure_pick[1]), Cesium.Cartesian3.fromDegrees(lon_lat[0], lon_lat[1]));
                    $scope.total_distance += distance;
                    var rectangleInstance = new Cesium.GeometryInstance({
                        geometry: new Cesium.CorridorGeometry({
                            positions: Cesium.Cartesian3.fromDegreesArray([last_measure_pick[0], last_measure_pick[1], lon_lat[0], lon_lat[1]]),
                            width: 5
                        }),
                        attributes: {
                            color: new Cesium.ColorGeometryInstanceAttribute(0.9, .2, .2, 0.8)
                        }
                    });
                    var line = viewer.scene.primitives.add(new Cesium.GroundPrimitive({
                        geometryInstances: rectangleInstance
                    }));
                    line.distance = distance;
                    planning_line_segments.push(line);
                    last_measure_pick = lon_lat;
                }

                function playGo() {
                    var audio = new Audio('sounds/go.mp3');
                    audio.play();
                }

                $rootScope.$on('map.loaded', function () {
                    map = hs_map.map;
                });

                $rootScope.$on('cesiummap.loaded', function (event, _viewer) {
                    viewer = _viewer;
                    var scene = viewer.scene;
                    scene.globe.depthTestAgainstTerrain = true;
                    disableRightMouse(scene);
                    character.currentPos([hs_map.map.getView().getCenter()[0], hs_map.map.getView().getCenter()[1], 0]);
                    character.init($scope, $compile, olus, viewer, stations);
                    olus.init($scope, $compile, map, utils, _viewer, character);
                    tick();
                });

                $rootScope.$on('map.sync_center', function (e, center, bounds) {
                    if($scope.game_state == 'before_game')
                        character.currentPos(center);
                })

                $scope.$on('infopanel.updated', function (event) { });

                $scope.donePlanning = function () {
                    $scope.game_started = true;
                    $scope.game_state = 'running';
                    time_game_started = last_time;
                    full_date = running_start_date;
                    playGo();
                    character.flyToInitialLocation();
                }

                $scope.endGame = function(){
                    var el = angular.element('

');
                    $("#hs-dialog-area").append(el);
                    $compile(el)($scope);
                    $scope.game_started = false;
                    var audio = new Audio('sounds/fanfare.mp3');
                    audio.play();
                }
            }
        ]);

        return module;
    });
<|endoftext|>


<commit_before>'use strict';

var oldClientHash = require('mano-auth/utils/client-hash')
  , registerSubmit   = require('mano-auth/controller/server-master/register').submit
  , sendNotification = require('../../server/email-notifications/create-account');

var addUserSubmit = function (data) {
	return registerSubmit.apply(this, arguments)(function (result) {
		sendNotification(data).done(null, function (err) {
			console.log("Cannot send email", err, err.stack);
		});
		return result;
	});
};

// Add User
exports['user-add'].submit = function (normalizedData, data) {
	normalizedData['User#/password'] =
		oldClientHash(normalizedData['User#/email'], normalizedData['User#/password']);
	return addUserSubmit.apply(this, arguments);
};
<commit_msg>#1298 fixed controller setup<commit_after>'use strict';

var oldClientHash = require('mano-auth/utils/client-hash')
  , registerSubmit   = require('mano-auth/controller/server-master/register').submit
  , sendNotification = require('../../server/email-notifications/create-account');

var addUserSubmit = function (data) {
	return registerSubmit.apply(this, arguments)(function (result) {
		sendNotification(data).done(null, function (err) {
			console.log("Cannot send email", err, err.stack);
		});
		return result;
	});
};

// Add User
exports['user-add'] = {
	submit: function (normalizedData, data) {
		normalizedData['User#/password'] =
			oldClientHash(normalizedData['User#/email'], normalizedData['User#/password']);
		return addUserSubmit.apply(this, arguments);
	}
};
<|endoftext|>


<commit_before>'use strict';

function compareNumbers(a, b) {
    return a - b;
}

/**
 * Computes the sum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.sum = function sum(values) {
    var sum = 0;
    for (var i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
};

/**
 * Computes the maximum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.max = function max(values) {
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] > max) max = values[i];
    }
    return max;
};

/**
 * Computes the minimum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.min = function min(values) {
    var min = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
    }
    return min;
};

/**
 * Computes the min and max of the given values
 * @param {Array} values
 * @returns {{min: number, max: number}}
 */
exports.minMax = function minMax(values) {
    var min = values[0];
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
        if (values[i] > max) max = values[i];
    }
    return {
        min: min,
        max: max
    };
};

/**
 * Computes the arithmetic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.arithmeticMean = function arithmeticMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        sum += values[i];
    }
    return sum / l;
};

/**
 * {@link arithmeticMean}
 */
exports.mean = exports.arithmeticMean;

/**
 * Computes the geometric mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.geometricMean = function geometricMean(values) {
    var mul = 1;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        mul *= values[i];
    }
    return Math.pow(mul, 1 / l);
};

/**
 * Computes the mean of the log of the given values
 * If the return value is exponentiated, it gives the same result as the
 * geometric mean.
 * @param {Array} values
 * @returns {number}
 */
exports.logMean = function logMean(values) {
    var lnsum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        lnsum += Math.log(values[i]);
    }
    return lnsum / l;
};

/**
 * Computes the weighted grand mean for a list of means and sample sizes
 * @param {Array} means - Mean values for each set of samples
 * @param {Array} samples - Number of original values for each set of samples
 * @returns {number}
 */
exports.grandMean = function grandMean(means, samples) {
    var sum = 0;
    var n = 0;
    var l = means.length;
    for (var i = 0; i < l; i++) {
        sum += samples[i] * means[i];
        n += samples[i];
    }
    return sum / n;
};

/**
 * Computes the truncated mean of the given values using a given percentage
 * @param {Array} values
 * @param {number} percent - The percentage of values to keep (range: [0,1])
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var k = Math.floor(l * percent);
    var sum = 0;
    for (var i = k; i < (l - k); i++) {
        sum += values[i];
    }
    return sum / (l - 2 * k);
};

/**
 * Computes the harmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.harmonicMean = function harmonicMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        if (values[i] === 0) {
            throw new RangeError('value at index ' + i + 'is zero');
        }
        sum += 1 / values[i];
    }
    return l / sum;
};

/**
 * Computes the contraharmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.contraHarmonicMean = function contraHarmonicMean(values) {
    var r1 = 0;
    var r2 = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        r1 += values[i] * values[i];
        r2 += values[i];
    }
    if (r2 < 0) {
        throw new RangeError('sum of values is negative');
    }
    return r1 / r2;
};

/**
 * Computes the median of the given values
 * @param {Array} values
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.median = function median(values, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var half = Math.floor(l / 2);
    if (l % 2 === 0) {
        return (values[half - 1] + values[half]) * 0.5;
    } else {
        return values[half];
    }
};

/**
 * Computes the variance of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.variance = function variance(values, unbiased) {
    if (unbiased === undefined) unbiased = true;
    var theMean = exports.mean(values);
    var theVariance = 0;
    var l = values.length;

    for (var i = 0; i < l; i++) {
        var x = values[i] - theMean;
        theVariance += x * x;
    }

    if (unbiased) {
        return theVariance / (l - 1);
    } else {
        return theVariance / l;
    }
};

/**
 * Computes the standard deviation of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.standardDeviation = function standardDeviation(values, unbiased) {
    return Math.sqrt(exports.variance(values, unbiased));
};

exports.standardError = function standardError(values) {
    return exports.standardDeviation(values) / Math.sqrt(values.length);
};

/**
 * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-
 * Calculate the standard deviation via the Median of the absolute deviation
 *  The formula for the standard deviation only holds for Gaussian random variables.
 * @returns {number}
 */
exports.robustMeanAndStddev = function robustMeanAndStddev(y){
    var mean = 0,stddev=0;
    var length = y.length,i=0;
    for(i = 0; i < length; i++){
        mean+=y[i];
    }
    mean/=length;
    var averageDeviations = new Array(length);
    for (i = 0; i < length; i++)
        averageDeviations[i] = Math.abs(y[i] - mean);
    averageDeviations.sort();
    if (length % 2 == 1) {
        stddev = averageDeviations[(length-1)/2] / 0.6745;
    } else {
        stddev = 0.5*(averageDeviations[length/2]+averageDeviations[length/2-1]) / 0.6745;
    }

    return [mean, stddev];
};

exports.quartiles = function quartiles(values, alreadySorted) {
    if (typeof(alreadySorted) === 'undefined') alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }

    var quart = values.length / 4;
    var q1 = values[Math.ceil(quart) - 1];
    var q2 = exports.median(values, true);
    var q3 = values[Math.ceil(quart * 3) - 1];

    return {q1: q1, q2: q2, q3: q3};
};

exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
    return Math.sqrt(exports.pooledVariance(samples, unbiased));
};

exports.pooledVariance = function pooledVariance(samples, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var sum = 0;
    var length = 0, l = samples.length;
    for (var i = 0; i < l; i++) {
        var values = samples[i];
        var vari = exports.variance(values);

        sum += (values.length - 1) * vari;

        if (unbiased)
            length += values.length - 1;
        else
            length += values.length;
    }
    return sum / length;
};

exports.mode = function mode(values) {
    var l = values.length,
        itemCount = new Array(l),
        i;
    for (i = 0; i < l; i++) {
        itemCount[i] = 0;
    }
    var itemArray = new Array(l);
    var count = 0;

    for (i = 0; i < l; i++) {
        var index = itemArray.indexOf(values[i]);
        if (index >= 0)
            itemCount[index]++;
        else {
            itemArray[count] = values[i];
            itemCount[count] = 1;
            count++;
        }
    }

    var maxValue = 0, maxIndex = 0;
    for (i = 0; i < count; i++) {
        if (itemCount[i] > maxValue) {
            maxValue = itemCount[i];
            maxIndex = i;
        }
    }

    return itemArray[maxIndex];
};

exports.covariance = function covariance(vector1, vector2, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var mean1 = exports.mean(vector1);
    var mean2 = exports.mean(vector2);

    if (vector1.length !== vector2.length)
        throw "Vectors do not have the same dimensions";

    var cov = 0, l = vector1.length;
    for (var i = 0; i < l; i++) {
        var x = vector1[i] - mean1;
        var y = vector2[i] - mean2;
        cov += x * y;
    }

    if (unbiased)
        return cov / (l - 1);
    else
        return cov / l;
};

exports.skewness = function skewness(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);

    var s2 = 0, s3 = 0, l = values.length;
    for (var i = 0; i < l; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s3 += dev * dev * dev;
    }
    var m2 = s2 / l;
    var m3 = s3 / l;

    var g = m3 / (Math.pow(m2, 3 / 2.0));
    if (unbiased) {
        var a = Math.sqrt(l * (l - 1));
        var b = l - 2;
        return (a / b) * g;
    }
    else {
        return g;
    }
};

exports.kurtosis = function kurtosis(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);
    var n = values.length, s2 = 0, s4 = 0;

    for (var i = 0; i < n; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s4 += dev * dev * dev * dev;
    }
    var m2 = s2 / n;
    var m4 = s4 / n;

    if (unbiased) {
        var v = s2 / (n - 1);
        var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
        var b = s4 / (v * v);
        var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));

        return a * b - 3 * c;
    }
    else {
        return m4 / (m2 * m2) - 3;
    }
};

exports.entropy = function entropy(values, eps) {
    if (typeof(eps) === 'undefined') eps = 0;
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * Math.log(values[i] + eps);
    return -sum;
};

exports.weightedMean = function weightedMean(values, weights) {
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * weights[i];
    return sum;
};

exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
    return Math.sqrt(exports.weightedVariance(values, weights));
};

exports.weightedVariance = function weightedVariance(values, weights) {
    var theMean = exports.weightedMean(values, weights);
    var vari = 0, l = values.length;
    var a = 0, b = 0;

    for (var i = 0; i < l; i++) {
        var z = values[i] - theMean;
        var w = weights[i];

        vari += w * (z * z);
        b += w;
        a += w * w;
    }

    return vari * (b / (b * b - a));
};

exports.center = function center(values, inPlace) {
    if (typeof(inPlace) === 'undefined') inPlace = false;

    var result = values;
    if (!inPlace)
        result = [].concat(values);

    var theMean = exports.mean(result), l = result.length;
    for (var i = 0; i < l; i++)
        result[i] -= theMean;
};

exports.standardize = function standardize(values, standardDev, inPlace) {
    if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);
    if (typeof(inPlace) === 'undefined') inPlace = false;
    var l = values.length;
    var result = inPlace ? values : new Array(l);
    for (var i = 0; i < l; i++)
        result[i] = values[i] / standardDev;
    return result;
};

exports.cumulativeSum = function cumulativeSum(array) {
    var l = array.length;
    var result = new Array(l);
    result[0] = array[0];
    for (var i = 1; i < l; i++)
        result[i] = result[i - 1] + array[i];
    return result;
};
<commit_msg>Breaking change in robustMeanAndStddev<commit_after>'use strict';

function compareNumbers(a, b) {
    return a - b;
}

/**
 * Computes the sum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.sum = function sum(values) {
    var sum = 0;
    for (var i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
};

/**
 * Computes the maximum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.max = function max(values) {
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] > max) max = values[i];
    }
    return max;
};

/**
 * Computes the minimum of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.min = function min(values) {
    var min = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
    }
    return min;
};

/**
 * Computes the min and max of the given values
 * @param {Array} values
 * @returns {{min: number, max: number}}
 */
exports.minMax = function minMax(values) {
    var min = values[0];
    var max = values[0];
    var l = values.length;
    for (var i = 1; i < l; i++) {
        if (values[i] < min) min = values[i];
        if (values[i] > max) max = values[i];
    }
    return {
        min: min,
        max: max
    };
};

/**
 * Computes the arithmetic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.arithmeticMean = function arithmeticMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        sum += values[i];
    }
    return sum / l;
};

/**
 * {@link arithmeticMean}
 */
exports.mean = exports.arithmeticMean;

/**
 * Computes the geometric mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.geometricMean = function geometricMean(values) {
    var mul = 1;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        mul *= values[i];
    }
    return Math.pow(mul, 1 / l);
};

/**
 * Computes the mean of the log of the given values
 * If the return value is exponentiated, it gives the same result as the
 * geometric mean.
 * @param {Array} values
 * @returns {number}
 */
exports.logMean = function logMean(values) {
    var lnsum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        lnsum += Math.log(values[i]);
    }
    return lnsum / l;
};

/**
 * Computes the weighted grand mean for a list of means and sample sizes
 * @param {Array} means - Mean values for each set of samples
 * @param {Array} samples - Number of original values for each set of samples
 * @returns {number}
 */
exports.grandMean = function grandMean(means, samples) {
    var sum = 0;
    var n = 0;
    var l = means.length;
    for (var i = 0; i < l; i++) {
        sum += samples[i] * means[i];
        n += samples[i];
    }
    return sum / n;
};

/**
 * Computes the truncated mean of the given values using a given percentage
 * @param {Array} values
 * @param {number} percent - The percentage of values to keep (range: [0,1])
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var k = Math.floor(l * percent);
    var sum = 0;
    for (var i = k; i < (l - k); i++) {
        sum += values[i];
    }
    return sum / (l - 2 * k);
};

/**
 * Computes the harmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.harmonicMean = function harmonicMean(values) {
    var sum = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        if (values[i] === 0) {
            throw new RangeError('value at index ' + i + 'is zero');
        }
        sum += 1 / values[i];
    }
    return l / sum;
};

/**
 * Computes the contraharmonic mean of the given values
 * @param {Array} values
 * @returns {number}
 */
exports.contraHarmonicMean = function contraHarmonicMean(values) {
    var r1 = 0;
    var r2 = 0;
    var l = values.length;
    for (var i = 0; i < l; i++) {
        r1 += values[i] * values[i];
        r2 += values[i];
    }
    if (r2 < 0) {
        throw new RangeError('sum of values is negative');
    }
    return r1 / r2;
};

/**
 * Computes the median of the given values
 * @param {Array} values
 * @param {boolean} [alreadySorted=false]
 * @returns {number}
 */
exports.median = function median(values, alreadySorted) {
    if (alreadySorted === undefined) alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }
    var l = values.length;
    var half = Math.floor(l / 2);
    if (l % 2 === 0) {
        return (values[half - 1] + values[half]) * 0.5;
    } else {
        return values[half];
    }
};

/**
 * Computes the variance of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.variance = function variance(values, unbiased) {
    if (unbiased === undefined) unbiased = true;
    var theMean = exports.mean(values);
    var theVariance = 0;
    var l = values.length;

    for (var i = 0; i < l; i++) {
        var x = values[i] - theMean;
        theVariance += x * x;
    }

    if (unbiased) {
        return theVariance / (l - 1);
    } else {
        return theVariance / l;
    }
};

/**
 * Computes the standard deviation of the given values
 * @param {Array} values
 * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
 * @returns {number}
 */
exports.standardDeviation = function standardDeviation(values, unbiased) {
    return Math.sqrt(exports.variance(values, unbiased));
};

exports.standardError = function standardError(values) {
    return exports.standardDeviation(values) / Math.sqrt(values.length);
};

/**
 * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-
 * Calculate the standard deviation via the Median of the absolute deviation
 *  The formula for the standard deviation only holds for Gaussian random variables.
 * @returns {mean: number, stddev: number}
 */
exports.robustMeanAndStddev = function robustMeanAndStddev(y){
    var mean = 0,stddev=0;
    var length = y.length,i=0;
    for(i = 0; i < length; i++){
        mean+=y[i];
    }
    mean/=length;
    var averageDeviations = new Array(length);
    for (i = 0; i < length; i++)
        averageDeviations[i] = Math.abs(y[i] - mean);
    averageDeviations.sort();
    if (length % 2 == 1) {
        stddev = averageDeviations[(length-1)/2] / 0.6745;
    } else {
        stddev = 0.5*(averageDeviations[length/2]+averageDeviations[length/2-1]) / 0.6745;
    }

    return {mean: mean, stddev: stddev};
};

exports.quartiles = function quartiles(values, alreadySorted) {
    if (typeof(alreadySorted) === 'undefined') alreadySorted = false;
    if (!alreadySorted) {
        values = [].concat(values).sort(compareNumbers);
    }

    var quart = values.length / 4;
    var q1 = values[Math.ceil(quart) - 1];
    var q2 = exports.median(values, true);
    var q3 = values[Math.ceil(quart * 3) - 1];

    return {q1: q1, q2: q2, q3: q3};
};

exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
    return Math.sqrt(exports.pooledVariance(samples, unbiased));
};

exports.pooledVariance = function pooledVariance(samples, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var sum = 0;
    var length = 0, l = samples.length;
    for (var i = 0; i < l; i++) {
        var values = samples[i];
        var vari = exports.variance(values);

        sum += (values.length - 1) * vari;

        if (unbiased)
            length += values.length - 1;
        else
            length += values.length;
    }
    return sum / length;
};

exports.mode = function mode(values) {
    var l = values.length,
        itemCount = new Array(l),
        i;
    for (i = 0; i < l; i++) {
        itemCount[i] = 0;
    }
    var itemArray = new Array(l);
    var count = 0;

    for (i = 0; i < l; i++) {
        var index = itemArray.indexOf(values[i]);
        if (index >= 0)
            itemCount[index]++;
        else {
            itemArray[count] = values[i];
            itemCount[count] = 1;
            count++;
        }
    }

    var maxValue = 0, maxIndex = 0;
    for (i = 0; i < count; i++) {
        if (itemCount[i] > maxValue) {
            maxValue = itemCount[i];
            maxIndex = i;
        }
    }

    return itemArray[maxIndex];
};

exports.covariance = function covariance(vector1, vector2, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var mean1 = exports.mean(vector1);
    var mean2 = exports.mean(vector2);

    if (vector1.length !== vector2.length)
        throw "Vectors do not have the same dimensions";

    var cov = 0, l = vector1.length;
    for (var i = 0; i < l; i++) {
        var x = vector1[i] - mean1;
        var y = vector2[i] - mean2;
        cov += x * y;
    }

    if (unbiased)
        return cov / (l - 1);
    else
        return cov / l;
};

exports.skewness = function skewness(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);

    var s2 = 0, s3 = 0, l = values.length;
    for (var i = 0; i < l; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s3 += dev * dev * dev;
    }
    var m2 = s2 / l;
    var m3 = s3 / l;

    var g = m3 / (Math.pow(m2, 3 / 2.0));
    if (unbiased) {
        var a = Math.sqrt(l * (l - 1));
        var b = l - 2;
        return (a / b) * g;
    }
    else {
        return g;
    }
};

exports.kurtosis = function kurtosis(values, unbiased) {
    if (typeof(unbiased) === 'undefined') unbiased = true;
    var theMean = exports.mean(values);
    var n = values.length, s2 = 0, s4 = 0;

    for (var i = 0; i < n; i++) {
        var dev = values[i] - theMean;
        s2 += dev * dev;
        s4 += dev * dev * dev * dev;
    }
    var m2 = s2 / n;
    var m4 = s4 / n;

    if (unbiased) {
        var v = s2 / (n - 1);
        var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
        var b = s4 / (v * v);
        var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));

        return a * b - 3 * c;
    }
    else {
        return m4 / (m2 * m2) - 3;
    }
};

exports.entropy = function entropy(values, eps) {
    if (typeof(eps) === 'undefined') eps = 0;
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * Math.log(values[i] + eps);
    return -sum;
};

exports.weightedMean = function weightedMean(values, weights) {
    var sum = 0, l = values.length;
    for (var i = 0; i < l; i++)
        sum += values[i] * weights[i];
    return sum;
};

exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
    return Math.sqrt(exports.weightedVariance(values, weights));
};

exports.weightedVariance = function weightedVariance(values, weights) {
    var theMean = exports.weightedMean(values, weights);
    var vari = 0, l = values.length;
    var a = 0, b = 0;

    for (var i = 0; i < l; i++) {
        var z = values[i] - theMean;
        var w = weights[i];

        vari += w * (z * z);
        b += w;
        a += w * w;
    }

    return vari * (b / (b * b - a));
};

exports.center = function center(values, inPlace) {
    if (typeof(inPlace) === 'undefined') inPlace = false;

    var result = values;
    if (!inPlace)
        result = [].concat(values);

    var theMean = exports.mean(result), l = result.length;
    for (var i = 0; i < l; i++)
        result[i] -= theMean;
};

exports.standardize = function standardize(values, standardDev, inPlace) {
    if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);
    if (typeof(inPlace) === 'undefined') inPlace = false;
    var l = values.length;
    var result = inPlace ? values : new Array(l);
    for (var i = 0; i < l; i++)
        result[i] = values[i] / standardDev;
    return result;
};

exports.cumulativeSum = function cumulativeSum(array) {
    var l = array.length;
    var result = new Array(l);
    result[0] = array[0];
    for (var i = 1; i < l; i++)
        result[i] = result[i - 1] + array[i];
    return result;
};
<|endoftext|>


<commit_before>var React = require('react');
var Button = require('./Button');
var Transition = require('../../src/Transition');

var List = React.createClass({
  displayName: 'List',

  getInitialState: function () {
    return {
      callbackMsg: '',
      count: 1,
    };
  },

  _handleAdd: function () {
    this.setState(function (previousState) {
      return {count: Math.min(previousState.count + 1, 6)};
    });
  },

  _handleRemove: function () {
    this.setState(function (previousState) {
      return {count: Math.max(previousState.count - 1, 0)};
    });
  },

  _handleStartAppear: function (id) {
    this.setState({callbackMsg: id + ' start to appear'});
  },

  _handleStartEnter: function (id) {
    this.setState({callbackMsg: id + ' start to enter'});
  },

  _handleStartLeave: function (id) {
    this.setState({callbackMsg: id + ' start to leave'});
  },

  _handleAppeared: function (id) {
    this.setState({callbackMsg: id + ' appeared'});
  },

  _handleEntered: function (id) {
    this.setState({callbackMsg: id + ' entered'});
  },

  _handleLeft: function (id) {
    this.setState({callbackMsg: id + ' left'});
  },

  render: function () {
    var styles = {
      container: {
        background: '#FFF',
        boxShadow: '0 4px 5px 0 rgba(0, 0, 0, 0.14),' +
          '0 1px 10px 0 rgba(0, 0, 0, 0.12),' +
          '0 2px 4px -1px rgba(0, 0, 0, 0.4)',
        padding: '30px',
        height: '300px',
        width: '500px',
        overflow: 'hidden',
      },

      numbersContainer: {
        position: 'relative',
        height: '200px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      },

      base: {
        position: 'absolute',
        background: '#F50057',
        borderRadius: '0%',
        height: '150px',
        width: '150px',
        fontSize: '80px',
        lineHeight: '150px',
        verticalAlign: 'middle',
        textAlign: 'center',
        color: 'transparent',
        opacity: '0.5',
        transformOrigin: 'center center',
        transform: 'scale(0) rotate(0deg) skew(-90deg, -90deg)',
      },

      appear: {
        background: '#3F51B5',
        borderRadius: '50%',
        color: 'white',
        opacity: '1',
        transform: 'scale(1) rotate(360deg) skew(0deg, 0deg)',
        transition: 'color 0.5s 1s, opacity 1s 1s, border-radius 3s ease-out,' +
          'background 3s, transform 2s',
      },

      leave: {
        background: 'transparent',
        borderRadius: '50%',
        transform: 'scale(0) rotate(0deg) skew(-90deg, -90deg)',
        transition: 'all 2000ms',
      },

      button: {
        backgroundColor: '#2980b9',
        margin: '0px 15px 15px 0',
      },

      callback: {
        height: '20px',
        backgroundColor: '#FFF',
        border: '1px solid #2980b9',
        borderRadius: '2px',
        marginBottom: '15px',
        padding: '5px 5px 5px 5px',
      },
    };

    var elems = [];

    for (var i = 0; i < this.state.count; i++) {
      elems.push(

{i}

      );
    }

    return (

          <Button
            label="Add"
            style={styles.button}
            onClick={this._handleAdd}
          />
          <Button
            label="Remove"
            style={styles.button}
            onClick={this._handleRemove}
          />

          {'Callback: ' + this.state.callbackMsg}

        <Transition
          childrenBaseStyle={styles.base}
          childrenAppearStyle={styles.appear}
          childrenEnterStyle={styles.appear}
          childrenLeaveStyle={styles.leave}
          onChildAppeared={this._handleAppeared}
          onChildEntered={this._handleEntered}
          onChildLeft={this._handleLeft}
          onChildStartAppear={this._handleStartAppear}
          onChildStartEnter={this._handleStartEnter}
          onChildStartLeave={this._handleStartLeave}
          style={styles.numbersContainer}
        >
          {elems}
        </Transition>

    );
  },

});

module.exports = List;<commit_msg>Update transition property in the numbers list demo<commit_after>var React = require('react');
var Button = require('./Button');
var Transition = require('../../src/Transition');

var List = React.createClass({
  displayName: 'List',

  getInitialState: function () {
    return {
      callbackMsg: '',
      count: 1,
    };
  },

  _handleAdd: function () {
    this.setState(function (previousState) {
      return {count: Math.min(previousState.count + 1, 6)};
    });
  },

  _handleRemove: function () {
    this.setState(function (previousState) {
      return {count: Math.max(previousState.count - 1, 0)};
    });
  },

  _handleStartAppear: function (id) {
    this.setState({callbackMsg: id + ' start to appear'});
  },

  _handleStartEnter: function (id) {
    this.setState({callbackMsg: id + ' start to enter'});
  },

  _handleStartLeave: function (id) {
    this.setState({callbackMsg: id + ' start to leave'});
  },

  _handleAppeared: function (id) {
    this.setState({callbackMsg: id + ' appeared'});
  },

  _handleEntered: function (id) {
    this.setState({callbackMsg: id + ' entered'});
  },

  _handleLeft: function (id) {
    this.setState({callbackMsg: id + ' left'});
  },

  render: function () {
    var styles = {
      container: {
        background: '#FFF',
        boxShadow: '0 4px 5px 0 rgba(0, 0, 0, 0.14),' +
          '0 1px 10px 0 rgba(0, 0, 0, 0.12),' +
          '0 2px 4px -1px rgba(0, 0, 0, 0.4)',
        padding: '30px',
        height: '300px',
        width: '500px',
        overflow: 'hidden',
      },

      numbersContainer: {
        position: 'relative',
        height: '200px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      },

      base: {
        position: 'absolute',
        background: '#F50057',
        borderRadius: '0%',
        height: '150px',
        width: '150px',
        fontSize: '80px',
        lineHeight: '150px',
        verticalAlign: 'middle',
        textAlign: 'center',
        color: 'transparent',
        opacity: '0.5',
        transformOrigin: 'center center',
        transform: 'scale(0) rotate(0deg) skew(-90deg, -90deg)',
      },

      appear: {
        background: '#3F51B5',
        borderRadius: '50%',
        color: 'white',
        opacity: '1',
        transform: 'scale(1) rotate(360deg) skew(0deg, 0deg)',
        transition: 'color 0.5s 1s, opacity 2s 1s, border-radius 2.5s, ' +
          'background 3s ease-out, transform 2s',
      },

      leave: {
        background: 'transparent',
        borderRadius: '50%',
        transform: 'scale(0) rotate(0deg) skew(-90deg, -90deg)',
        transition: 'all 2000ms',
      },

      button: {
        backgroundColor: '#2980b9',
        margin: '0px 15px 15px 0',
      },

      callback: {
        height: '20px',
        backgroundColor: '#FFF',
        border: '1px solid #2980b9',
        borderRadius: '2px',
        marginBottom: '15px',
        padding: '5px 5px 5px 5px',
      },
    };

    var elems = [];

    for (var i = 0; i < this.state.count; i++) {
      elems.push(

{i}

      );
    }

    return (

          <Button
            label="Add"
            style={styles.button}
            onClick={this._handleAdd}
          />
          <Button
            label="Remove"
            style={styles.button}
            onClick={this._handleRemove}
          />

          {'Callback: ' + this.state.callbackMsg}

        <Transition
          childrenBaseStyle={styles.base}
          childrenAppearStyle={styles.appear}
          childrenEnterStyle={styles.appear}
          childrenLeaveStyle={styles.leave}
          onChildAppeared={this._handleAppeared}
          onChildEntered={this._handleEntered}
          onChildLeft={this._handleLeft}
          onChildStartAppear={this._handleStartAppear}
          onChildStartEnter={this._handleStartEnter}
          onChildStartLeave={this._handleStartLeave}
          style={styles.numbersContainer}
        >
          {elems}
        </Transition>

    );
  },

});

module.exports = List;<|endoftext|>