<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name dists
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/stats/base/dists}
*/
setReadOnly( ns, 'dists', require( '@stdlib/stats/base/dists' ) );

/**
* @name dmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmax}
*/
setReadOnly( ns, 'dmax', require( '@stdlib/stats/base/dmax' ) );

/**
* @name dmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmean}
*/
setReadOnly( ns, 'dmean', require( '@stdlib/stats/base/dmean' ) );

/**
* @name dmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmin}
*/
setReadOnly( ns, 'dmin', require( '@stdlib/stats/base/dmin' ) );

/**
* @name dnanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmax}
*/
setReadOnly( ns, 'dnanmax', require( '@stdlib/stats/base/dnanmax' ) );

/**
* @name dnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmean}
*/
setReadOnly( ns, 'dnanmean', require( '@stdlib/stats/base/dnanmean' ) );

/**
* @name dnanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmin}
*/
setReadOnly( ns, 'dnanmin', require( '@stdlib/stats/base/dnanmin' ) );

/**
* @name dnansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnansum}
*/
setReadOnly( ns, 'dnansum', require( '@stdlib/stats/base/dnansum' ) );

/**
* @name dnansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnansumors}
*/
setReadOnly( ns, 'dnansumors', require( '@stdlib/stats/base/dnansumors' ) );

/**
* @name dsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsmean}
*/
setReadOnly( ns, 'dsmean', require( '@stdlib/stats/base/dsmean' ) );

/**
* @name dsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsnanmean}
*/
setReadOnly( ns, 'dsnanmean', require( '@stdlib/stats/base/dsnanmean' ) );

/**
* @name dsum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsum}
*/
setReadOnly( ns, 'dsum', require( '@stdlib/stats/base/dsum' ) );

/**
* @name dsumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsumors}
*/
setReadOnly( ns, 'dsumors', require( '@stdlib/stats/base/dsumors' ) );

/**
* @name max
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/max}
*/
setReadOnly( ns, 'max', require( '@stdlib/stats/base/max' ) );

/**
* @name mean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/mean}
*/
setReadOnly( ns, 'mean', require( '@stdlib/stats/base/mean' ) );

/**
* @name min
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/min}
*/
setReadOnly( ns, 'min', require( '@stdlib/stats/base/min' ) );

/**
* @name nanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmax}
*/
setReadOnly( ns, 'nanmax', require( '@stdlib/stats/base/nanmax' ) );

/**
* @name nanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmean}
*/
setReadOnly( ns, 'nanmean', require( '@stdlib/stats/base/nanmean' ) );

/**
* @name nanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmin}
*/
setReadOnly( ns, 'nanmin', require( '@stdlib/stats/base/nanmin' ) );

/**
* @name nansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansum}
*/
setReadOnly( ns, 'nansum', require( '@stdlib/stats/base/nansum' ) );

/**
* @name nansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansumors}
*/
setReadOnly( ns, 'nansumors', require( '@stdlib/stats/base/nansumors' ) );

/**
* @name nansumpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansumpw}
*/
setReadOnly( ns, 'nansumpw', require( '@stdlib/stats/base/nansumpw' ) );

/**
* @name sdsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsmean}
*/
setReadOnly( ns, 'sdsmean', require( '@stdlib/stats/base/sdsmean' ) );

/**
* @name sdsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsnanmean}
*/
setReadOnly( ns, 'sdsnanmean', require( '@stdlib/stats/base/sdsnanmean' ) );

/**
* @name smax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smax}
*/
setReadOnly( ns, 'smax', require( '@stdlib/stats/base/smax' ) );

/**
* @name smean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smean}
*/
setReadOnly( ns, 'smean', require( '@stdlib/stats/base/smean' ) );

/**
* @name smin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smin}
*/
setReadOnly( ns, 'smin', require( '@stdlib/stats/base/smin' ) );

/**
* @name snanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmax}
*/
setReadOnly( ns, 'snanmax', require( '@stdlib/stats/base/snanmax' ) );

/**
* @name snanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmean}
*/
setReadOnly( ns, 'snanmean', require( '@stdlib/stats/base/snanmean' ) );

/**
* @name snanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmin}
*/
setReadOnly( ns, 'snanmin', require( '@stdlib/stats/base/snanmin' ) );

/**
* @name snansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snansum}
*/
setReadOnly( ns, 'snansum', require( '@stdlib/stats/base/snansum' ) );

/**
* @name snansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snansumors}
*/
setReadOnly( ns, 'snansumors', require( '@stdlib/stats/base/snansumors' ) );

/**
* @name ssum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/ssum}
*/
setReadOnly( ns, 'ssum', require( '@stdlib/stats/base/ssum' ) );

/**
* @name ssumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/ssumors}
*/
setReadOnly( ns, 'ssumors', require( '@stdlib/stats/base/ssumors' ) );

/**
* @name sum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sum}
*/
setReadOnly( ns, 'sum', require( '@stdlib/stats/base/sum' ) );

/**
* @name sumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sumors}
*/
setReadOnly( ns, 'sumors', require( '@stdlib/stats/base/sumors' ) );

/**
* @name sumpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sumpw}
*/
setReadOnly( ns, 'sumpw', require( '@stdlib/stats/base/sumpw' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name dists
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/stats/base/dists}
*/
setReadOnly( ns, 'dists', require( '@stdlib/stats/base/dists' ) );

/**
* @name dmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmax}
*/
setReadOnly( ns, 'dmax', require( '@stdlib/stats/base/dmax' ) );

/**
* @name dmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmean}
*/
setReadOnly( ns, 'dmean', require( '@stdlib/stats/base/dmean' ) );

/**
* @name dmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dmin}
*/
setReadOnly( ns, 'dmin', require( '@stdlib/stats/base/dmin' ) );

/**
* @name dnanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmax}
*/
setReadOnly( ns, 'dnanmax', require( '@stdlib/stats/base/dnanmax' ) );

/**
* @name dnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmean}
*/
setReadOnly( ns, 'dnanmean', require( '@stdlib/stats/base/dnanmean' ) );

/**
* @name dnanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnanmin}
*/
setReadOnly( ns, 'dnanmin', require( '@stdlib/stats/base/dnanmin' ) );

/**
* @name dnansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnansum}
*/
setReadOnly( ns, 'dnansum', require( '@stdlib/stats/base/dnansum' ) );

/**
* @name dnansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnansumors}
*/
setReadOnly( ns, 'dnansumors', require( '@stdlib/stats/base/dnansumors' ) );

/**
* @name dnansumpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dnansumpw}
*/
setReadOnly( ns, 'dnansumpw', require( '@stdlib/stats/base/dnansumpw' ) );

/**
* @name dsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsmean}
*/
setReadOnly( ns, 'dsmean', require( '@stdlib/stats/base/dsmean' ) );

/**
* @name dsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsnanmean}
*/
setReadOnly( ns, 'dsnanmean', require( '@stdlib/stats/base/dsnanmean' ) );

/**
* @name dsum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsum}
*/
setReadOnly( ns, 'dsum', require( '@stdlib/stats/base/dsum' ) );

/**
* @name dsumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/dsumors}
*/
setReadOnly( ns, 'dsumors', require( '@stdlib/stats/base/dsumors' ) );

/**
* @name max
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/max}
*/
setReadOnly( ns, 'max', require( '@stdlib/stats/base/max' ) );

/**
* @name mean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/mean}
*/
setReadOnly( ns, 'mean', require( '@stdlib/stats/base/mean' ) );

/**
* @name min
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/min}
*/
setReadOnly( ns, 'min', require( '@stdlib/stats/base/min' ) );

/**
* @name nanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmax}
*/
setReadOnly( ns, 'nanmax', require( '@stdlib/stats/base/nanmax' ) );

/**
* @name nanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmean}
*/
setReadOnly( ns, 'nanmean', require( '@stdlib/stats/base/nanmean' ) );

/**
* @name nanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nanmin}
*/
setReadOnly( ns, 'nanmin', require( '@stdlib/stats/base/nanmin' ) );

/**
* @name nansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansum}
*/
setReadOnly( ns, 'nansum', require( '@stdlib/stats/base/nansum' ) );

/**
* @name nansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansumors}
*/
setReadOnly( ns, 'nansumors', require( '@stdlib/stats/base/nansumors' ) );

/**
* @name nansumpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/nansumpw}
*/
setReadOnly( ns, 'nansumpw', require( '@stdlib/stats/base/nansumpw' ) );

/**
* @name sdsmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsmean}
*/
setReadOnly( ns, 'sdsmean', require( '@stdlib/stats/base/sdsmean' ) );

/**
* @name sdsnanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sdsnanmean}
*/
setReadOnly( ns, 'sdsnanmean', require( '@stdlib/stats/base/sdsnanmean' ) );

/**
* @name smax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smax}
*/
setReadOnly( ns, 'smax', require( '@stdlib/stats/base/smax' ) );

/**
* @name smean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smean}
*/
setReadOnly( ns, 'smean', require( '@stdlib/stats/base/smean' ) );

/**
* @name smin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/smin}
*/
setReadOnly( ns, 'smin', require( '@stdlib/stats/base/smin' ) );

/**
* @name snanmax
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmax}
*/
setReadOnly( ns, 'snanmax', require( '@stdlib/stats/base/snanmax' ) );

/**
* @name snanmean
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmean}
*/
setReadOnly( ns, 'snanmean', require( '@stdlib/stats/base/snanmean' ) );

/**
* @name snanmin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snanmin}
*/
setReadOnly( ns, 'snanmin', require( '@stdlib/stats/base/snanmin' ) );

/**
* @name snansum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snansum}
*/
setReadOnly( ns, 'snansum', require( '@stdlib/stats/base/snansum' ) );

/**
* @name snansumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/snansumors}
*/
setReadOnly( ns, 'snansumors', require( '@stdlib/stats/base/snansumors' ) );

/**
* @name ssum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/ssum}
*/
setReadOnly( ns, 'ssum', require( '@stdlib/stats/base/ssum' ) );

/**
* @name ssumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/ssumors}
*/
setReadOnly( ns, 'ssumors', require( '@stdlib/stats/base/ssumors' ) );

/**
* @name sum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sum}
*/
setReadOnly( ns, 'sum', require( '@stdlib/stats/base/sum' ) );

/**
* @name sumors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sumors}
*/
setReadOnly( ns, 'sumors', require( '@stdlib/stats/base/sumors' ) );

/**
* @name sumpw
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/stats/base/sumpw}
*/
setReadOnly( ns, 'sumpw', require( '@stdlib/stats/base/sumpw' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/*
 * containers.js: Instance methods for working with containers from AWS S3
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var async = require('async'),
    request = require('request'),
    base = require('../../../core/storage'),
    pkgcloud = require('../../../../../lib/pkgcloud'),
    storage = pkgcloud.providers.amazon.storage;

//
// ### function getContainers (callback)
// #### @callback {function} Continuation to respond to when complete.
// Gets all Rackspace Cloudfiles containers for this instance.
//
exports.getContainers = function (callback) {
  var self = this;

  this.xmlRequest({
    path: '/'
  }, function (err, body) {
    if (err) {
      return callback(err);
    }

    var containers = self._toArray(body.Buckets.Bucket);

    containers = containers.map(function (container) {
      return new (storage.Container)(self, container);
    });

    callback(null, containers);
  });
};

//
// ### function getContainer (container, callback)
// #### @container {string|storage.Container} Name of the container to return
// #### @callback {function} Continuation to respond to when complete.
// Responds with the Rackspace Cloudfiles container for the specified
// `container`.
//
exports.getContainer = function (container, callback) {
  var containerName = container instanceof storage.Container ? container.name : container,
      self = this;

  this.xmlRequest({
    container: containerName
  }, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new (storage.Container)(self, body));
  });
};

//
// ### function createContainer (container, callback)
// #### @container {string|Container} Container to create in Rackspace Cloudfiles.
// #### @callback {function} Continuation to respond to when complete.
// Creates the specified `container` in the Rackspace Cloudfiles associated
// with this instance.
//
exports.createContainer = function (container, callback) {
  var containerName = container instanceof base.Container ? container.name : container,
      self = this;

  this.xmlRequest({
    method: 'PUT',
    container: containerName
  }, function (err) {
    return err
      ? callback(err)
      : callback(null, new (storage.Container)(self, container));
  });
};

//
// ### function destroyContainer (container, callback)
// #### @container {string} Name of the container to destroy
// #### @callback {function} Continuation to respond to when complete.
// Destroys the specified `container` and all files in it.
//
exports.destroyContainer = function (container, callback) {
  var containerName = container instanceof base.Container ? container.name : container,
      self = this;

  this.getFiles(containerName, false, function (err, files) {
    if (err) {
      return callback(err);
    }

    function deleteContainer(err) {
      if (err) {
        return callback(err);
      }

      self.xmlRequest({
        method: 'DELETE',
        container: containerName
      }, function (err, body, res) {
          return err
            ? callback(err)
            : callback(null, res.statusCode == 204);
        }
      );
    }

    function destroyFile(file, next) {
      file.remove(next);
    }

    if (files.length === 0) {
      return deleteContainer();
    }

    async.forEach(files, destroyFile, deleteContainer);
  });
};
<commit_msg>[docs] fixes amazon section documentation<commit_after>/*
 * containers.js: Instance methods for working with containers from AWS S3
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var async = require('async'),
  request = require('request'),
  base = require('../../../core/storage'),
  pkgcloud = require('../../../../../lib/pkgcloud'),
  storage = pkgcloud.providers.amazon.storage;

//
// ### function getContainers (callback)
// #### @callback {function} Continuation to respond to when complete.
// Gets all AWS S3 containers for this instance.
//
exports.getContainers = function (callback) {
  var self = this;

  this.xmlRequest({
    path: '/'
  }, function (err, body) {
    if (err) {
      return callback(err);
    }

    var containers = self._toArray(body.Buckets.Bucket);

    containers = containers.map(function (container) {
      return new (storage.Container)(self, container);
    });

    callback(null, containers);
  });
};

//
// ### function getContainer (container, callback)
// #### @container {string|storage.Container} Name of the container to return
// #### @callback {function} Continuation to respond to when complete.
// Responds with the AWS S3 container for the specified
// `container`.
//
exports.getContainer = function (container, callback) {
  var containerName = container instanceof storage.Container ? container.name : container,
    self = this;

  this.xmlRequest({
    container: containerName
  }, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new (storage.Container)(self, body));
  });
};

//
// ### function createContainer (container, callback)
// #### @container {string|Container} Container to create in AWS S3.
// #### @callback {function} Continuation to respond to when complete.
// Creates the specified `container` in AWS S3 account associated
// with this instance.
//
exports.createContainer = function (container, callback) {
  var containerName = container instanceof base.Container ? container.name : container,
    self = this;

  this.xmlRequest({
    method: 'PUT',
    container: containerName
  }, function (err) {
    return err
      ? callback(err)
      : callback(null, new (storage.Container)(self, container));
  });
};

//
// ### function destroyContainer (container, callback)
// #### @container {string} Name of the container to destroy
// #### @callback {function} Continuation to respond to when complete.
// Destroys the specified `container` and all files in it.
//
exports.destroyContainer = function (container, callback) {
  var containerName = container instanceof base.Container ? container.name : container,
    self = this;

  this.getFiles(containerName, false, function (err, files) {
    if (err) {
      return callback(err);
    }

    function deleteContainer(err) {
      if (err) {
        return callback(err);
      }

      self.xmlRequest({
          method: 'DELETE',
          container: containerName
        }, function (err, body, res) {
          return err
            ? callback(err)
            : callback(null, res.statusCode == 204);
        }
      );
    }

    function destroyFile(file, next) {
      file.remove(next);
    }

    if (files.length === 0) {
      return deleteContainer();
    }

    async.forEach(files, destroyFile, deleteContainer);
  });
};
<|endoftext|>


<commit_before>!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.scroller=t():e.scroller=t()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=t.ScrollContainer=void 0;var o=n(1),l=t.ScrollContainer=function(){function e(t){var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];i(this,e),this._container=t,this._scrollView=new e.ScrollView(this,r),this._options=r,this._eventListener={wheel:function(e){n.setScrollTop(n._container.scrollTop+e.deltaY),n.setScrollLeft(n._container.scrollLeft+e.deltaX)},touchstart:function(e){if(!e.defaultPrevented&&!r.disableTouchScrollingOnContainer){e.preventDefault();var t=e.which||0,i=e.touches[t].pageX,o=e.touches[t].pageY,l=function(e){if(e.which===t){e.preventDefault();var r=i-e.touches[t].pageX,l=o-e.touches[t].pageY;i=e.touches[t].pageX,o=e.touches[t].pageY,n.setScrollTop(l,"add"),n.setScrollLeft(r,"add")}},s=function(e){e.which===t&&(e.preventDefault(),document.body.removeEventListener("touchmove",l),document.body.removeEventListener("touchend",s),document.body.removeEventListener("touchleave",s),l=null,s=null)};document.body.addEventListener("touchmove",l),document.body.addEventListener("touchend",s),document.body.addEventListener("touchleave",s)}}};var o=this._container.clientHeight,l=this._container.clientWidth,s=this._container.scrollHeight,a=this._container.scrollWidth;this._intervalPointer=window.setInterval(function(){for(var e=n._container.parentElement;void 0!=e&&e!==document.body;)e=e.parentElement;void 0==e?n.destroy():(o!==n._container.clientHeight||l!==n._container.clientWidth||s!==n._container.scrollHeight||a!==n._container.scrollWidth)&&(o=n._container.clientHeight,l=n._container.clientWidth,s=n._container.scrollHeight,a=n._container.scrollWidth,n._scrollView.parentUpdated())},r.checkInterval||300),this._container.style.overflow="hidden",this._container.style.position="relative",Object.keys(this._eventListener).forEach(function(e){n._container.addEventListener(e,n._eventListener[e])}),this._scrollView.parentUpdated()}return r(e,[{key:"setScrollTop",value:function(e,t){if(!this._options.disableYScrolling){var n=this._container.scrollTop;switch(t){case"add":n+=e;break;case"substract":n-=e;break;default:n=e}0>n?n=0:n>this._container.scrollHeight-this._container.clientHeight&&(n=this._container.scrollHeight-this._container.clientHeight),this._scrollView.scrollTopUpdated(n),this._container.scrollTop=n}}},{key:"setScrollLeft",value:function(e,t){if(!this._options.disableXScrolling){var n=this._container.scrollLeft;switch(t){case"add":n+=e;break;case"substract":n-=e;break;default:n=e}0>n?n=0:n>this._container.scrollWidth-this._container.clientWidth&&(n=this._container.scrollWidth-this._container.clientWidth),this._scrollView.scrollLeftUpdated(n),this._container.scrollLeft=n}}},{key:"destroy",value:function(){var e=this;window.clearInterval(this._intervalPointer),Object.keys(this._eventListener).forEach(function(t){e._container.removeEventListener(t,e._eventListener[t])}),this._scrollView.destroy(),this._scrollView=null,this._container=null}}]),e}();l.ScrollView=o.ScrollView;t.VERSION="1.0.0-alpha"},function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollView=void 0;var o=n(2);t.ScrollView=function(){function e(t,n){var r=this;i(this,e),this._parent=t._container,this._scrollerParent=t,this._xElement=document.createElement("div"),this._yElement=document.createElement("div"),this._xEventListener=o.generateEventHandlerForElement.call(this,"pageX","setScrollLeft"),this._yEventListener=o.generateEventHandlerForElement.call(this,"pageY","setScrollTop"),this._xElement.style.height="6px",this._xElement.style.left="0px",this._yElement.style.width="6px",this._yElement.style.top="0px",this._xElement.style.position=this._yElement.style.position="absolute",this._xElement.style.backgroundColor=this._yElement.style.backgroundColor="rgba(0,0,0,0.6)",this._xElement.style.borderRadius=this._yElement.style.borderRadius="3px",(0,o.applyOptionsToScollBarElement)(this._xElement,"xElement",n),(0,o.applyOptionsToScollBarElement)(this._yElement,"yElement",n),n.disableXScrolling||this._parent.appendChild(this._xElement),n.disableYScrolling||this._parent.appendChild(this._yElement),Object.keys(this._xEventListener).forEach(function(e){r._xElement.addEventListener(e,r._xEventListener[e])}),Object.keys(this._yEventListener).forEach(function(e){r._yElement.addEventListener(e,r._yEventListener[e])}),this.parentUpdated(),this.scrollTopUpdated(),this.scrollLeftUpdated()}return r(e,[{key:"scrollTopUpdated",value:function(e){if(this._parentScrollHeight>this._parentHeight){var t=e/(this._parentScrollHeight-this._parentHeight);t*=this._parentHeight-this._elementHeight;var n=e+t;this._yElement.style.top=n+"px"}this._xElement.style.top=e+this._parentHeight-6+"px"}},{key:"scrollLeftUpdated",value:function(e){if(this._parentScrollWidth>this._parentWidth){var t=e/(this._parentScrollWidth-this._parentWidth);t*=this._parentWidth-this._elementWidth;var n=e+t;this._xElement.style.left=n+"px"}this._yElement.style.left=e+this._parentWidth-6+"px"}},{key:"parentUpdated",value:function(){this._parentWidth=this._parent.clientWidth,this._parentScrollWidth=this._parent.scrollWidth,this._elementWidth=this._parentWidth*this._parentWidth/this._parentScrollWidth,this._parentHeight=this._parent.clientHeight,this._parentScrollHeight=this._parent.scrollHeight,this._elementHeight=this._parentHeight*this._parentHeight/this._parentScrollHeight,this._parentWidth<this._parentScrollWidth?(this._xElement.style.display="block",this._xElement.style.width=this._elementWidth+"px",this.scrollLeftUpdated(this._parent.scrollLeft)):this._xElement.style.display="none",this._parentHeight<this._parentScrollHeight?(this._yElement.style.display="block",this._yElement.style.height=this._elementHeight+"px",this.scrollTopUpdated(this._parent.scrollTop)):this._yElement.style.display="none"}},{key:"destroy",value:function(){var e=this;Object.keys(this._xEventListener).forEach(function(t){e._xElement.removeEventListener(t,e._xEventListener[t])}),Object.keys(this._yEventListener).forEach(function(t){e._yElement.removeEventListener(t,e._yEventListener[t])}),this._parent=null,this._scrollerParent=null,this._xElement=null,this._yElement=null}}]),e}()},function(e,t){"use strict";function n(e,t){var n=this;return{mousedown:function(i){i.preventDefault();var r=i[e],o=function(i){i.preventDefault();var o=i[e]-r;r=i[e],n._scrollerParent[t](o,"add")},l=function(e){e.preventDefault(),document.body.removeEventListener("mousemove",o),document.body.removeEventListener("mouseup",l),document.body.removeEventListener("mouseleave",l),o=null,l=null};document.body.addEventListener("mousemove",o),document.body.addEventListener("mouseup",l),document.body.addEventListener("mouseleave",l)},touchstart:function(i){i.preventDefault();var r=i.which||0,o=i.touches[r][e],l=function(i){if(i.which===r){i.preventDefault();var l=i.touches[r][e]-o;o=i.touches[r][e],n._scrollerParent[t](l,"add")}},s=function(e){e.which===r&&(e.preventDefault(),document.body.removeEventListener("touchmove",l),document.body.removeEventListener("touchend",s),document.body.removeEventListener("touchleave",s),l=null,s=null)};document.body.addEventListener("touchmove",l),document.body.addEventListener("touchend",s),document.body.addEventListener("touchleave",s)}}}function i(e,t,n){var i=t+"Styles",r=t+"Class";n[i]&&"[object Object]"===toString.call(n[i])&&Object.keys(n[i]).forEach(function(t){e.style[t]=n[i][t]}),n[r]&&"[object String]"===toString.call(n[r])?e.classList.add(n[r]):Array.isArray(n[r])&&n[r].forEach(function(t){e.classList.add(t)})}Object.defineProperty(t,"__esModule",{value:!0}),t.generateEventHandlerForElement=n,t.applyOptionsToScollBarElement=i}])});<commit_msg>Updated bundle<commit_after>!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.scroller=t():e.scroller=t()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=t.ScrollContainer=void 0;var o=n(1),l=t.ScrollContainer=function(){function e(t){var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];i(this,e),this._container=t,this._scrollView=new e.ScrollView(this,r),this._options=r,this._eventListener={wheel:function(e){n.setScrollTop(n._container.scrollTop+e.deltaY),n.setScrollLeft(n._container.scrollLeft+e.deltaX)},touchstart:function(e){if(!e.defaultPrevented&&!r.disableTouchScrollingOnContainer){e.preventDefault();var t=e.which||0,i=e.touches[t].pageX,o=e.touches[t].pageY,l=function(e){if(e.which===t){e.preventDefault();var r=i-e.touches[t].pageX,l=o-e.touches[t].pageY;i=e.touches[t].pageX,o=e.touches[t].pageY,n.setScrollTop(l,"add"),n.setScrollLeft(r,"add")}},s=function(e){e.which===t&&(e.preventDefault(),document.body.removeEventListener("touchmove",l),document.body.removeEventListener("touchend",s),document.body.removeEventListener("touchleave",s),l=null,s=null)};document.body.addEventListener("touchmove",l),document.body.addEventListener("touchend",s),document.body.addEventListener("touchleave",s)}}};var o=this._container.clientHeight,l=this._container.clientWidth,s=this._container.scrollHeight,c=this._container.scrollWidth;this._intervalPointer=window.setInterval(function(){for(var e=n._container.parentElement;void 0!=e&&e!==document.body;)e=e.parentElement;void 0==e?n.destroy():(o!==n._container.clientHeight||l!==n._container.clientWidth||s!==n._container.scrollHeight||c!==n._container.scrollWidth)&&(o=n._container.clientHeight,l=n._container.clientWidth,s=n._container.scrollHeight,c=n._container.scrollWidth,n._scrollView.parentUpdated())},r.checkInterval||300),this._container.style.overflow="hidden",this._container.style.position="relative",Object.keys(this._eventListener).forEach(function(e){n._container.addEventListener(e,n._eventListener[e])}),this._scrollView.parentUpdated()}return r(e,[{key:"setScrollTop",value:function(e,t){if(!this._options.disableYScrolling){var n=this._container.scrollTop;switch(t){case"add":n+=e;break;case"substract":n-=e;break;default:n=e}0>n?n=0:n>this._container.scrollHeight-this._container.clientHeight&&(n=this._container.scrollHeight-this._container.clientHeight),this._scrollView.scrollTopUpdated(n),this._container.scrollTop=n}}},{key:"setScrollLeft",value:function(e,t){if(!this._options.disableXScrolling){var n=this._container.scrollLeft;switch(t){case"add":n+=e;break;case"substract":n-=e;break;default:n=e}0>n?n=0:n>this._container.scrollWidth-this._container.clientWidth&&(n=this._container.scrollWidth-this._container.clientWidth),this._scrollView.scrollLeftUpdated(n),this._container.scrollLeft=n}}},{key:"destroy",value:function(){var e=this;window.clearInterval(this._intervalPointer),Object.keys(this._eventListener).forEach(function(t){e._container.removeEventListener(t,e._eventListener[t])}),this._scrollView.destroy(),this._scrollView=null,this._container=null}}]),e}();l.ScrollView=o.ScrollView;t.VERSION="1.0.0-alpha"},function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollView=void 0;var o=n(2);t.ScrollView=function(){function e(t,n){var r=this;i(this,e),this._parent=t._container,this._scrollerParent=t,this._xElement=document.createElement("div"),this._yElement=document.createElement("div"),this._xEventListener=o.generateEventHandlerForElement.call(this,"pageX","setScrollLeft"),this._yEventListener=o.generateEventHandlerForElement.call(this,"pageY","setScrollTop"),this._xElement.style.height="6px",this._xElement.style.left="0px",this._yElement.style.width="6px",this._yElement.style.top="0px",this._xElement.style.position=this._yElement.style.position="absolute",this._xElement.style.backgroundColor=this._yElement.style.backgroundColor="rgba(0,0,0,0.6)",this._xElement.style.borderRadius=this._yElement.style.borderRadius="3px",(0,o.applyOptionsToScollBarElement)(this._xElement,"xElement",n),(0,o.applyOptionsToScollBarElement)(this._yElement,"yElement",n),n.disableXScrolling||this._parent.appendChild(this._xElement),n.disableYScrolling||this._parent.appendChild(this._yElement),Object.keys(this._xEventListener).forEach(function(e){r._xElement.addEventListener(e,r._xEventListener[e])}),Object.keys(this._yEventListener).forEach(function(e){r._yElement.addEventListener(e,r._yEventListener[e])}),this.parentUpdated()}return r(e,[{key:"scrollTopUpdated",value:function(e){if(this._parentScrollHeight>this._parentHeight){var t=e/(this._parentScrollHeight-this._parentHeight);t*=this._parentHeight-this._elementHeight,this._yElement.style.top=e+t+"px"}this._xElement.style.top=e+this._parentHeight-6+"px"}},{key:"scrollLeftUpdated",value:function(e){if(this._parentScrollWidth>this._parentWidth){var t=e/(this._parentScrollWidth-this._parentWidth);t*=this._parentWidth-this._elementWidth,this._xElement.style.left=e+t+"px"}this._yElement.style.left=e+this._parentWidth-6+"px"}},{key:"parentUpdated",value:function(){this._parentWidth=this._parent.clientWidth,this._parentScrollWidth=this._parent.scrollWidth,this._elementWidth=this._parentWidth*this._parentWidth/this._parentScrollWidth,this._parentHeight=this._parent.clientHeight,this._parentScrollHeight=this._parent.scrollHeight,this._elementHeight=this._parentHeight*this._parentHeight/this._parentScrollHeight,this._parentWidth<this._parentScrollWidth?(this.scrollTopUpdated(this._parent.scrollTop),this._xElement.style.display="block",this._xElement.style.width=this._elementWidth+"px"):this._xElement.style.display="none",this._parentHeight<this._parentScrollHeight?(this.scrollLeftUpdated(this._parent.scrollLeft),this._yElement.style.display="block",this._yElement.style.height=this._elementHeight+"px"):this._yElement.style.display="none"}},{key:"destroy",value:function(){var e=this;Object.keys(this._xEventListener).forEach(function(t){e._xElement.removeEventListener(t,e._xEventListener[t])}),Object.keys(this._yEventListener).forEach(function(t){e._yElement.removeEventListener(t,e._yEventListener[t])}),this._parent=null,this._scrollerParent=null,this._xElement=null,this._yElement=null}}]),e}()},function(e,t){"use strict";function n(e,t){var n=this;return{mousedown:function(i){i.preventDefault();var r=i[e],o=function(i){i.preventDefault();var o=i[e]-r;r=i[e],n._scrollerParent[t](o,"add")},l=function(e){e.preventDefault(),document.body.removeEventListener("mousemove",o),document.body.removeEventListener("mouseup",l),document.body.removeEventListener("mouseleave",l),o=null,l=null};document.body.addEventListener("mousemove",o),document.body.addEventListener("mouseup",l),document.body.addEventListener("mouseleave",l)},touchstart:function(i){i.preventDefault();var r=i.which||0,o=i.touches[r][e],l=function(i){if(i.which===r){i.preventDefault();var l=i.touches[r][e]-o;o=i.touches[r][e],n._scrollerParent[t](l,"add")}},s=function(e){e.which===r&&(e.preventDefault(),document.body.removeEventListener("touchmove",l),document.body.removeEventListener("touchend",s),document.body.removeEventListener("touchleave",s),l=null,s=null)};document.body.addEventListener("touchmove",l),document.body.addEventListener("touchend",s),document.body.addEventListener("touchleave",s)}}}function i(e,t,n){var i=t+"Styles",r=t+"Class";n[i]&&"[object Object]"===toString.call(n[i])&&Object.keys(n[i]).forEach(function(t){e.style[t]=n[i][t]}),n[r]&&"[object String]"===toString.call(n[r])?e.classList.add(n[r]):Array.isArray(n[r])&&n[r].forEach(function(t){e.classList.add(t)})}Object.defineProperty(t,"__esModule",{value:!0}),t.generateEventHandlerForElement=n,t.applyOptionsToScollBarElement=i}])});<|endoftext|>


<commit_before>var _ = require('lodash');
var on_client = require('on-client');

var filterOptions = function(input, Parent){
	var output = _.clone(input);
	if (on_client){
		if ('bodyTemplate' in input){
			output.template = input.bodyTemplate;
		}
	} else {
		if ('documentTemplate' in input){
			output.template = input.documentTemplate;
		}
		if ('bodyTemplate' in input){
			output.partials = _.clone(input.partials || {});
			output.partials.body = input.bodyTemplate;
		}
	}
	// inherit api members
	if ('api' in input){
		output.api = _.assign({}, Parent.prototype.api || {}, input.api);
	}
	// convert and inherit pages
	if ('pages' in input){
		//convert input array to output object
		var input_pages = {};
		_.forEach(input.pages, function(Page){
			input_pages[Page.prototype.name] = Page;
		});
		// inherit pages
		output.pages = _.assign({}, Parent.prototype.pages || {}, input_pages);
	}
	return output;
};

module.exports = filterOptions;<commit_msg>clean bodyTemplate & documentTemplate from init options<commit_after>var _ = require('lodash');
var on_client = require('on-client');

var filterOptions = function(input, Parent){
	var output = _.clone(input);
	if (on_client){
		if ('documentTemplate' in input){
			delete output.documentTemplate;
		}
		if ('bodyTemplate' in input){
			output.template = input.bodyTemplate;
			delete output.bodyTemplate;
		}
	} else {
		if ('documentTemplate' in input){
			output.template = input.documentTemplate;
			delete output.documentTemplate;
		}
		if ('bodyTemplate' in input){
			output.partials = _.clone(input.partials || {});
			output.partials.body = input.bodyTemplate;
			delete output.bodyTemplate;
		}
	}
	// inherit api members
	if ('api' in input){
		output.api = _.assign({}, Parent.prototype.api || {}, input.api);
	}
	// convert and inherit pages
	if ('pages' in input){
		//convert input array to output object
		var input_pages = {};
		_.forEach(input.pages, function(Page){
			input_pages[Page.prototype.name] = Page;
		});
		// inherit pages
		output.pages = _.assign({}, Parent.prototype.pages || {}, input_pages);
	}
	return output;
};

module.exports = filterOptions;<|endoftext|>


<commit_before>(function($, window, undefined){

	"use strict";

	// 定数定義
	var CONSTANT = {
		SIZE: {
			width: 1280,
			height: 720
		},
		fps: 30,
		SCREEN: {
			LOADING: 0,
			TITLE:   1,
		}
	};

	var manifest = [
		{id: "normal", src: "/assets/img/technyan-normal.png"},
		{id: "angry", src: "/assets/img/technyan-angry.png"},
		{id: "smile", src: "/assets/img/technyan-smile.png"},
		{id: "back", src: "/assets/img/back.png"},
		{id: "sound", src: "/assets/sound/nc43138.wav"}
	];

	var _stage, _load;

	var _SCREENSTATUS = CONSTANT.SCREEN.LOADING;
	var _SCREENSTATUS_OLD = null;

	var game, Game = function() {
		game = this;
		this.stage = null;
		this.initalized();
	};
	Game.prototype = {
		// 初期化
		initalized: function() {
			// 画面領域の設定(Retinaの対応)
			$("#game").attr({width: CONSTANT.SIZE.width, height: CONSTANT.SIZE.height}).css({width: CONSTANT.SIZE.width/2, height:CONSTANT.SIZE.height/2});
			// ステージの作成
			this.stage = new createjs.Stage($("#game").get(0));
			// 入力の受付
			createjs.Touch.enable(this.stage);
			// FPSの設定
			createjs.Ticker.setFPS(CONSTANT.fps);
			// ticker
			createjs.Ticker.addEventListener("tick", $.proxy(this.transitScreen, this));
		},
		transitScreen: function() {
			// 画面が変更されたら
			if ( _SCREENSTATUS != _SCREENSTATUS_OLD ) {
				// ローディング画面
				if ( _SCREENSTATUS == CONSTANT.SCREEN.LOADING ) {
					this.stage.removeAllChildren();
					this.stage.addChild(this.displayLoading());
				}
				// タイトル画面
				else if ( _SCREENSTATUS == CONSTANT.SCREEN.TITLE ) {
					this.stage.removeAllChildren();
					this.stage.addChild(this.displayTitle());
				}
			}
			this.stage.update();
			_SCREENSTATUS_OLD = _SCREENSTATUS;
		},
		// ローディング画面
		displayLoading: function() {
			// Loadingのコンテナ
			var container = new createjs.Container();

			// 黒色の背景
			var back = new createjs.Shape();
			back.graphics.f("#000").r(0, 0, CONSTANT.SIZE.width, CONSTANT.SIZE.height);
			back.set({x: 0, y: 0});
			var text = new createjs.Text();
			text.set({
				x: CONSTANT.SIZE.width/2,
				y :CONSTANT.SIZE.height/2 - text.getMeasuredHeight()/2,
				text: "よみこみちゅう   ",
				font: "24px PixelMplus12",
				color: "#FFF",
				textAlign: "center"
			});

			container.addChild(back, text);

			createjs.Tween.get(text, {loop: true, ignoreGlobalPause: false})
				.to({text: "よみこみちゅう.  "}, 500)
				.to({text: "よみこみちゅう.. "}, 500)
				.to({text: "よみこみちゅう..."}, 500)
				.wait(500);

			return container;
		},
		// タイトル画面
		displayTitle: function() {
			// タイトル画面用のコンテナ
			var container = new createjs.Container();

			// 黒色の背景
			var back = new createjs.Shape();
			back.graphics.f("#000000").r(0, 0, CONSTANT.SIZE.width, CONSTANT.SIZE.height);
			back.set({x: 0, y: 0});

			var halo = new createjs.Bitmap("/assets/img/back.png");
			halo.regX = 960;
			halo.regY = 960;
			halo.set({
				regX: 640, regY: 640, x: 640, y: 440, scaleX: 1.5, scaleY: 1.5,
				alpha: 0
			})
			createjs.Tween.get(halo, {loop: true, ignoreGlobalPause: false})
				.to({rotation:360}, 10000);

			var technyans = {
				normal: new createjs.Bitmap(preload.load.getResult("normal")),
				angry:  new createjs.Bitmap(preload.load.getResult("angry")),
				smile:  new createjs.Bitmap(preload.load.getResult("smile"))
			};

			var text = new createjs.Text();
			text.set({
				x: CONSTANT.SIZE.width/2,
				y: 80,
				text: "てくにゃんを喜ばせろ!!!!",
				font: "50px メイリオ",
				color: "#FFF",
				textAlign: "center"
			});

			var technyan = technyans.normal;

			// てくにゃんをクリックした時の効果
			technyan.addEventListener("click", function(){
				halo.alpha += 0.12;
				if ( halo.alpha >= 0.3 ) {
					container.removeChild(text);
				}
				createjs.Tween.get(technyan, {loop: false, ignoreGlobalPause: false})
					.to({scaleX: 0.95, scaleY: 0.95}, 50)
					.to({scaleX: 1.0, scaleY: 1.0}, 100);

			});

			var flag = true;

			createjs.Ticker.addEventListener("tick", function(evt) {
				container.removeChild(technyan);
				if ( halo.alpha > 0 && flag ) {
					halo.alpha -= 0.02;
				}
				if ( halo.alpha > 1 ) {
					technyan = technyans.smile;
					if ( flag )	{
						createjs.Sound.play("sound");
						text.set({
							text: "てくにゃんはお喜びになられている!!!",
							color: "#000"
						});
						container.addChild(text);
					}
					flag = false;
				}
				technyan.set({ regX: 270, regY: 270, x: 640, y: 440 });
				container.addChild(technyan);
			});

			container.addChild(back, halo, text);

			return container;
		}
	};

	// Preload.js
	var preload, Preload = function() {
		preload = this;
		this.load = null;
		this.initalized();
	};
	Preload.prototype = {
		// 初期化
		initalized: function() {
			// Preload.js
			this.load = new createjs.LoadQueue();

			// Sound.js
			this.load.installPlugin(createjs.Sound);

			// 最大並列接続数
			this.load.setMaxConnections(6);

			// 読み込みの進行状況が変化した
			this.load.addEventListener("progress", this.handleProgress);
			// 1つのファイルを読み込み終わったら
			//this.load.addEventListener("fileload", this.handleFileLoadComplete);
			// 全てのファイルを読み込み終わったら
			this.load.addEventListener("complete", this.handleComplete);

			// 読み込み開始
			this.load.loadManifest(manifest);
		},
		// 読み込み中
		handleProgress: function(event) {
			// 読み込み率を0.0~1.0で取得
			var progress = event.progress;
		},
		// ファイルごとの読み込み完了イベント
		handleProgress: function(event) {
			// 読み込んだファイル
			var result = event.result;
		},
		// 読み込み完了
		handleComplete: function() {
			_SCREENSTATUS = CONSTANT.SCREEN.TITLE;
		}
	}

	$(document).ready(function(e){
		new Preload();
		new Game();
		window.game = game;
	});

}(jQuery, window, undefined));
<commit_msg>カウンターを追加<commit_after>(function($, window, undefined){

	"use strict";

	// 定数定義
	var CONSTANT = {
		SIZE: {
			width: 1280,
			height: 720
		},
		fps: 30,
		SCREEN: {
			LOADING: 0,
			TITLE:   1,
		}
	};

	var manifest = [
		{id: "normal", src: "./assets/img/technyan-normal.png"},
		{id: "angry", src: "./assets/img/technyan-angry.png"},
		{id: "smile", src: "./assets/img/technyan-smile.png"},
		{id: "back", src: "./assets/img/back.png"},
		{id: "sound", src: "./assets/sound/nc43138.wav"}
	];

	var _stage, _load;

	var _SCREENSTATUS = CONSTANT.SCREEN.LOADING;
	var _SCREENSTATUS_OLD = null;

	var game, Game = function() {
		game = this;
		this.stage = null;
		this.initalized();
	};
	Game.prototype = {
		// 初期化
		initalized: function() {
			// 画面領域の設定(Retinaの対応)
			$("#game").attr({width: CONSTANT.SIZE.width, height: CONSTANT.SIZE.height}).css({width: CONSTANT.SIZE.width/2, height:CONSTANT.SIZE.height/2});
			// ステージの作成
			this.stage = new createjs.Stage($("#game").get(0));
			// 入力の受付
			createjs.Touch.enable(this.stage);
			// FPSの設定
			createjs.Ticker.setFPS(CONSTANT.fps);
			// ticker
			createjs.Ticker.addEventListener("tick", $.proxy(this.transitScreen, this));
		},
		transitScreen: function() {
			// 画面が変更されたら
			if ( _SCREENSTATUS != _SCREENSTATUS_OLD ) {
				// ローディング画面
				if ( _SCREENSTATUS == CONSTANT.SCREEN.LOADING ) {
					this.stage.removeAllChildren();
					this.stage.addChild(this.displayLoading());
				}
				// タイトル画面
				else if ( _SCREENSTATUS == CONSTANT.SCREEN.TITLE ) {
					this.stage.removeAllChildren();
					this.stage.addChild(this.displayTitle());
				}
			}
			this.stage.update();
			_SCREENSTATUS_OLD = _SCREENSTATUS;
		},
		// ローディング画面
		displayLoading: function() {
			// Loadingのコンテナ
			var container = new createjs.Container();

			// 黒色の背景
			var back = new createjs.Shape();
			back.graphics.f("#000").r(0, 0, CONSTANT.SIZE.width, CONSTANT.SIZE.height);
			back.set({x: 0, y: 0});
			var text = new createjs.Text();
			text.set({
				x: CONSTANT.SIZE.width/2,
				y :CONSTANT.SIZE.height/2 - text.getMeasuredHeight()/2,
				text: "よみこみちゅう   ",
				font: "24px PixelMplus12",
				color: "#FFF",
				textAlign: "center"
			});

			container.addChild(back, text);

			createjs.Tween.get(text, {loop: true, ignoreGlobalPause: false})
				.to({text: "よみこみちゅう.  "}, 500)
				.to({text: "よみこみちゅう.. "}, 500)
				.to({text: "よみこみちゅう..."}, 500)
				.wait(500);

			return container;
		},
		// タイトル画面
		displayTitle: function() {
			// タイトル画面用のコンテナ
			var container = new createjs.Container();

			// 黒色の背景
			var back = new createjs.Shape();
			back.graphics.f("#000000").r(0, 0, CONSTANT.SIZE.width, CONSTANT.SIZE.height);
			back.set({x: 0, y: 0});

			var halo = new createjs.Bitmap(preload.load.getResult("back"));
			halo.regX = 960;
			halo.regY = 960;
			halo.set({
				regX: 640, regY: 640, x: 640, y: 440, scaleX: 1.5, scaleY: 1.5,
				alpha: 0
			})
			createjs.Tween.get(halo, {loop: true, ignoreGlobalPause: false})
				.to({rotation:360}, 10000);

			var technyans = {
				normal: new createjs.Bitmap(preload.load.getResult("normal")),
				angry:  new createjs.Bitmap(preload.load.getResult("angry")),
				smile:  new createjs.Bitmap(preload.load.getResult("smile"))
			};

			var text = new createjs.Text();
			text.set({
				x: CONSTANT.SIZE.width/2,
				y: 80,
				text: "てくにゃんを喜ばせろ!!!!",
				font: "Bold 50px メイリオ",
				color: "#FFF",
				textAlign: "center"
			});

			var technyan = technyans.normal;
			technyan.set({ regX: 270, regY: 270, x: 640, y: 440 });

			var click = 0;

			// てくにゃんをクリックした時の効果
			technyan.addEventListener("click", function(){
				halo.alpha += 0.12;
				if ( halo.alpha >= 0.3 ) {
					container.removeChild(text);
				}
				createjs.Tween.get(technyan, {loop: false, ignoreGlobalPause: false})
					.to({scaleX: 0.95, scaleY: 0.95}, 50)
					.to({scaleX: 1.0, scaleY: 1.0}, 100);
				click++;
			});

			var flag = true;

			createjs.Ticker.addEventListener("tick", function(evt) {
				if ( halo.alpha > 0 && flag ) {
					halo.alpha -= 0.02;
				}
				// てくにゃんが喜んだ
				if ( halo.alpha > 1 ) {
					if ( flag )	{
						container.removeChild(technyan);
						technyan = technyans.smile;
						technyan.set({ regX: 270, regY: 270, x: 640, y: 440 });
						container.addChild(technyan);
						createjs.Sound.play("sound");
						text.set({
							text: "てくにゃんはお喜びになられている!!!",
							color: "#000",
							shadow: new createjs.Shadow("#fff", 0, 2, 5),
						});
						$.ajax({
							url: "http://test.windyakin.net/technyan-halo/cgi/count.cgi?"+click,
							type: "get",
							dataType: "json"
						})
						.done(function(data){
							var count = new createjs.Text();
							count.set({
								x: CONSTANT.SIZE.width/2,
								y: 500,
								text: "本日お喜びになった回数 "+ data.happy + "回\n" +
											"クリックされた回数 " + data.click + "回",
								font: "Bold 50px メイリオ",
								color: "#FFF",
								shadow: new createjs.Shadow("#000000", 5, 5, 10),
								textAlign: "center",
								alpha: 0
							});
							container.addChild(count);
							createjs.Tween.get(count, {loop: false, ignoreGlobalPause: false})
								.wait(3000)
								.to({alpha: 1}, 50)
						});

						container.addChild(text);
					}
					flag = false;
				}
			});

			container.addChild(back, halo, text, technyan);

			return container;
		}
	};

	// Preload.js
	var preload, Preload = function() {
		preload = this;
		this.load = null;
		this.initalized();
	};
	Preload.prototype = {
		// 初期化
		initalized: function() {
			// Preload.js
			this.load = new createjs.LoadQueue();

			// Sound.js
			this.load.installPlugin(createjs.Sound);

			// 最大並列接続数
			this.load.setMaxConnections(6);

			// 読み込みの進行状況が変化した
			this.load.addEventListener("progress", this.handleProgress);
			// 1つのファイルを読み込み終わったら
			//this.load.addEventListener("fileload", this.handleFileLoadComplete);
			// 全てのファイルを読み込み終わったら
			this.load.addEventListener("complete", this.handleComplete);

			// 読み込み開始
			this.load.loadManifest(manifest);
		},
		// 読み込み中
		handleProgress: function(event) {
			// 読み込み率を0.0~1.0で取得
			var progress = event.progress;
		},
		// ファイルごとの読み込み完了イベント
		handleProgress: function(event) {
			// 読み込んだファイル
			var result = event.result;
		},
		// 読み込み完了
		handleComplete: function() {
			_SCREENSTATUS = CONSTANT.SCREEN.TITLE;
		}
	}

	$(document).ready(function(e){
		new Preload();
		new Game();
		window.game = game;
	});

}(jQuery, window, undefined));
<|endoftext|>


<commit_before>#!/usr/bin/env node

/* jslint node: true */
/* eslint-disable no-console */
'use strict';

//	ENiGMA½
const config		= require('./core/config.js');
const db			= require('./core/database.js');
const resolvePath	= require('./core/misc_util.js').resolvePath;

//	deps
const _				= require('lodash');
const async			= require('async');
const assert		= require('assert');
const inq			= require('inquirer');
const mkdirsSync	= require('fs-extra').mkdirsSync;
const fs			= require('fs');
const hjson			= require('hjson');
const paths			= require('path');

const argv 			= require('minimist')(process.argv.slice(2));

const ExitCodes = {
	SUCCESS		: 0,
	ERROR		: -1,
	BAD_COMMAND	: -2,
	BAD_ARGS	: -3,
};

const USAGE_HELP = {
	General :
`usage: optutil.js [--version] [--help]
                   <command> [<args>]

global args:
  --config PATH         : specify config path (${getDefaultConfigPath()})

commands:
  user                  : user utilities
  config                : config file management

`,
	User :
`usage: optutil.js user --user USERNAME <args>

valid args:
  --user USERNAME       : specify username for further actions
  --password PASS       : set new password
  --delete              : delete user
  --activate            : activate user
  --deactivate          : deactivate user
`,

	Config :
`usage: optutil.js config <args>

valid args:
  --new                 : generate a new/initial configuration
`
};

function printUsage(command) {
	console.error(USAGE_HELP[command]);
}

function initConfig(cb) {
	const configPath = argv.config ? argv.config : config.getDefaultPath();

	config.init(configPath, cb);
}

function initConfigAndDatabases(cb) {
	async.series(
		[
			function init(callback) {
				initConfig(callback);
			},
			function initDb(callback) {
				db.initializeDatabases(callback);
			},
		],
		err => {
			return cb(err);
		}
	);
}

function getUser(userName, cb) {
	const user = require('./core/user.js');
	user.getUserIdAndName(argv.user, function userNameAndId(err, userId) {
		if(err) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return cb(new Error('Failed to retrieve user'));
		} else {
			let u = new user.User();
			u.userId = userId;
			return cb(null, u);
		}
	});
}

function initAndGetUser(userName, cb) {
	async.waterfall(
		[
			function init(callback) {
				initConfigAndDatabases(callback);
			},
			function getUserObject(callback) {
				getUser(argv.user, (err, user) => {
					if(err) {
						process.exitCode = ExitCodes.BAD_ARGS;
						return callback(err);
					}
					return callback(null, user);
				});
			}
		],
		(err, user) => {
			return cb(err, user);
		}
	);
}

function setAccountStatus(userName, active) {
	async.waterfall(
		[
			function init(callback) {
				initAndGetUser(argv.user, callback);
			},
			function activateUser(user, callback) {
				const AccountStatus = require('./core/user.js').User.AccountStatus;
				user.persistProperty('account_status', active ? AccountStatus.active : AccountStatus.inactive, callback);
			}
		],
		err => {
			if(err) {
				console.error(err.message);
			} else {
				console.info('User ' + ((true === active) ? 'activated' : 'deactivated'));
			}
		}
	);
}

function handleUserCommand() {
	if(true === argv.help || !_.isString(argv.user) || 0 === argv.user.length) {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('User');
	}

	if(_.isString(argv.password)) {
		if(0 === argv.password.length) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return console.error('Invalid password');
		}

		async.waterfall(
			[
				function init(callback) {
					initAndGetUser(argv.user, callback);
				},
				function setNewPass(user, callback) {
					user.setNewAuthCredentials(argv.password, function credsSet(err) {
						if(err) {
							process.exitCode = ExitCodes.ERROR;
							callback(new Error('Failed setting password'));
						} else {
							callback(null);
						}
					});
				}
			],
			function complete(err) {
				if(err) {
					console.error(err.message);
				} else {
					console.info('Password set');
				}
			}
		);
	} else if(argv.activate) {
		setAccountStatus(argv.user, true);
	} else if(argv.deactivate) {
		setAccountStatus(argv.user, false);
	}
}

function getAnswers(questions, cb) {
	inq.prompt(questions).then( answers => {
		return cb(answers);
	});
}

function getDefaultConfigPath() {
	return resolvePath('~/.config/enigma-bbs/config.hjson');
}

const QUESTIONS = {
	Intro		: [
		{
			name	: 'createNewConfig',
			message	: 'Create a new configuration?',
			type	: 'confirm',
			default	: false,
		},
		{
			name	: 'configPath',
			message	: 'Configuration path:',
			default	: argv.config ? argv.config : getDefaultConfigPath(),
			when	: answers => answers.createNewConfig
		},
	],

	OverwriteConfig	: [
		{
			name	: 'overwriteConfig',
			message	: 'Config file exists. Overwrite?',
			type	: 'confirm',
			default	: false,
		}
	],

	Basic			: [
		{
			name	: 'boardName',
			message	: 'BBS name:',
			default	: 'New ENiGMA½ BBS',
		},
	],

	Misc		: [
		{
			name	: 'loggingLevel',
			message	: 'Logging level:',
			type	: 'list',
			choices	: [ 'Error', 'Warn', 'Info', 'Debug', 'Trace' ],
			default	: 2,
			filter	: s => s.toLowerCase(),
		},
		{
			name	: 'sevenZipExe',
			message	: '7-Zip executable:',
			type	: 'list',
			choices	: [ '7z', '7za', 'None' ]
		}
	],

	MessageConfAndArea	: [
		{
			name	: 'msgConfName',
			message	: 'First message conference:',
			default	: 'Local',
		},
		{
			name	: 'msgConfDesc',
			message	: 'Conference description:',
			default	: 'Local Areas',
		},
		{
			name	: 'msgAreaName',
			message	: 'First area in message conference:',
			default	: 'General',
		},
		{
			name	: 'msgAreaDesc',
			message	: 'Area description:',
			default	: 'General chit-chat',
		}
	]
};

function makeMsgConfAreaName(s) {
	return s.toLowerCase().replace(/\s+/g, '_');
}

function askNewConfigQuestions(cb) {

	const ui = new inq.ui.BottomBar();

	let configPath;
	let config;

	async.waterfall(
		[
			function intro(callback) {
				getAnswers(QUESTIONS.Intro, answers => {
					if(!answers.createNewConfig) {
						return callback('exit');
					}

					//	adjust for ~ and the like
					configPath = resolvePath(answers.configPath);

					const configDir = paths.dirname(configPath);
					mkdirsSync(configDir);

					//
					//	Check if the file exists and can be written to
					//
					fs.access(configPath, fs.F_OK | fs.W_OK, err => {
						if(err) {
							if('EACCES' === err.code) {
								ui.log.write(`${configPath} cannot be written to`);
								callback('exit');
							} else if('ENOENT' === err.code) {
								callback(null, false);
							}
						} else {
							callback(null, true);	//	exists + writable
						}
					});
				});
			},
			function promptOverwrite(needPrompt, callback) {
				if(needPrompt) {
					getAnswers(QUESTIONS.OverwriteConfig, answers => {
						callback(answers.overwriteConfig ? null : 'exit');
					});
				} else {
					callback(null);
				}
			},
			function basic(callback) {
				getAnswers(QUESTIONS.Basic, answers => {
					config = {
						general : {
							boardName : answers.boardName,
						},
					};

					callback(null);
				});
			},
			function msgConfAndArea(callback) {
				getAnswers(QUESTIONS.MessageConfAndArea, answers => {
					config.messageConferences = {};

					const confName	= makeMsgConfAreaName(answers.msgConfName);
					const areaName	= makeMsgConfAreaName(answers.msgAreaName);

					config.messageConferences[confName] = {
						name	: answers.msgConfName,
						desc	: answers.msgConfDesc,
						sort	: 1,
						default	: true,
					};

					config.messageConferences.another_sample_conf = {
						name	: 'Another Sample Conference',
						desc	: 'Another conference example. Change me!',
						sort	: 2,
					};

					config.messageConferences[confName].areas = {};
					config.messageConferences[confName].areas[areaName] = {
						name	: answers.msgAreaName,
						desc	: answers.msgAreaDesc,
						sort	: 1,
						default	: true,
					};

					config.messageConferences.another_sample_conf = {
						areas :  {
							another_sample_area : {
								name	: 'Another Sample Area',
								desc	: 'Another area example. Change me!',
								sort	: 2
							}
						}
					};

					callback(null);
				});
			},
			function misc(callback) {
				getAnswers(QUESTIONS.Misc, answers => {
					if('None' !== answers.sevenZipExe) {
						config.archivers = {
							zip : {
								compressCmd		: answers.sevenZipExe,
								decompressCmd	: answers.sevenZipExe,
							}
						};
					}

					config.logging = {
						level : answers.loggingLevel,
					};

					callback(null);
				});
			}
		],
		err => {
			cb(err, configPath, config);
		}
	);
}

function handleConfigCommand() {
	if(true === argv.help) {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('Config');
	}

	if(argv.new) {
		askNewConfigQuestions( (err, configPath, config) => {
			if(err) {
				return;
			}

			config = hjson.stringify(config, { bracesSameLine : true, spaces : '\t' } );

			try {
				fs.writeFileSync(configPath, config, 'utf8');
				console.info('Configuration generated');
			} catch(e) {
				console.error('Exception attempting to create config: ' + e.toString());
			}
		});
	} else {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('Config');
	}
}

function main() {

	process.exitCode = ExitCodes.SUCCESS;

	if(true === argv.version) {
		return console.info(require('./package.json').version);
	}

	if(0 === argv._.length ||
		'help' === argv._[0])
	{
		printUsage('General');
		process.exit(ExitCodes.SUCCESS);
	}

	switch(argv._[0]) {
		case 'user' :
			handleUserCommand();
			break;

		case 'config' :
			handleConfigCommand();
			break;

		default:
			printUsage('');
			process.exitCode = ExitCodes.BAD_COMMAND;
	}
}

main();<commit_msg>Remove assert<commit_after>#!/usr/bin/env node

/* jslint node: true */
/* eslint-disable no-console */
'use strict';

//	ENiGMA½
const config		= require('./core/config.js');
const db			= require('./core/database.js');
const resolvePath	= require('./core/misc_util.js').resolvePath;

//	deps
const _				= require('lodash');
const async			= require('async');
const inq			= require('inquirer');
const mkdirsSync	= require('fs-extra').mkdirsSync;
const fs			= require('fs');
const hjson			= require('hjson');
const paths			= require('path');

const argv 			= require('minimist')(process.argv.slice(2));

const ExitCodes = {
	SUCCESS		: 0,
	ERROR		: -1,
	BAD_COMMAND	: -2,
	BAD_ARGS	: -3,
};

const USAGE_HELP = {
	General :
`usage: optutil.js [--version] [--help]
                   <command> [<args>]

global args:
  --config PATH         : specify config path (${getDefaultConfigPath()})

commands:
  user                  : user utilities
  config                : config file management

`,
	User :
`usage: optutil.js user --user USERNAME <args>

valid args:
  --user USERNAME       : specify username for further actions
  --password PASS       : set new password
  --delete              : delete user
  --activate            : activate user
  --deactivate          : deactivate user
`,

	Config :
`usage: optutil.js config <args>

valid args:
  --new                 : generate a new/initial configuration
`
};

function printUsage(command) {
	console.error(USAGE_HELP[command]);
}

function initConfig(cb) {
	const configPath = argv.config ? argv.config : config.getDefaultPath();

	config.init(configPath, cb);
}

function initConfigAndDatabases(cb) {
	async.series(
		[
			function init(callback) {
				initConfig(callback);
			},
			function initDb(callback) {
				db.initializeDatabases(callback);
			},
		],
		err => {
			return cb(err);
		}
	);
}

function getUser(userName, cb) {
	const user = require('./core/user.js');
	user.getUserIdAndName(argv.user, function userNameAndId(err, userId) {
		if(err) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return cb(new Error('Failed to retrieve user'));
		} else {
			let u = new user.User();
			u.userId = userId;
			return cb(null, u);
		}
	});
}

function initAndGetUser(userName, cb) {
	async.waterfall(
		[
			function init(callback) {
				initConfigAndDatabases(callback);
			},
			function getUserObject(callback) {
				getUser(argv.user, (err, user) => {
					if(err) {
						process.exitCode = ExitCodes.BAD_ARGS;
						return callback(err);
					}
					return callback(null, user);
				});
			}
		],
		(err, user) => {
			return cb(err, user);
		}
	);
}

function setAccountStatus(userName, active) {
	async.waterfall(
		[
			function init(callback) {
				initAndGetUser(argv.user, callback);
			},
			function activateUser(user, callback) {
				const AccountStatus = require('./core/user.js').User.AccountStatus;
				user.persistProperty('account_status', active ? AccountStatus.active : AccountStatus.inactive, callback);
			}
		],
		err => {
			if(err) {
				console.error(err.message);
			} else {
				console.info('User ' + ((true === active) ? 'activated' : 'deactivated'));
			}
		}
	);
}

function handleUserCommand() {
	if(true === argv.help || !_.isString(argv.user) || 0 === argv.user.length) {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('User');
	}

	if(_.isString(argv.password)) {
		if(0 === argv.password.length) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return console.error('Invalid password');
		}

		async.waterfall(
			[
				function init(callback) {
					initAndGetUser(argv.user, callback);
				},
				function setNewPass(user, callback) {
					user.setNewAuthCredentials(argv.password, function credsSet(err) {
						if(err) {
							process.exitCode = ExitCodes.ERROR;
							callback(new Error('Failed setting password'));
						} else {
							callback(null);
						}
					});
				}
			],
			function complete(err) {
				if(err) {
					console.error(err.message);
				} else {
					console.info('Password set');
				}
			}
		);
	} else if(argv.activate) {
		setAccountStatus(argv.user, true);
	} else if(argv.deactivate) {
		setAccountStatus(argv.user, false);
	}
}

function getAnswers(questions, cb) {
	inq.prompt(questions).then( answers => {
		return cb(answers);
	});
}

function getDefaultConfigPath() {
	return resolvePath('~/.config/enigma-bbs/config.hjson');
}

const QUESTIONS = {
	Intro		: [
		{
			name	: 'createNewConfig',
			message	: 'Create a new configuration?',
			type	: 'confirm',
			default	: false,
		},
		{
			name	: 'configPath',
			message	: 'Configuration path:',
			default	: argv.config ? argv.config : getDefaultConfigPath(),
			when	: answers => answers.createNewConfig
		},
	],

	OverwriteConfig	: [
		{
			name	: 'overwriteConfig',
			message	: 'Config file exists. Overwrite?',
			type	: 'confirm',
			default	: false,
		}
	],

	Basic			: [
		{
			name	: 'boardName',
			message	: 'BBS name:',
			default	: 'New ENiGMA½ BBS',
		},
	],

	Misc		: [
		{
			name	: 'loggingLevel',
			message	: 'Logging level:',
			type	: 'list',
			choices	: [ 'Error', 'Warn', 'Info', 'Debug', 'Trace' ],
			default	: 2,
			filter	: s => s.toLowerCase(),
		},
		{
			name	: 'sevenZipExe',
			message	: '7-Zip executable:',
			type	: 'list',
			choices	: [ '7z', '7za', 'None' ]
		}
	],

	MessageConfAndArea	: [
		{
			name	: 'msgConfName',
			message	: 'First message conference:',
			default	: 'Local',
		},
		{
			name	: 'msgConfDesc',
			message	: 'Conference description:',
			default	: 'Local Areas',
		},
		{
			name	: 'msgAreaName',
			message	: 'First area in message conference:',
			default	: 'General',
		},
		{
			name	: 'msgAreaDesc',
			message	: 'Area description:',
			default	: 'General chit-chat',
		}
	]
};

function makeMsgConfAreaName(s) {
	return s.toLowerCase().replace(/\s+/g, '_');
}

function askNewConfigQuestions(cb) {

	const ui = new inq.ui.BottomBar();

	let configPath;
	let config;

	async.waterfall(
		[
			function intro(callback) {
				getAnswers(QUESTIONS.Intro, answers => {
					if(!answers.createNewConfig) {
						return callback('exit');
					}

					//	adjust for ~ and the like
					configPath = resolvePath(answers.configPath);

					const configDir = paths.dirname(configPath);
					mkdirsSync(configDir);

					//
					//	Check if the file exists and can be written to
					//
					fs.access(configPath, fs.F_OK | fs.W_OK, err => {
						if(err) {
							if('EACCES' === err.code) {
								ui.log.write(`${configPath} cannot be written to`);
								callback('exit');
							} else if('ENOENT' === err.code) {
								callback(null, false);
							}
						} else {
							callback(null, true);	//	exists + writable
						}
					});
				});
			},
			function promptOverwrite(needPrompt, callback) {
				if(needPrompt) {
					getAnswers(QUESTIONS.OverwriteConfig, answers => {
						callback(answers.overwriteConfig ? null : 'exit');
					});
				} else {
					callback(null);
				}
			},
			function basic(callback) {
				getAnswers(QUESTIONS.Basic, answers => {
					config = {
						general : {
							boardName : answers.boardName,
						},
					};

					callback(null);
				});
			},
			function msgConfAndArea(callback) {
				getAnswers(QUESTIONS.MessageConfAndArea, answers => {
					config.messageConferences = {};

					const confName	= makeMsgConfAreaName(answers.msgConfName);
					const areaName	= makeMsgConfAreaName(answers.msgAreaName);

					config.messageConferences[confName] = {
						name	: answers.msgConfName,
						desc	: answers.msgConfDesc,
						sort	: 1,
						default	: true,
					};

					config.messageConferences.another_sample_conf = {
						name	: 'Another Sample Conference',
						desc	: 'Another conference example. Change me!',
						sort	: 2,
					};

					config.messageConferences[confName].areas = {};
					config.messageConferences[confName].areas[areaName] = {
						name	: answers.msgAreaName,
						desc	: answers.msgAreaDesc,
						sort	: 1,
						default	: true,
					};

					config.messageConferences.another_sample_conf = {
						areas :  {
							another_sample_area : {
								name	: 'Another Sample Area',
								desc	: 'Another area example. Change me!',
								sort	: 2
							}
						}
					};

					callback(null);
				});
			},
			function misc(callback) {
				getAnswers(QUESTIONS.Misc, answers => {
					if('None' !== answers.sevenZipExe) {
						config.archivers = {
							zip : {
								compressCmd		: answers.sevenZipExe,
								decompressCmd	: answers.sevenZipExe,
							}
						};
					}

					config.logging = {
						level : answers.loggingLevel,
					};

					callback(null);
				});
			}
		],
		err => {
			cb(err, configPath, config);
		}
	);
}

function handleConfigCommand() {
	if(true === argv.help) {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('Config');
	}

	if(argv.new) {
		askNewConfigQuestions( (err, configPath, config) => {
			if(err) {
				return;
			}

			config = hjson.stringify(config, { bracesSameLine : true, spaces : '\t' } );

			try {
				fs.writeFileSync(configPath, config, 'utf8');
				console.info('Configuration generated');
			} catch(e) {
				console.error('Exception attempting to create config: ' + e.toString());
			}
		});
	} else {
		process.exitCode = ExitCodes.ERROR;
		return printUsage('Config');
	}
}

function main() {

	process.exitCode = ExitCodes.SUCCESS;

	if(true === argv.version) {
		return console.info(require('./package.json').version);
	}

	if(0 === argv._.length ||
		'help' === argv._[0])
	{
		printUsage('General');
		process.exit(ExitCodes.SUCCESS);
	}

	switch(argv._[0]) {
		case 'user' :
			handleUserCommand();
			break;

		case 'config' :
			handleConfigCommand();
			break;

		default:
			printUsage('');
			process.exitCode = ExitCodes.BAD_COMMAND;
	}
}

main();<|endoftext|>


<commit_before>
google.load('visualization', '1', {packages:['table']});
function loadClinicalData(cancerStudyId,caseSetId) {
    var params = {cmd:'getClinicalData',
                 case_set_id:caseSetId,
                 include_free_form:1};
    $.get("webservice.do",
          params,
          function(data){
              //$('#summary').html("

"+data.replace(/^#[^\r\n]+[\r\n]+/g,"").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/[\r\n]+/g,"

").replace(/\t/g,"	")+"

");
              var rows = data.replace(/^#[^\r\n]+[\r\n]+/g,"").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/\tNA([\t\r\n])/g,"\t$1").match(/[^\r\n]+/g);
              var matrix = [];
              for (var i=0; i<rows.length; i++) {
                  matrix.push(rows[i].split('\t'));
              }

              dataTableWrapper.setDataMatrix(matrix);
              var table = new google.visualization.Table(document.getElementById('summary'));
              table.draw(dataTableWrapper.dataTable, {showRowNumber: true});
          })
}

function DataTableWrapper() {
    this.dataTable = null;
}
DataTableWrapper.prototype = {
    setDataMatrix: function(matrix) {
        var converter = new MatrixDataTypeConverter();
        converter.convertTypes(matrix);
        this.dataTable = google.visualization.arrayToDataTable(converter.dataMatrix);
        for (var i=matrix[0].length-1; i>=0; i--) {
            if (converter.isColumnNA(i)) {
                this.dataTable.removeColumn(i);
            }
        }
    }
};
var dataTableWrapper = new DataTableWrapper();

function MatrixDataTypeConverter() {
    this.dataMatrix = null;
    this.colTypes = null;
}
MatrixDataTypeConverter.prototype = {
    convertTypes: function (dataMatrix) {
        this.dataMatrix = dataMatrix;
        this.colTypes = this.determineColumnTypes(this.dataMatrix);
        var headers = this.dataMatrix[0];
        for (var c=0; c<headers.length; c++) {
            if (this.colTypes[c]=='number') {
                for (var r=1; r<this.dataMatrix.length; r++) {
                    this.dataMatrix[r][c] = parseFloat(this.dataMatrix[r][c]);
                }
            } else if (this.colTypes[c]=='boolean') {
                for (var r=1; r<this.dataMatrix.length; r++) {
                    var dl = this.dataMatrix[r][c].toLowerCase()
                    this.dataMatrix[r][c] = dl=='true' || dl=='y';
                }
            }
        }
    },
    determineColumnTypes: function (dataMatrix) {
        var rows = dataMatrix.length;
        var headers = dataMatrix[0];
        var types = [];
        var cols = headers.length;
        for (var c=0; c<cols; c++) {
            var type = headers[c].match(/_cluster$/) ? 'string' : null;
            for (var r=1; r<rows; r++) {
                if (type=='string') break;
                var d = dataMatrix[r][c];
                if (d.length==0) continue;
                if (type==null)
                    type = this.getType(d);
                else if (type!=this.getType(d))
                    type = 'string';
            }
            types.push(type);
        }
        return types;
    },
    getType: function(str) {
        if (this.isNum(str))
            return 'number';
        if (this.isBool(str))
            return 'boolean';
        return 'string';
    },
    isNum: function (str) {
        this.regex = new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$');
        return this.regex.test(str);
    },
    isBool: function (str) {
        this.regex = new RegExp('^(true)|(false)|(y)|(n)$');
        return this.regex.test(str.toLowerCase());
    },
    isColumnNA: function(col) {
        return this.colTypes[col] == null;
    }
};
<commit_msg>cancer study view: tweaks<commit_after>
google.load('visualization', '1', {packages:['table']});
function loadClinicalData(cancerStudyId,caseSetId) {
    var params = {cmd:'getClinicalData',
                 case_set_id:caseSetId,
                 include_free_form:1};
    $.get("webservice.do",
          params,
          function(data){
              //$('#summary').html("

"+data.replace(/^#[^\r\n]+[\r\n]+/g,"").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/[\r\n]+/g,"

").replace(/\t/g,"	")+"

");
              var rows = data.replace(/^#[^\r\n]+[\r\n]+/g,"").replace(/\tNA([\t\r\n])/g,"\t$1").replace(/\tNA([\t\r\n])/g,"\t$1").match(/[^\r\n]+/g);
              var matrix = [];
              for (var i=0; i<rows.length; i++) {
                  matrix.push(rows[i].split('\t'));
              }

              dataTableWrapper.setDataMatrix(matrix);
              var table = new google.visualization.Table(document.getElementById('summary'));
              table.draw(dataTableWrapper.dataTable, {showRowNumber: true});
          })
}

function DataTableWrapper() {
    this.dataTable = null;
}
DataTableWrapper.prototype = {
    setDataMatrix: function(matrix) {
        var converter = new MatrixDataTypeConverter();
        converter.convertTypes(matrix);
        this.dataTable = google.visualization.arrayToDataTable(converter.dataMatrix);
        for (var i=matrix[0].length-1; i>=0; i--) {
            if (converter.isColumnNA(i)) {
                this.dataTable.removeColumn(i);
            }
        }
    }
};
var dataTableWrapper = new DataTableWrapper();

function MatrixDataTypeConverter() {
    this.dataMatrix = null;
    this.colTypes = null;
}
MatrixDataTypeConverter.prototype = {
    convertTypes: function (dataMatrix) {
        this.dataMatrix = dataMatrix;
        this.colTypes = this.determineColumnTypes(this.dataMatrix);
        var headers = this.dataMatrix[0];
        for (var c=0; c<headers.length; c++) {
            if (this.colTypes[c]=='number') {
                for (var r=1; r<this.dataMatrix.length; r++) {
                    this.dataMatrix[r][c] = parseFloat(this.dataMatrix[r][c]);
                }
            } else if (this.colTypes[c]=='boolean') {
                for (var r=1; r<this.dataMatrix.length; r++) {
                    var dl = this.dataMatrix[r][c].toLowerCase();
                    this.dataMatrix[r][c] = dl=='true' || dl=='y';
                }
            } else if (this.colTypes[c]=='boolean') {
                for (var r=1; r<this.dataMatrix.length; r++) {
                    // hacky way to deal with empty rows
                    // the column will be removed later
                    this.dataMatrix[r][c] = " ";
                }
            }
        }
    },
    determineColumnTypes: function (dataMatrix) {
        var rows = dataMatrix.length;
        var headers = dataMatrix[0];
        var types = [];
        var cols = headers.length;
        for (var c=0; c<cols; c++) {
            var type = headers[c].match(/_cluster$/) ? 'string' : null;
            for (var r=1; r<rows; r++) {
                if (type=='string') break;
                var d = dataMatrix[r][c];
                if (d.length==0) continue;
                if (type==null)
                    type = this.getType(d);
                else if (type!=this.getType(d))
                    type = 'string';
            }
            types.push(type);
        }
        return types;
    },
    getType: function(str) {
        if (this.isNum(str))
            return 'number';
        if (this.isBool(str))
            return 'boolean';
        return 'string';
    },
    isNum: function (str) {
        this.regex = new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$');
        return this.regex.test(str);
    },
    isBool: function (str) {
        this.regex = new RegExp('^(true)|(false)|(y)|(n)$');
        return this.regex.test(str.toLowerCase());
    },
    isColumnNA: function(col) {
        return this.colTypes[col] == null;
    }
};
<|endoftext|>


<commit_before>/**
 * @fileOverview
 *
 * Perform click to specified selector on the page
 */

const Action = require('./Action');

class ActionBlur extends Action {
    async perform() {
        this.log('blur on %s', this._selector);
        const blurredCount = await this._env.evaluateJs(this._selector, /* @covignore */ function (selector) {
            const nodes = Sizzle(selector);
            for (var i = 0, l = nodes.length; i < l; i++) {
                nodes[i].blur();
            }

            return nodes.length;
        });
        this.log('blured consequently %s nodes', blurredCount);
        return result;
    }
}

module.exports = ActionBlur;
<commit_msg>- ActionBlur - coverage report fixes, returning number of blurred elements<commit_after>/**
 * @fileOverview
 *
 * Perform click to specified selector on the page
 */

const Action = require('./Action');

class ActionBlur extends Action {
    async perform() {
        this.log('blur on %s', this._selector);
        const blurredCount = await this._env.evaluateJs(this._selector, /* istanbul ignore next */ function (selector) {
            const nodes = Sizzle(selector);
            for (var i = 0, l = nodes.length; i < l; i++) {
                nodes[i].blur();
            }

            return nodes.length;
        });
        this.log('blurred consequently %s nodes', blurredCount);
        return blurredCount;
    }
}

module.exports = ActionBlur;
<|endoftext|>


<commit_before>/*global describe, it, expect, geo*/
describe('geo.sceneObject', function() {
  function CallCounter(extraData) {
    var m_this = this;
    this.ncalls = 0;
    this.call = function (evtData) {
      if (extraData !== null) {
        expect(evtData).toBe(extraData);
      }
      m_this.ncalls++;
    };
  }
  describe('Check tree operators', function () {
    it('addChild', function () {
      var parent = new geo.sceneObject(),
          children = [
            new geo.sceneObject(),
            new geo.sceneObject(),
            new geo.sceneObject()
          ];
      children.forEach(function (child) {
        parent.addChild(child);
      });

      expect(parent.parent()).toBe(null);
      parent.children().forEach(function (child, idx) {
        expect(child).toBe(children[idx]);
        expect(child.parent()).toBe(parent);
        expect(child.children().length).toBe(0);
      });
    });

    it('removeChild', function () {
      function deepCount(obj) {
        var n = 1;
        obj.children().forEach(function (child) {
          n += deepCount(child);
        });
        return n;
      }
      function spawnThree(r) {
        r.addChild(new geo.sceneObject());
        r.addChild(new geo.sceneObject());
        r.addChild(new geo.sceneObject());
      }
      var root = new geo.sceneObject(), child;
      spawnThree(root);
      expect(deepCount(root)).toBe(4);
      root.children().forEach(function (child) {
        spawnThree(child);
        child.children().forEach(spawnThree);
      });
      expect(deepCount(root)).toBe(40);

      root.removeChild(root.children()[0]);
      expect(deepCount(root)).toBe(27);

      child = root.children()[0];
      child.removeChild(child.children()[2]);
      expect(deepCount(root)).toBe(23);

      child = new geo.sceneObject();
      root.addChild(child);
      expect(deepCount(root)).toBe(24);

      root.removeChild(child);
      expect(deepCount(root)).toBe(23);

      root.children().forEach(root.removeChild);
      expect(deepCount(root)).toBe(1);
    });
  });

  describe('Check signal propagation', function () {
    function makeNode(root) {
      var child = new geo.sceneObject();
      child._handler = new CallCounter(null);
      child.count = function () {
        return child._handler.ncalls;
      };
      child.on('signal', child._handler.call);
      if (root) {
        root.addChild(child);
      }
      return child;
    }

    it('Simple tree', function () {
      var root = makeNode(),
          child = makeNode(root),
          grandchild = makeNode(child);
      function checkCounts(n) {
        expect(root.count()).toBe(n);
        expect(child.count()).toBe(n);
        expect(grandchild.count()).toBe(n);
      }
      checkCounts(0);

      root.trigger('signal');
      checkCounts(1);

      child.trigger('signal');
      checkCounts(2);

      grandchild.trigger('signal');
      checkCounts(3);
    });

    it('Shallow tree', function () {
      var root = makeNode();
      function checkCounts(n) {
        expect(root.count()).toBe(n);
        root.children().forEach(function (child) {
          expect(child.count()).toBe(n);
        });
      }

      var i, n;
      for (i = 0; i < 10; i++) {
        makeNode(root);
      }

      checkCounts(0);

      root.trigger('signal');
      checkCounts(1);

      n = 1;
      root.children().forEach(function (child) {
        child.trigger('signal');
        checkCounts(++n);
      });
    });

    it('Binary tree', function () {
      var root = makeNode(), nTrigger = 0;

      function checkCounts(root, n) {
        expect(root.count()).toBe(n);
        root.children().forEach(function (child) {
          checkCounts(child, n);
        });
      }

      function makeLevel(root, depth) {
        if (depth > 5) {
          return;
        }

        makeLevel(makeNode(root), depth + 1);
        makeLevel(makeNode(root), depth + 1);
      }

      function triggerEach(thisRoot) {
        thisRoot.trigger('signal');
        checkCounts(root, ++nTrigger);
        thisRoot.children().forEach(function (child) {
          triggerEach(child);
        });
      }

      makeLevel(root, 0);
      checkCounts(root, 0);

      triggerEach(root);
    });

    it('Stop propagation', function () {
      var root, child1, child2, child2Called = false;
      root = geo.sceneObject();
      child1 = geo.sceneObject();
      child2 = geo.sceneObject();

      root.addChild(child1);
      child1.addChild(child2);

      child2.on('signal', function () {
        child2Called = true;
      });
      root.trigger('signal');

      expect(child2Called).toBe(true);

      child1.on('signal', function (args) {
        args.geo.stopPropagation = true;
      });

      child2Called = false;
      root.trigger('signal');

      expect(child2Called).toBe(false);
    });

    it('Children only', function () {
      var root, child1, child2, child1Called = false, child2Called = false, rootCalled = false;
      root = geo.sceneObject();
      child1 = geo.sceneObject();
      child2 = geo.sceneObject();

      root.addChild(child1);
      child1.addChild(child2);

      root.on('signal', function () {
        rootCalled = true;
      });
      child1.on('signal', function () {
        child1Called = true;
      });
      child2.on('signal', function () {
        child2Called = true;
      });
      child1.trigger('signal', {}, true);

      expect(child1Called).toBe(true);
      expect(child2Called).toBe(true);
      expect(rootCalled).toBe(false);
    });
  });
});
<commit_msg>adding tests for sceneObject.onIdle<commit_after>/*global describe, it, expect, geo*/
describe('geo.sceneObject', function() {
  'use strict';

  function CallCounter(extraData) {
    var m_this = this;
    this.ncalls = 0;
    this.call = function (evtData) {
      if (extraData !== null) {
        expect(evtData).toBe(extraData);
      }
      m_this.ncalls++;
    };
  }
  describe('Check tree operators', function () {
    it('addChild', function () {
      var parent = new geo.sceneObject(),
          children = [
            new geo.sceneObject(),
            new geo.sceneObject(),
            new geo.sceneObject()
          ];
      children.forEach(function (child) {
        parent.addChild(child);
      });

      expect(parent.parent()).toBe(null);
      parent.children().forEach(function (child, idx) {
        expect(child).toBe(children[idx]);
        expect(child.parent()).toBe(parent);
        expect(child.children().length).toBe(0);
      });
    });

    it('removeChild', function () {
      function deepCount(obj) {
        var n = 1;
        obj.children().forEach(function (child) {
          n += deepCount(child);
        });
        return n;
      }
      function spawnThree(r) {
        r.addChild(new geo.sceneObject());
        r.addChild(new geo.sceneObject());
        r.addChild(new geo.sceneObject());
      }
      var root = new geo.sceneObject(), child;
      spawnThree(root);
      expect(deepCount(root)).toBe(4);
      root.children().forEach(function (child) {
        spawnThree(child);
        child.children().forEach(spawnThree);
      });
      expect(deepCount(root)).toBe(40);

      root.removeChild(root.children()[0]);
      expect(deepCount(root)).toBe(27);

      child = root.children()[0];
      child.removeChild(child.children()[2]);
      expect(deepCount(root)).toBe(23);

      child = new geo.sceneObject();
      root.addChild(child);
      expect(deepCount(root)).toBe(24);

      root.removeChild(child);
      expect(deepCount(root)).toBe(23);

      root.children().forEach(root.removeChild);
      expect(deepCount(root)).toBe(1);
    });
  });

  describe('Check signal propagation', function () {
    function makeNode(root) {
      var child = new geo.sceneObject();
      child._handler = new CallCounter(null);
      child.count = function () {
        return child._handler.ncalls;
      };
      child.on('signal', child._handler.call);
      if (root) {
        root.addChild(child);
      }
      return child;
    }

    it('Simple tree', function () {
      var root = makeNode(),
          child = makeNode(root),
          grandchild = makeNode(child);
      function checkCounts(n) {
        expect(root.count()).toBe(n);
        expect(child.count()).toBe(n);
        expect(grandchild.count()).toBe(n);
      }
      checkCounts(0);

      root.trigger('signal');
      checkCounts(1);

      child.trigger('signal');
      checkCounts(2);

      grandchild.trigger('signal');
      checkCounts(3);
    });

    it('Shallow tree', function () {
      var root = makeNode();
      function checkCounts(n) {
        expect(root.count()).toBe(n);
        root.children().forEach(function (child) {
          expect(child.count()).toBe(n);
        });
      }

      var i, n;
      for (i = 0; i < 10; i++) {
        makeNode(root);
      }

      checkCounts(0);

      root.trigger('signal');
      checkCounts(1);

      n = 1;
      root.children().forEach(function (child) {
        child.trigger('signal');
        checkCounts(++n);
      });
    });

    it('Binary tree', function () {
      var root = makeNode(), nTrigger = 0;

      function checkCounts(root, n) {
        expect(root.count()).toBe(n);
        root.children().forEach(function (child) {
          checkCounts(child, n);
        });
      }

      function makeLevel(root, depth) {
        if (depth > 5) {
          return;
        }

        makeLevel(makeNode(root), depth + 1);
        makeLevel(makeNode(root), depth + 1);
      }

      function triggerEach(thisRoot) {
        thisRoot.trigger('signal');
        checkCounts(root, ++nTrigger);
        thisRoot.children().forEach(function (child) {
          triggerEach(child);
        });
      }

      makeLevel(root, 0);
      checkCounts(root, 0);

      triggerEach(root);
    });

    it('Stop propagation', function () {
      var root, child1, child2, child2Called = false;
      root = geo.sceneObject();
      child1 = geo.sceneObject();
      child2 = geo.sceneObject();

      root.addChild(child1);
      child1.addChild(child2);

      child2.on('signal', function () {
        child2Called = true;
      });
      root.trigger('signal');

      expect(child2Called).toBe(true);

      child1.on('signal', function (args) {
        args.geo.stopPropagation = true;
      });

      child2Called = false;
      root.trigger('signal');

      expect(child2Called).toBe(false);
    });

    it('Children only', function () {
      var root, child1, child2, child1Called = false, child2Called = false, rootCalled = false;
      root = geo.sceneObject();
      child1 = geo.sceneObject();
      child2 = geo.sceneObject();

      root.addChild(child1);
      child1.addChild(child2);

      root.on('signal', function () {
        rootCalled = true;
      });
      child1.on('signal', function () {
        child1Called = true;
      });
      child2.on('signal', function () {
        child2Called = true;
      });
      child1.trigger('signal', {}, true);

      expect(child1Called).toBe(true);
      expect(child2Called).toBe(true);
      expect(rootCalled).toBe(false);
    });
  });
  describe('Check onIdle handlers', function () {
    var root = geo.sceneObject(),
        child1 = geo.sceneObject(),
        child2 = geo.sceneObject(),
        child3 = geo.sceneObject();

    root.addChild(child1);
    root.addChild(child2);
    child2.addChild(child3);

    it('child defers to parent', function () {
      var defer = $.Deferred(),
          handlerRoot = new CallCounter(null),
          handler1 = new CallCounter(null),
          handler2 = new CallCounter(null),
          handler3 = new CallCounter(null);

      function checkCallCount(count) {
        expect(handlerRoot.ncalls).toBe(count);
        expect(handler1.ncalls).toBe(count);
        expect(handler2.ncalls).toBe(count);
        expect(handler3.ncalls).toBe(count);
      }

      child3.addDeferred(defer);
      root.onIdle(handlerRoot.call);
      child1.onIdle(handler1.call);
      child2.onIdle(handler2.call);
      child3.onIdle(handler3.call);

      checkCallCount(0);

      defer.resolve();

      checkCallCount(1);

      defer = $.Deferred();
      child3.addDeferred(defer);

      checkCallCount(1);

      defer.resolve();

      checkCallCount(1);

      root.onIdle(handlerRoot.call);
      child1.onIdle(handler1.call);
      child2.onIdle(handler2.call);
      child3.onIdle(handler3.call);

      checkCallCount(2);
    });

    it('aysnchronous events from multiple children', function (done) {
      window.setTimeout(function () {
        var defer = $.Deferred();
        child1.addDeferred(defer);

        window.setTimeout(function () {
          defer.resolve();
        }, 100);
      }, 0);
      window.setTimeout(function () {
        var defer = $.Deferred();
        child2.addDeferred(defer);

        window.setTimeout(function () {
          defer.resolve();
        }, 200);
      }, 0);
      window.setTimeout(function () {
        var defer = $.Deferred();
        child3.addDeferred(defer);

        window.setTimeout(function () {
          defer.resolve();
        }, 40);
      }, 10);

      window.setTimeout(function () {
        var handler = new CallCounter(null);
        root.onIdle(handler.call);
        expect(handler.ncalls).toBe(0);
        window.setTimeout(function () {
          expect(handler.ncalls).toBe(1);
          done();
        }, 400);
      }, 50);

    });
  });
});
<|endoftext|>