<commit_before>/*
Copyright 2016 Google Inc.

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.
*/
/*jshint esversion: 6*/

var app = (function() {

  function getImageName(country) {
    country = country.toLowerCase();
    var promiseOfImageName = new Promise(function(resolve, reject) {
      setTimeout(function() {
        if (country === 'spain' || country === 'chile' || country === 'peru') {
          resolve(country + '.png');
        } else {
          reject(Error('Didn\'t receive a valid country name!'));
        }
      }, 1000);
    });
    console.log(promiseOfImageName);
    return promiseOfImageName;
  }

  function isSpain(country) {
    return new Promise(function(resolve, reject) {
      if (country === 'Spain') {
        resolve('It is Spain!');
      } else {
        reject('It is not Spain!');
      }
    });
  }

  function flagChain(country) {
    return getImageName(country)
    .catch(fallbackName)
    .then(fetchFlag)
    .then(processFlag)
    .then(appendFlag)
    .catch(logError);
  }

  function spainTest(country) {
    return isSpain(country)
    .then(returnTrue)
    .catch(returnFalse);
  }

  function allFlags(promiseList) {
    return Promise.all(promiseList)
    .catch(returnFalse);
  }

  var promises = [
    getImageName('Spain'),
    getImageName('Chile'),
    getImageName('Peru')
  ];
  allFlags(promises).then(function(result) {
    console.log(result);
  });

  var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
  });

  var promise2 = new Promise(function(resolve, reject) {
    setTimeout(reject, 100, 'two');
  });

  Promise.race([promise1, promise2])
  .then(logSuccess)
  .catch(logError);

  /* Helper functions */

  function logSuccess(result) {
    console.log('Success!:\n' + result);
  }

  function logError(err) {
    console.log('Oh no!:\n' + err);
  }

  function returnTrue() {
    return true;
  }

  function returnFalse() {
    return false;
  }

  function fetchFlag(imageName) {
    return fetch('flags/' + imageName); // fetch returns a promise
  }

  function processFlag(flagResponse) {
    if (!flagResponse.ok) {
      throw Error('Bad response for flag request!'); // This will implicitly reject
    }
    return flagResponse.blob(); // blob() returns a promise
  }

  function appendFlag(flagBlob) {
    var flagImage = document.createElement('img');
    var flagDataURL = URL.createObjectURL(flagBlob);
    flagImage.src = flagDataURL;
    document.body.appendChild(flagImage);
  }

  function fallbackName() {
    return 'chile.png';
  }

  // Don't worry if you don't understand this, it's not part of Promises.
  // We are using the JavaScript Module Pattern to enable unit testing of
  // our functions.
  return {
    getImageName: (getImageName),
    flagChain: (flagChain),
    isSpain: (isSpain),
    spainTest: (spainTest),
    fetchFlag: (fetchFlag),
    processFlag: (processFlag),
    appendFlag: (appendFlag),
    allFlags: (allFlags)
  };

})();
<commit_msg>update(promises-lab): convert solution code to ES6<commit_after>/*
Copyright 2016 Google Inc.

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.
*/
/*jshint esversion: 6*/

const app = (() => {

  function getImageName(country) {
    country = country.toLowerCase();
    const promiseOfImageName = new Promise((resolve, reject) => {
      setTimeout(() => {
        if (country === 'spain' || country === 'chile' || country === 'peru') {
          resolve(country + '.png');
        } else {
          reject(Error('Didn\'t receive a valid country name!'));
        }
      }, 1000);
    });
    console.log(promiseOfImageName);
    return promiseOfImageName;
  }

  function isSpain(country) {
    return new Promise((resolve, reject) => {
      if (country === 'Spain') {
        resolve('It is Spain!');
      } else {
        reject('It is not Spain!');
      }
    });
  }

  function flagChain(country) {
    return getImageName(country)
    .catch(fallbackName)
    .then(fetchFlag)
    .then(processFlag)
    .then(appendFlag)
    .catch(logError);
  }

  function spainTest(country) {
    return isSpain(country)
    .then(returnTrue)
    .catch(returnFalse);
  }

  function allFlags(promiseList) {
    return Promise.all(promiseList)
    .catch(returnFalse);
  }

  const promises = [
    getImageName('Spain'),
    getImageName('Chile'),
    getImageName('Peru')
  ];
  allFlags(promises).then(result => {
    console.log(result);
  });

  const promise1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 500, 'one');
  });

  const promise2 = new Promise((resolve, reject) => {
    setTimeout(reject, 100, 'two');
  });

  Promise.race([promise1, promise2])
  .then(logSuccess)
  .catch(logError);

  /* Helper functions */

  function logSuccess(result) {
    console.log('Success!:\n' + result);
  }

  function logError(err) {
    console.log('Oh no!:\n' + err);
  }

  function returnTrue() {
    return true;
  }

  function returnFalse() {
    return false;
  }

  function fetchFlag(imageName) {
    return fetch('flags/' + imageName); // fetch returns a promise
  }

  function processFlag(flagResponse) {
    if (!flagResponse.ok) {
      throw Error('Bad response for flag request!'); // This will implicitly reject
    }
    return flagResponse.blob(); // blob() returns a promise
  }

  function appendFlag(flagBlob) {
    const flagImage = document.createElement('img');
    const flagDataURL = URL.createObjectURL(flagBlob);
    flagImage.src = flagDataURL;
    document.body.appendChild(flagImage);
  }

  function fallbackName() {
    return 'chile.png';
  }

  // Don't worry if you don't understand this, it's not part of Promises.
  // We are using the JavaScript Module Pattern to enable unit testing of
  // our functions.
  return {
    getImageName: (getImageName),
    flagChain: (flagChain),
    isSpain: (isSpain),
    spainTest: (spainTest),
    fetchFlag: (fetchFlag),
    processFlag: (processFlag),
    appendFlag: (appendFlag),
    allFlags: (allFlags)
  };

})();
<|endoftext|>


<commit_before>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(
  [ 'hft/misc/misc',
    '../bower_components/hft-utils/dist/imageutils',
    '../bower_components/tdl/tdl/fast',
    '../bower_components/tdl/tdl/math',
    '../bower_components/tdl/tdl/particles',
    '../bower_components/tdl/tdl/textures',
  ], function(
    Misc,
    ImageUtils,
    Fast,
    Maths,
    Particles,
    Textures) {

  var maxConfetti = 10;
  var onePixelTexture;
  var snowFlakeTexture;
  var ghostsTexture;
  var rainTexture;

  var setup = function(services) {
    if (!onePixelTexture) {
      onePixelTexture = new Textures.SolidTexture([255,255,255,255]);
      var c = document.createElement("canvas");
      var ctx = c.getContext("2d");
      c.width = 32;
      c.height = 32;
      for (var ii = 0; ii < 6; ++ii) {
        ctx.save();
        ctx.translate(c.width / 2, c.height / 2);
        ctx.rotate(ii / 6 * Math.PI * 2);
        ctx.translate(c.width / 4, 0);
        ctx.beginPath();
        ctx.arc(0, 0, c.width / 6, 0, Math.PI * 2, true);
        ctx.strokeStyle = "white";
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.restore();
      }
      snowFlakeTexture = new Textures.Texture2D(c);
      ctx.clearRect(0, 0, c.width, c.height);
      ctx.beginPath();
      ctx.moveTo(c.width / 2, 4);
      ctx.lineTo(c.width / 2, c.height - 1);
      ctx.strokeStyle = "white";
      ctx.stroke();
      rainTexture = new Textures.Texture2D(c);
      ghostsTexture = services.images.ghosts.frames[0];
    }
  };

  var createConfetti = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(onePixelTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    emitter.setColorRamp(
        [1, 1, 1, 1]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 1.0,
        //timeRange: 0.0,
        startSize: 7.0,
        endSize: 7.0,
        spinSpeedRange: Math.PI * 4},
        function(index, parameters) {
            var speed = Math.random() * 25 + 5;
            var angle = Math.random() * 2 * Math.PI;
            var color = ImageUtils.hsvToRgb(Math.random(), 0.7, 1);
            parameters.startTime = Math.random() * 0.2;
            parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [0, 0, 0])
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
            parameters.acceleration = Maths.addVector(Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]), [0, 100, 0]);
        });
    return tdl.particles.createOneShotManager(emitter, maxConfetti);
  };

  var createBallConfetti = function(particleSystemManager, hue) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(onePixelTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    emitter.setColorRamp(
        [1, 1, 1, 1]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 1.0,
        //timeRange: 0.0,
        startSize: 7.0,
        endSize: 7.0,
        spinSpeedRange: Math.PI * 4},
        function(index, parameters) {
            var speed = Math.random() * 25 + 5;
            var angle = Math.random() * 2 * Math.PI;
            var color = ImageUtils.hsvToRgb(hue, Math.random() * 0.5 + 0.5, 1);
            parameters.startTime = Math.random() * 0.2;
            parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [0, 0, 0])
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
            parameters.acceleration = Maths.addVector(Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]), [0, 100, 0]);
        });
    return tdl.particles.createOneShotManager(emitter, maxConfetti);
  };

  var createSnow = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterBehindLevel(snowFlakeTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    emitter.setColorRamp(
        [0.8, 0.9, 1, 0.0,
         0.8, 0.9, 1, 0.3,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.3,
         0.8, 0.9, 1, 0.0]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 2.0,
        timeRange: 2.0,
        startSize: 17.0,
        endSize: 17.0,
        spinSpeedRange: Math.PI},
        function(index, parameters) {
            var speed = Math.random() * 1 + 3;
            var angle = (Math.random() * 0.2 + 0.4) * Math.PI;
            //var color = ImageUtils.hsvToRgb(hue, Math.random() * 0.5 + 0.5, 1);
            //parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position =  [Misc.randInt(1280), Misc.randInt(720) - 32, 0];
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
//            parameters.acceleration = Maths.matrix4.transformPoint(
//                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]));
        });
    return emitter;
  };

  var createGhosts = function(particleSystemManager, services) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(ghostsTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.SUBTRACT);
    emitter.setColorRamp(
        [0.8, 0.9, 1, 0.0,
         0.8, 0.9, 1, 0.2,
         0.8, 0.9, 1, 0.4,
         0.8, 0.9, 1, 0.6,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.3,
         0.8, 0.9, 1, 0.0]);
    var timeRange = 50;
    emitter.setParameters({
        numFrames: 4,
        numParticles: 20,
        frameDuration: timeRange,
        lifeTime: 2.0,
        timeRange: timeRange,
        startSize: 32.0,
        endSize: 256.0,
        spinSpeedRange:  Math.PI * 0},
        function(index, parameters) {
            parameters.startTime  = Math.random() * timeRange;
            parameters.frameStart = Misc.randInt(4);
            var speed = Math.random() * 1 + 3;
            var angle = Math.random() * 0.4 + -0.2;
            parameters.spinStart = angle;
            angle += Math.PI / 2 + (Math.random() > 0.5 ? 0 : Math.PI);
            parameters.position =  [Misc.randInt(1280), Misc.randInt(720) - 32, 0];
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
        });
    return emitter;
  };

  var createRain = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterBehindLevel(rainTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    var timeRange = 1;
    var angle = Math.PI * 0.6;
    emitter.setParameters({
        numParticles: 100,
        lifeTime: 1.0,
        timeRange: 1.0,
        startSize: 32.0,
        endSize: 32.0,
      },
      function(index, parameters) {
        parameters.spinStart = angle + Math.PI / 16 * 5.0;
        var speed = Math.random() * 10 + 50;
        parameters.position =  [Misc.randInt(1280) + 100, -32, 0];
        parameters.velocity = Maths.matrix4.transformPoint(
            Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
        });
    return emitter;
  };

  var ParticleEffectManager = function(services) {
    setup(services);
    this.services = services;
    this.confettis = createConfetti(services.particleSystemManager);
    this.ballRedConfetti = createBallConfetti(services.particleSystemManager, 0);
    this.ballBlueConfetti = createBallConfetti(services.particleSystemManager, 0.666);
  };

  ParticleEffectManager.prototype.spawnConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.confettis.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.spawnBallRedConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.ballRedConfetti.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.spawnBallBlueConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.ballBlueConfetti.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.createSnow = function() {
    createSnow(this.services.particleSystemManager);
  };

  ParticleEffectManager.prototype.createGhosts = function() {
    createGhosts(this.services.particleSystemManager);
  };

  ParticleEffectManager.prototype.createRain = function() {
    createRain(this.services.particleSystemManager);
  };

  return ParticleEffectManager;
});

<commit_msg>adjust snow for new background<commit_after>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(
  [ 'hft/misc/misc',
    '../bower_components/hft-utils/dist/imageutils',
    '../bower_components/tdl/tdl/fast',
    '../bower_components/tdl/tdl/math',
    '../bower_components/tdl/tdl/particles',
    '../bower_components/tdl/tdl/textures',
  ], function(
    Misc,
    ImageUtils,
    Fast,
    Maths,
    Particles,
    Textures) {

  var maxConfetti = 10;
  var onePixelTexture;
  var snowFlakeTexture;
  var ghostsTexture;
  var rainTexture;

  var setup = function(services) {
    if (!onePixelTexture) {
      onePixelTexture = new Textures.SolidTexture([255,255,255,255]);
      var c = document.createElement("canvas");
      var ctx = c.getContext("2d");
      c.width = 32;
      c.height = 32;
      for (var ii = 0; ii < 6; ++ii) {
        ctx.save();
        ctx.translate(c.width / 2, c.height / 2);
        ctx.rotate(ii / 6 * Math.PI * 2);
        ctx.translate(c.width / 4, 0);
        ctx.beginPath();
        ctx.arc(0, 0, c.width / 6, 0, Math.PI * 2, true);
        ctx.strokeStyle = "white";
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.restore();
      }
      snowFlakeTexture = new Textures.Texture2D(c);
      ctx.clearRect(0, 0, c.width, c.height);
      ctx.beginPath();
      ctx.moveTo(c.width / 2, 4);
      ctx.lineTo(c.width / 2, c.height - 1);
      ctx.strokeStyle = "white";
      ctx.stroke();
      rainTexture = new Textures.Texture2D(c);
      ghostsTexture = services.images.ghosts.frames[0];
    }
  };

  var createConfetti = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(onePixelTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    emitter.setColorRamp(
        [1, 1, 1, 1]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 1.0,
        //timeRange: 0.0,
        startSize: 7.0,
        endSize: 7.0,
        spinSpeedRange: Math.PI * 4},
        function(index, parameters) {
            var speed = Math.random() * 25 + 5;
            var angle = Math.random() * 2 * Math.PI;
            var color = ImageUtils.hsvToRgb(Math.random(), 0.7, 1);
            parameters.startTime = Math.random() * 0.2;
            parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [0, 0, 0])
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
            parameters.acceleration = Maths.addVector(Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]), [0, 100, 0]);
        });
    return tdl.particles.createOneShotManager(emitter, maxConfetti);
  };

  var createBallConfetti = function(particleSystemManager, hue) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(onePixelTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    emitter.setColorRamp(
        [1, 1, 1, 1]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 1.0,
        //timeRange: 0.0,
        startSize: 7.0,
        endSize: 7.0,
        spinSpeedRange: Math.PI * 4},
        function(index, parameters) {
            var speed = Math.random() * 25 + 5;
            var angle = Math.random() * 2 * Math.PI;
            var color = ImageUtils.hsvToRgb(hue, Math.random() * 0.5 + 0.5, 1);
            parameters.startTime = Math.random() * 0.2;
            parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [0, 0, 0])
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
            parameters.acceleration = Maths.addVector(Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]), [0, 100, 0]);
        });
    return tdl.particles.createOneShotManager(emitter, maxConfetti);
  };

  var createSnow = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterBehindLevel(snowFlakeTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.ADD);
    emitter.setColorRamp(
        [0.8, 0.9, 1, 0.0,
         0.8, 0.9, 1, 0.2,
         0.8, 0.9, 1, 0.4,
         0.8, 0.9, 1, 0.4,
         0.8, 0.9, 1, 0.2,
         0.8, 0.9, 1, 0.0]);
    emitter.setParameters({
        numParticles: 200,
        lifeTime: 2.0,
        timeRange: 2.0,
        startSize: 17.0,
        endSize: 17.0,
        spinSpeedRange: Math.PI},
        function(index, parameters) {
            var speed = Math.random() * 1 + 3;
            var angle = (Math.random() * 0.2 + 0.4) * Math.PI;
            //var color = ImageUtils.hsvToRgb(hue, Math.random() * 0.5 + 0.5, 1);
            //parameters.colorMult = [color[0] / 255, color[1] / 255, color[2] / 255, 1];
            parameters.position =  [Misc.randInt(1280), Misc.randInt(720) - 32, 0];
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
//            parameters.acceleration = Maths.matrix4.transformPoint(
//                Maths.matrix4.rotationZ(angle), [-speed * 8, 0, 0]));
        });
    return emitter;
  };

  var createGhosts = function(particleSystemManager, services) {
    var emitter = particleSystemManager.createParticleEmitterInFrontOfPlayer(ghostsTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.SUBTRACT);
    emitter.setColorRamp(
        [0.8, 0.9, 1, 0.0,
         0.8, 0.9, 1, 0.2,
         0.8, 0.9, 1, 0.4,
         0.8, 0.9, 1, 0.6,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.9,
         0.8, 0.9, 1, 0.3,
         0.8, 0.9, 1, 0.0]);
    var timeRange = 50;
    emitter.setParameters({
        numFrames: 4,
        numParticles: 20,
        frameDuration: timeRange,
        lifeTime: 2.0,
        timeRange: timeRange,
        startSize: 32.0,
        endSize: 256.0,
        spinSpeedRange:  Math.PI * 0},
        function(index, parameters) {
            parameters.startTime  = Math.random() * timeRange;
            parameters.frameStart = Misc.randInt(4);
            var speed = Math.random() * 1 + 3;
            var angle = Math.random() * 0.4 + -0.2;
            parameters.spinStart = angle;
            angle += Math.PI / 2 + (Math.random() > 0.5 ? 0 : Math.PI);
            parameters.position =  [Misc.randInt(1280), Misc.randInt(720) - 32, 0];
            parameters.velocity = Maths.matrix4.transformPoint(
                Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
        });
    return emitter;
  };

  var createRain = function(particleSystemManager) {
    var emitter = particleSystemManager.createParticleEmitterBehindLevel(rainTexture.texture);
    emitter.setState(tdl.particles.ParticleStateIds.BLEND);
    var timeRange = 1;
    var angle = Math.PI * 0.6;
    emitter.setParameters({
        numParticles: 100,
        lifeTime: 1.0,
        timeRange: 1.0,
        startSize: 32.0,
        endSize: 32.0,
      },
      function(index, parameters) {
        parameters.spinStart = angle + Math.PI / 16 * 5.0;
        var speed = Math.random() * 10 + 50;
        parameters.position =  [Misc.randInt(1280) + 100, -32, 0];
        parameters.velocity = Maths.matrix4.transformPoint(
            Maths.matrix4.rotationZ(angle), [speed * 20, 0, 0]);
        });
    return emitter;
  };

  var ParticleEffectManager = function(services) {
    setup(services);
    this.services = services;
    this.confettis = createConfetti(services.particleSystemManager);
    this.ballRedConfetti = createBallConfetti(services.particleSystemManager, 0);
    this.ballBlueConfetti = createBallConfetti(services.particleSystemManager, 0.666);
  };

  ParticleEffectManager.prototype.spawnConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.confettis.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.spawnBallRedConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.ballRedConfetti.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.spawnBallBlueConfetti = function(x, y) {
    var _tp_ = tdl.fast.matrix4.translation(new Float32Array(16), [x, y, 0]);
    this.ballBlueConfetti.startOneShot(_tp_);
  };

  ParticleEffectManager.prototype.createSnow = function() {
    createSnow(this.services.particleSystemManager);
  };

  ParticleEffectManager.prototype.createGhosts = function() {
    createGhosts(this.services.particleSystemManager);
  };

  ParticleEffectManager.prototype.createRain = function() {
    createRain(this.services.particleSystemManager);
  };

  return ParticleEffectManager;
});

<|endoftext|>


<commit_before>/**
 * @providesModule PLApp
 * @flow
 */

'use strict';

var React = require('React');
var AppState = require('AppState');
var Platform = require('Platform');
var LoginScene = require('./scenes/auth/LoginScene');
var StyleSheet = require('StyleSheet');
var PLNavigator = require('PLNavigator');
var View = require('View');
var StatusBar = require('StatusBar');
var SplashScreen = require('react-native-splash-screen');
var { connect } = require('react-redux');
var { version } = require('./PLEnv.js');

var PLApp = React.createClass({
  displayName: 'PLApp',
  componentDidMount: function () {
    if (Platform.OS === 'android') {
      SplashScreen.hide();
    }
    AppState.addEventListener('change', this.handleAppStateChange);
  },

  componentWillUnmount: function () {
    AppState.removeEventListener('change', this.handleAppStateChange);
  },

  handleAppStateChange: function (appState) {
    if (appState === 'active') {
    }
  },

  render: function () {
    if (!this.props.isLoggedIn) {
      return <LoginScene />;
    }
    return (
      <View style={styles.container}>
        <StatusBar
          translucent={true}
          backgroundColor="rgba(0, 0, 0, 0.2)"
          barStyle="light-content"
        />
        <PLNavigator />
      </View>
    );
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

function select(store) {
  return {
    isLoggedIn: store.user.isLoggedIn,
  };
}

module.exports = connect(select)(PLApp);
<commit_msg>issue #4 - add stack navigation for login flow  * different header title for terms and policy buttons<commit_after>/**
 * @providesModule PLApp
 * @flow
 */

'use strict';

var React = require('React');
var AppState = require('AppState');
var Platform = require('Platform');
var LoginScene = require('./scenes/auth/LoginScene');
var TermsPolicyScene = require('./scenes/auth/TermsPolicyScene');
var StyleSheet = require('StyleSheet');
var PLNavigator = require('PLNavigator');
var View = require('View');
var StatusBar = require('StatusBar');
var SplashScreen = require('react-native-splash-screen');
var { connect } = require('react-redux');
var { version } = require('./PLEnv.js');
var { StackNavigator } = require('react-navigation');

var PLApp = React.createClass({
  displayName: 'PLApp',
  componentDidMount: function () {
    if (Platform.OS === 'android') {
      SplashScreen.hide();
    }
    AppState.addEventListener('change', this.handleAppStateChange);
  },

  componentWillUnmount: function () {
    AppState.removeEventListener('change', this.handleAppStateChange);
  },

  handleAppStateChange: function (appState) {
    if (appState === 'active') {
    }
  },

  render: function () {
    if (!this.props.isLoggedIn) {
      return <LoginStack />;
    }
    return (
      <View style={styles.container}>
        <StatusBar
          translucent={true}
          backgroundColor="rgba(0, 0, 0, 0.2)"
          barStyle="light-content"
        />
        <PLNavigator />
      </View>
    );
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

var LoginStack = StackNavigator({
  initialRouteName: { screen: LoginScene },
  Login: { screen: LoginScene },
  TermsAndPolicy: { screen: TermsPolicyScene },
});

TermsPolicyScene.navigationOptions = props => {
  var { navigation } = props;
  var { state, setParams } = navigation;
  var { params } = state;
  var navTitle = (params.isTerms === true) ? 'Terms of Service' : 'Privacy Policy';
  return {
    headerTitle: `${navTitle}`,
  };
};

function select(store) {
  return {
    isLoggedIn: store.user.isLoggedIn,
  };
}

module.exports = connect(select)(PLApp);
<|endoftext|>


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

var repl = require('../lib/repl.js');

var argv = require('optimist')
  .boolean('v').describe('v', 'verbose')
  .argv;

argv.eval = function(cmd, context, filename, callback) {
  callback(null, 'foo');
}

repl.start(argv, function(mesh){
  mesh.router(true);
  mesh.discover(true);
  mesh.accept = mesh.link; // auto-link any

  mesh.rlog('chat:',mesh.uri());

});<commit_msg>join chat<commit_after>#!/usr/bin/env node

var repl = require('../lib/repl.js');

var argv = require('optimist')
  .boolean('v').describe('v', 'verbose')
  .describe('nick', 'nickname')
  .argv;

argv.eval = function(cmd, context, filename, callback) {
  callback(null, 'foo');
}

repl.start(argv, function(mesh){
  mesh.router(true);
  mesh.discover(true);
  mesh.accept = mesh.link; // auto-link any

  // create a chat
  var args = argv._[0] || {}; // from given uri, or blank
  mesh.chat(args, function(err, chat){
    if(err) return mesh.rlog('err',err);
    chat.join(argv.nick,function(err){
      if(argv._[0]) mesh.rlog('joined');
      else mesh.rlog('invite others with',mesh.uri({protocol:'chat',token:chat.id}));
    });
  });

});<|endoftext|>


<commit_before>'use strict';

var qs = require('qs');
var Promise = require('promise');

/**
 * Core application
 *
 * @returns {CoreApplication}
 * @constructor
 */
function CoreApplication() {
  var preHookList = [];
  var postHookList = [];
  var routers = [];

  /**
   * Method that receive all http requests
   * @param request
   * @param response
   * @returns {Promise}
   */
  this.requestListener = function (request, response) {
    return Promise.resolve()
      .then(postDecode.bind(this, request))
      .then(runHooks.bind(this, request, response, preHookList))
      .then(dispatch.bind(this, request, response))
      .then(runHooks.bind(this, request, response, postHookList))
      .then(endResponse.bind(this, response))
      .catch(this.onError.bind(this, request, response));
  };

  /**
   * Add router to resolve uri
   * @param router
   * @returns {CoreApplication}
   */
  this.addRouter = function (router) {
    routers.push(router);
    return this;
  };

  /**
   * Add hook before calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPreHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    preHookList.push(callableHook);
    return this;
  };

  /**
   * Add hook after calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPostHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    postHookList.push(callableHook);
    return this;
  };

  /**
   * If page not found
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onPageNotFound = function (request, response, error) {
    console.log(error);
    response.writeHead(404);
    response.end();
    return this;
  };

  /**
   * If an error occured
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onError = function (request, response, error) {
    console.error(error);
    response.writeHead(503);
    response.end();
    return this;
  };

  return this;

  /**
   * Dispatch request in good action using routers
   * @param request
   * @param response
   * @returns {Promise}
   */
  function dispatch(request, response) {
    return Promise.resolve()
      .then(resolveRouters.bind(this, request))
      .then(callAction.bind(this, request, response))
      .catch(this.onPageNotFound.bind(this, request, response));
  }

  /**
   * Resolve uri using routers
   * @param request
   * @returns {Promise}
   */
  function resolveRouters(request) {
    for (var i = 0, l = routers.length; i < l; i++) {
      var callback = routers[i].resolve(request);
      if (null != callback) {
        return Promise.resolve(callback);
      }
    }
    return Promise.reject('Route not defined for "' + request.url + '"');
  }

  /**
   * Call action and method form resolved route
   * @param request
   * @param response
   * @param callback
   * @returns {*}
   */
  function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      return Promise.reject('Action ' + callback.action + ' does not exist.');
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }

  /**
   * Decode post data and add input into request
   * @param request
   * @returns {Promise}
   */
  function postDecode(request) {
    return new Promise(function promisePostDecode(resolve) {
      var postData = '';
      if (request.method === 'POST') {
        request.on('data', function (chunk) {
          // append the current chunk of data to the fullBody variable
          postData += chunk.toString();
        });

        request.on('end', function () {
          request.body = qs.parse(postData);
          resolve();
        });

      } else {
        resolve();
      }
    });
  }

  /**
   * Run given hooks
   * @param request
   * @param response
   * @param hooks
   * @returns {Promise}
   */
  function runHooks(request, response, hooks) {
    var promise = Promise.resolve();
    for (var i = 0; i < hooks.length; i++) {
      promise = promise.then(hooks[i].bind(this, request, response));
    }
    return promise;
  }

  /**
   * Finalize response
   * @param response
   */
  function endResponse(response) {
    response.end();
  }
}

module.exports = CoreApplication;<commit_msg>Fix bug when catching missing action<commit_after>'use strict';

var qs = require('qs');
var Promise = require('promise');

/**
 * Core application
 *
 * @returns {CoreApplication}
 * @constructor
 */
function CoreApplication() {
  var preHookList = [];
  var postHookList = [];
  var routers = [];

  /**
   * Method that receive all http requests
   * @param request
   * @param response
   * @returns {Promise}
   */
  this.requestListener = function (request, response) {
    return Promise.resolve()
      .then(postDecode.bind(this, request))
      .then(runHooks.bind(this, request, response, preHookList))
      .then(dispatch.bind(this, request, response))
      .then(runHooks.bind(this, request, response, postHookList))
      .then(endResponse.bind(this, response))
      .catch(this.onError.bind(this, request, response));
  };

  /**
   * Add router to resolve uri
   * @param router
   * @returns {CoreApplication}
   */
  this.addRouter = function (router) {
    routers.push(router);
    return this;
  };

  /**
   * Add hook before calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPreHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    preHookList.push(callableHook);
    return this;
  };

  /**
   * Add hook after calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPostHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    postHookList.push(callableHook);
    return this;
  };

  /**
   * If page not found
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onPageNotFound = function (request, response, error) {
    console.log(error);
    response.writeHead(404);
    response.end();
    return this;
  };

  /**
   * If an error occured
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onError = function (request, response, error) {
    console.error(error);
    response.writeHead(503);
    response.end();
    return this;
  };

  return this;

  /**
   * Dispatch request in good action using routers
   * @param request
   * @param response
   * @returns {Promise}
   */
  function dispatch(request, response) {
    return Promise.resolve()
      .then(resolveRouters.bind(this, request))
      .then(callAction.bind(this, request, response));
  }

  /**
   * Resolve uri using routers
   * @param request
   * @returns {Promise}
   */
  function resolveRouters(request) {
    for (var i = 0, l = routers.length; i < l; i++) {
      var callback = routers[i].resolve(request);
      if (null != callback) {
        return Promise.resolve(callback);
      }
    }
    return Promise.reject('Route not defined for "' + request.url + '"');
  }

  /**
   * Call action and method form resolved route
   * @param request
   * @param response
   * @param callback
   * @returns {*}
   */
  function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }

  /**
   * Decode post data and add input into request
   * @param request
   * @returns {Promise}
   */
  function postDecode(request) {
    return new Promise(function promisePostDecode(resolve) {
      var postData = '';
      if (request.method === 'POST') {
        request.on('data', function (chunk) {
          // append the current chunk of data to the fullBody variable
          postData += chunk.toString();
        });

        request.on('end', function () {
          request.body = qs.parse(postData);
          resolve();
        });

      } else {
        resolve();
      }
    });
  }

  /**
   * Run given hooks
   * @param request
   * @param response
   * @param hooks
   * @returns {Promise}
   */
  function runHooks(request, response, hooks) {
    var promise = Promise.resolve();
    for (var i = 0; i < hooks.length; i++) {
      promise = promise.then(hooks[i].bind(this, request, response));
    }
    return promise;
  }

  /**
   * Finalize response
   * @param response
   */
  function endResponse(response) {
    response.end();
  }
}

module.exports = CoreApplication;<|endoftext|>


<commit_before>define([
    'knockout',
    'jquery',
    'viewmodels/widget',
    'arches',
], function(ko, $, WidgetViewModel, arches) {
    var nameLookup = {};
    var ConceptSelectViewModel = function(params) {
        var self = this;

        params.configKeys = ['placeholder', 'defaultValue'];

        this.multiple = params.multiple || false;
        this.allowClear = true;
        this.displayName = ko.observable('');

        WidgetViewModel.apply(this, [params]);

        this.valueList = ko.computed(function() {
            var valueList = self.value();

            if (!self.multiple && valueList) {
                valueList = [valueList];
            }
            if (Array.isArray(valueList)) {
                return valueList;
            }
            return [];
        });

        this.valueObjects = ko.computed(function() {
            return self.valueList().map(function(value) {
                return {
                    id: value,
                    name: nameLookup[value]
                };
            }).filter(function(item) {
                return item.name;
            });
        });

        this.updateName = function() {
            var names = [];

            self.valueList().forEach(function(val) {
                if (val) {
                    if (nameLookup[val]) {
                        names.push(nameLookup[val]);
                        self.displayName(names.join(', '));
                    } else {
                        $.ajax(arches.urls.get_pref_label + '?valueid=' + val, {
                            dataType: "json"
                        }).done(function(data) {
                            nameLookup[val] = data.value;
                            names.push(data.value);
                            self.displayName(names.join(', '));
                        });
                    }
                }
            });
        };
        this.value.subscribe(self.updateName);

        this.displayValue = ko.computed(function() {
            var val = self.value();
            var name = self.displayName();
            var displayVal = null;

            if (val) {
                displayVal = name;
            }

            return displayVal;
        });

        this.select2Config = {
            value: self.value,
            clickBubble: true,
            multiple: self.multiple,
            closeOnSlect: false,
            placeholder: self.placeholder,
            allowClear: true,
            ajax: {
                url: arches.urls.paged_dropdown,
                dataType: 'json',
                quietMillis: 250,
                data: function(term, page) {
                    return {
                        conceptid: ko.unwrap(params.node.config.rdmCollection),
                        query: term,
                        page: page
                    };
                },
                results: function(data) {
                    data.results.forEach(function(result) {
                        if (result.collector) {
                            delete result.id;
                        }
                    });
                    return {
                        results: data.results,
                        more: data.more
                    };
                }
            },
            id: function(item) {
                return item.id;
            },
            formatResult: function(item) {
                var indentation = '';
                for (var i = 0; i < item.depth-1; i++) {
                    indentation += '    ';
                }
                return indentation + item.text;
            },
            formatSelection: function(item) {
                return item.text;
            },
            clear: function() {
                self.value('');
            },
            isEmpty: ko.computed(function() {
                return self.value() === '' || !self.value();
            }),
            initSelection: function(el, callback) {
                /* reversing the values gives correct ordering if multiple === true */
                var valueList = self.valueList().reverse();

                var setSelectionData = function(data) {
                    if (!(data instanceof Array)) { data = [data]; }

                    var valueData = data.reduce(function(acc, datum) {
                        var valueDatum;

                        /* coerce different datum types into expected type */
                        if (!datum.value) {
                            var valueObject = self.valueObjects().find(function(valueObject) {
                                return valueObject.name === datum;
                            });

                            if (valueObject) {
                                valueDatum = {
                                    id: valueObject.id,
                                    text: valueObject.name,
                                };
                            }
                        }
                        else if (datum.value) {
                            valueDatum = {
                                id: datum.valueid,
                                text: datum.value,
                            };
                        }

                        if (valueDatum) {
                            acc.push(valueDatum);
                        }

                        return acc;
                    }, []);

                    if (self.multiple) {
                        /* add the rest of the valueList */
                        valueList.forEach(function(value) {
                            if (value !== valueData[0].id) {
                                valueData.unshift({
                                    id: value,
                                    text: nameLookup[value],
                                });
                            }
                        });
                    }

                    if (valueData) {
                        callback(valueData);
                    }
                };

                valueList.forEach(function(value) {
                    if (value) {
                        if (nameLookup[value]) {
                            setSelectionData(nameLookup[value]);
                        } else {
                            $.ajax(arches.urls.concept_value + '?valueid=' + value, {
                                dataType: "json"
                            }).done(function(data) {
                                nameLookup[value] = data.value;
                                setSelectionData(data);
                            });
                        }
                    }
                });
            }
        };
    };

    return ConceptSelectViewModel;
});
<commit_msg>nit #6963<commit_after>define([
    'knockout',
    'jquery',
    'viewmodels/widget',
    'arches',
], function(ko, $, WidgetViewModel, arches) {
    NAME_LOOKUP = {};

    var ConceptSelectViewModel = function(params) {
        var self = this;

        params.configKeys = ['placeholder', 'defaultValue'];

        this.multiple = params.multiple || false;
        this.allowClear = true;
        this.displayName = ko.observable('');

        WidgetViewModel.apply(this, [params]);

        this.valueList = ko.computed(function() {
            var valueList = self.value();

            if (!self.multiple && valueList) {
                valueList = [valueList];
            }
            if (Array.isArray(valueList)) {
                return valueList;
            }
            return [];
        });

        this.valueObjects = ko.computed(function() {
            return self.valueList().map(function(value) {
                return {
                    id: value,
                    name: NAME_LOOKUP[value]
                };
            }).filter(function(item) {
                return item.name;
            });
        });

        this.updateName = function() {
            var names = [];

            self.valueList().forEach(function(val) {
                if (val) {
                    if (NAME_LOOKUP[val]) {
                        names.push(NAME_LOOKUP[val]);
                        self.displayName(names.join(', '));
                    } else {
                        $.ajax(arches.urls.get_pref_label + '?valueid=' + val, {
                            dataType: "json"
                        }).done(function(data) {
                            NAME_LOOKUP[val] = data.value;
                            names.push(data.value);
                            self.displayName(names.join(', '));
                        });
                    }
                }
            });
        };
        this.value.subscribe(self.updateName);

        this.displayValue = ko.computed(function() {
            var val = self.value();
            var name = self.displayName();
            var displayVal = null;

            if (val) {
                displayVal = name;
            }

            return displayVal;
        });

        this.select2Config = {
            value: self.value,
            clickBubble: true,
            multiple: self.multiple,
            closeOnSlect: false,
            placeholder: self.placeholder,
            allowClear: true,
            ajax: {
                url: arches.urls.paged_dropdown,
                dataType: 'json',
                quietMillis: 250,
                data: function(term, page) {
                    return {
                        conceptid: ko.unwrap(params.node.config.rdmCollection),
                        query: term,
                        page: page
                    };
                },
                results: function(data) {
                    data.results.forEach(function(result) {
                        if (result.collector) {
                            delete result.id;
                        }
                    });
                    return {
                        results: data.results,
                        more: data.more
                    };
                }
            },
            id: function(item) {
                return item.id;
            },
            formatResult: function(item) {
                var indentation = '';
                for (var i = 0; i < item.depth-1; i++) {
                    indentation += '    ';
                }
                return indentation + item.text;
            },
            formatSelection: function(item) {
                return item.text;
            },
            clear: function() {
                self.value('');
            },
            isEmpty: ko.computed(function() {
                return self.value() === '' || !self.value();
            }),
            initSelection: function(el, callback) {
                /* reversing the values gives correct ordering if multiple === true */
                var valueList = self.valueList().reverse();

                var setSelectionData = function(data) {
                    if (!(data instanceof Array)) { data = [data]; }

                    var valueData = data.map(function(valueId) {
                        return {
                            id: valueId,
                            text: NAME_LOOKUP[valueId],
                        };
                    });

                    if (self.multiple) {
                        /* add the rest of the previously selected values */
                        valueList.forEach(function(value) {
                            if (value !== valueData[0].id) {
                                valueData.unshift({
                                    id: value,
                                    text: NAME_LOOKUP[value],
                                });
                            }
                        });
                    }

                    if (valueData) {
                        callback(valueData);
                    }
                };

                valueList.forEach(function(value) {
                    if (value) {
                        if (NAME_LOOKUP[value]) {
                            setSelectionData(value);
                        } else {
                            $.ajax(arches.urls.concept_value + '?valueid=' + value, {
                                dataType: "json"
                            }).done(function(data) {
                                NAME_LOOKUP[value] = data.value;
                                setSelectionData(value);
                            });
                        }
                    }
                });
            }
        };
    };

    return ConceptSelectViewModel;
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var ceil = require( '@stdlib/math/base/special/ceil' );
var randu = require( '@stdlib/math/base/random/randu' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var pkg = require( './../package.json' ).name;
var cdf = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var k;
	var x;
	var y;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = ( randu()*100.0 ) + EPS;
		k = ceil( randu()*100.0 );
		y = cdf( x, k );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':factory', function benchmark( b ) {
	var mycdf;
	var k;
	var x;
	var y;
	var i;

	k = 10.0;
	mycdf = cdf.factory( k );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = ( randu()*100.0 ) + EPS;
		y = mycdf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<commit_msg>Remove epsilon adjustment<commit_after>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var ceil = require( '@stdlib/math/base/special/ceil' );
var randu = require( '@stdlib/math/base/random/randu' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var pkg = require( './../package.json' ).name;
var cdf = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var k;
	var x;
	var y;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu() * 100.0;
		k = ceil( randu()*100.0 );
		y = cdf( x, k );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':factory', function benchmark( b ) {
	var mycdf;
	var k;
	var x;
	var y;
	var i;

	k = 10.0;
	mycdf = cdf.factory( k );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		x = randu() * 100.0;
		y = mycdf( x );
		if ( isnan( y ) ) {
			b.fail( 'should not return NaN' );
		}
	}
	b.toc();
	if ( isnan( y ) ) {
		b.fail( 'should not return NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>//= require social_stream/wall

SocialStream.Documents.Wall = (function(SS, $, undefined) {
  var initWall = function() {
    $('<label/>', {
      "for": 'new_document_title',
      style: 'display: none;',
      text: I18n.t('activerecord.attributes.document.title')
    }).insertBefore($('#post_text'));

    $('<textarea/>', {
      name: 'document[description]',
      id: 'new_document_description',
      'class': 'document_description',
      style: 'display: none;',
      placeholder: I18n.t('document.description.input')
    }).insertAfter($('#post_text'));

    $('.wall_input form').
      attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

    $('<input>', {
      name: 'document[file]',
      type: 'file',
      style: 'visibility: hidden; position: absolute'
    }).insertAfter('.wall_input textarea.document_description');

    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $('label[for="new_document_title"]').show();

      $('#post_text').
        attr('name', 'document[title]').
        attr('placeholder', I18n.t('document.title.input'));

      $('#new_document_description').show().val($('#post_text').val());

      SocialStream.Wall.changeAction($(this).attr('data-path'));
      SocialStream.Wall.changeParams('document');

      $('.wall_input input[type=file]').trigger('click');
    });

    $('.wall_input input[type=file]').change(function(){
      $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
    });
  };

  SS.Wall.callbackRegister('show', initWall);
})(SocialStream, jQuery);
<commit_msg>Support cancelling attachments in wall input<commit_after>//= require social_stream/wall

SocialStream.Documents.Wall = (function(SS, $, undefined) {
  var initWall = function() {
    $('<label/>', {
      "for": 'new_document_title',
      style: 'display: none;',
      text: I18n.t('activerecord.attributes.document.title')
    }).insertBefore($('#post_text'));

    $('<textarea/>', {
      name: 'document[description]',
      id: 'new_document_description',
      'class': 'document_description',
      style: 'display: none;',
      placeholder: I18n.t('document.description.input')
    }).insertAfter($('#post_text'));

    $('.wall_input form').
      attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

    $('<input>', {
      name: 'document[file]',
      type: 'file',
      style: 'visibility: hidden; position: absolute'
    }).insertAfter('.wall_input textarea.document_description');

    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $('.wall_input input[type=file]').trigger('click');
    });

    $('.wall_input input[type=file]').change(function(){
      if ($(this).val()) {
        $('label[for="new_document_title"]').show();

        $('#post_text').
          attr('name', 'document[title]').
          attr('placeholder', I18n.t('document.title.input'));

        $('#new_document_description').show().val($('#post_text').val());

        SocialStream.Wall.changeAction($(this).closest('form').find('button.new_document').attr('data-path'));
        SocialStream.Wall.changeParams('document');

        $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
      } else {
        $('label[for="new_document_title"]').hide();

        $('#post_text').
          attr('name', 'post[text]').
          attr('placeholder', I18n.t('post.input'));

        $('#new_document_description').hide();

        SocialStream.Wall.changeAction();
        SocialStream.Wall.changeParams();

        $("#post_text").val($('#new_document_description').val());
      }
    });
  };

  SS.Wall.callbackRegister('show', initWall);
})(SocialStream, jQuery);
<|endoftext|>


<commit_before>"use strict";

(function(window, builder) {
  /**
   * @global
   * @class
   * @name Api
   */
  var Api = window["Asc"]["spreadsheet_api"];

  /**
   * Class representing a sheet.
   * @constructor
   */
  function ApiWorksheet(worksheet) {
    this.worksheet = worksheet;
  }

  /**
   * Class representing a range.
   * @constructor
   */
  function ApiRange(range) {
    this.range = range;
  }

  /**
   * Class representing a graphical object.
   * @constructor
   */
  function ApiDrawing(Drawing)
  {
    this.Drawing = Drawing;
  }

  /**
   * This type specifies the types, create charts
   * @typedef {("bar" | "barStacked" | "barStackedPercent" | "bar3D" | "barStacked3D" | "barStackedPercent3D" | "barStackedPercent3DPerspective" | "horizontalBar" | "horizontalBarStacked" | "horizontalBarStackedPercent" | "horizontalBar3D" | "horizontalBarStacked3D" | "horizontalBarStackedPercent3D" | "lineNormal" | "lineStacked" | "lineStackedPercent" | "line3D" | "pie" | "pie3D" | "doughnut" | "scatter" | "stock")} ChartType
   */

  /**
   * Class representing a Chart.
   * @constructor
   *
   */
  function ApiChart(Chart)
  {
    ApiChart.superclass.constructor.call(this, Chart.parent);
    this.Chart = Chart;
  }
  AscCommon.extendClass(ApiChart, ApiDrawing);

  /**
   * Returns an object that represents the active sheet
   * @memberof Api
   * @returns {ApiWorksheet}
   */
  Api.prototype.GetActiveSheet = function() {
    return new ApiWorksheet(this.wbModel.getWorksheet(this.wbModel.getActive()));
  };

  /**
   * Set sheet name
   * @memberof ApiWorksheet
   * @param {string} name
   */
  ApiWorksheet.prototype.setName = function(name) {
    this.worksheet.setName(name);
  };

  /**
   * Returns an object that represents the range
   * @memberof ApiWorksheet
   * @param {string} sRange
   * @returns {ApiRange}
   */
  ApiWorksheet.prototype.getRange = function(sRange) {
    return new ApiRange(this.worksheet.getRange2(sRange));
  };

  /**
   * Format as table
   * @memberof ApiWorksheet
   * @param {string} sRange
   */
  ApiWorksheet.prototype.formatAsTable = function(sRange) {
    this.worksheet.autoFilters.addAutoFilter('TableStyleLight9', AscCommonExcel.g_oRangeCache.getAscRange(sRange));
  };

  /**
   * Set column width
   * @memberof ApiWorksheet
   * @param {number} column
   * @param {number} width
   */
  ApiWorksheet.prototype.setColumnWidth = function(column, width) {
    this.worksheet.setColWidth(width, column, column);
  };

  /**
   * Set column width
   * @memberof ApiWorksheet
   * @param {string} sDataRange
   * @param {bool} bInRows
   * @param {ChartType} sType
   * @param {number} nStyleIndex
   * @param {number} nFromCol
   * @param {number} nFromRow
   * @param {number} nToCol
   * @param {number} nToRow
   */
  ApiWorksheet.prototype.addChart = function(sDataRange, bInRows, sType, nStyleIndex, nFromCol, nFromRow, nToCol, nToRow) {

    History.Create_NewPoint();
    var settings = new AscCommon.asc_ChartSettings();
    switch (sType)
    {
      case "bar" :
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal;
        break;
      }
      case "barStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStacked;
        break;
      }
      case "barStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStackedPer;
        break;
      }
      case "bar3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal3d;
        break;
      }
      case "barStacked3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStacked3d;
        break;
      }
      case "barStackedPercent3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStackedPer3d;
        break;
      }
      case "barStackedPercent3DPerspective":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal3dPerspective;
        break;
      }
      case "horizontalBar":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarNormal;
        break;
      }
      case "horizontalBarStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStacked;
        break;
      }
      case "horizontalBarStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStackedPer;
        break;
      }
      case "horizontalBar3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarNormal3d;
        break;
      }
      case "horizontalBarStacked3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStacked3d;
        break;
      }
      case "horizontalBarStackedPercent3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStackedPer3d;
        break;
      }
      case "lineNormal":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineNormal;
        break;
      }
      case "lineStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineStacked;
        break;
      }
      case "lineStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineStackedPer;
        break;
      }
      case "line3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.line3d;
        break;
      }
      case "pie":
      {
        settings.type = Asc.c_oAscChartTypeSettings.pie;
        break;
      }
      case "pie3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.pie3d;
        break;
      }
      case "doughnut":
      {
        settings.type = Asc.c_oAscChartTypeSettings.doughnut;
        break;
      }
      case "scatter":
      {
        settings.type = Asc.c_oAscChartTypeSettings.scatter;
        break;
      }
      case "stock":
      {
        settings.type = Asc.c_oAscChartTypeSettings.stock;
        break;
      }
    }
    settings.style = nStyleIndex;
    settings.inColumns = !bInRows;
    settings.range = sDataRange;
    var oChart = AscFormat.DrawingObjectsController.prototype.getChartSpace(this.worksheet, settings);
    oChart.setWorksheet(this.worksheet);
    oChart.setBFromSerialize(true);
    oChart.addToDrawingObjects();
    oChart.setDrawingBaseCoords(nFromCol, 0, nFromRow, 0, nToCol, 0, nToRow, 0, 0, 0, 0, 0);
    if(AscFormat.isRealNumber(nStyleIndex))
    {
      oChart.setStyle(nStyleIndex);
    }
  };

  /**
   * Set cell value
   * @memberof ApiRange
   * @param {string} val
   */
  ApiRange.prototype.setValue = function(val) {
    this.range.setValue(val);
  };

  /**
   * Set text color in the rgb format.
   * @param {byte} r
   * @param {byte} g
   * @param {byte} b
   */
  ApiRange.prototype.setFontColor = function(r, g, b) {
    this.range.setFontcolor(new AscCommonExcel.RgbColor((r << 16) +  (g << 8) +  b));
  };

  /**
   * Set font size
   * @param {number} size
   */
  ApiRange.prototype.setFontSize = function(size) {
    this.range.setFontsize(size);
  };

  /**
   * Set font name
   * @param {string} name
   */
  ApiRange.prototype.setFontName = function(name) {
    this.range.setFontname(name);
  };

  /**
   * Set align vertical
   * @param {'center' | 'bottom' | 'top'} value
   */
  ApiRange.prototype.setAlignVertical = function(value) {
    this.range.setAlignVertical(value);
  };

  /**
   * Set align horizontal
   * @param {'left' | 'right' | 'center' | 'justify'} value
   */
  ApiRange.prototype.setAlignHorizontal = function(value) {
    this.range.setAlignHorizontal(value);
  };

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // Export
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  Api.prototype["GetActiveSheet"] = Api.prototype.GetActiveSheet;

  ApiWorksheet.prototype["setName"] = ApiWorksheet.prototype.setName;
  ApiWorksheet.prototype["getRange"] = ApiWorksheet.prototype.getRange;
  ApiWorksheet.prototype["formatAsTable"] = ApiWorksheet.prototype.formatAsTable;
  ApiWorksheet.prototype["setColumnWidth"] = ApiWorksheet.prototype.setColumnWidth;
  ApiWorksheet.prototype["addChart"] = ApiWorksheet.prototype.addChart;

  ApiRange.prototype["setValue"] = ApiRange.prototype.setValue;
  ApiRange.prototype["setFontColor"] = ApiRange.prototype.setFontColor;
  ApiRange.prototype["setFontSize"] = ApiRange.prototype.setFontSize;
  ApiRange.prototype["setFontName"] = ApiRange.prototype.setFontName;
  ApiRange.prototype["setAlignVertical"] = ApiRange.prototype.setAlignVertical;
  ApiRange.prototype["setAlignHorizontal"] = ApiRange.prototype.setAlignHorizontal;
}(window, null));
<commit_msg>upper case first symbol in function names in apiBuilder<commit_after>"use strict";

(function(window, builder) {
  /**
   * @global
   * @class
   * @name Api
   */
  var Api = window["Asc"]["spreadsheet_api"];

  /**
   * Class representing a sheet.
   * @constructor
   */
  function ApiWorksheet(worksheet) {
    this.worksheet = worksheet;
  }

  /**
   * Class representing a range.
   * @constructor
   */
  function ApiRange(range) {
    this.range = range;
  }

  /**
   * Class representing a graphical object.
   * @constructor
   */
  function ApiDrawing(Drawing)
  {
    this.Drawing = Drawing;
  }

  /**
   * This type specifies the types, create charts
   * @typedef {("bar" | "barStacked" | "barStackedPercent" | "bar3D" | "barStacked3D" | "barStackedPercent3D" | "barStackedPercent3DPerspective" | "horizontalBar" | "horizontalBarStacked" | "horizontalBarStackedPercent" | "horizontalBar3D" | "horizontalBarStacked3D" | "horizontalBarStackedPercent3D" | "lineNormal" | "lineStacked" | "lineStackedPercent" | "line3D" | "pie" | "pie3D" | "doughnut" | "scatter" | "stock")} ChartType
   */

  /**
   * Class representing a Chart.
   * @constructor
   *
   */
  function ApiChart(Chart)
  {
    ApiChart.superclass.constructor.call(this, Chart.parent);
    this.Chart = Chart;
  }
  AscCommon.extendClass(ApiChart, ApiDrawing);

  /**
   * Returns an object that represents the active sheet
   * @memberof Api
   * @returns {ApiWorksheet}
   */
  Api.prototype.GetActiveSheet = function() {
    return new ApiWorksheet(this.wbModel.getWorksheet(this.wbModel.getActive()));
  };

  /**
   * Set sheet name
   * @memberof ApiWorksheet
   * @param {string} name
   */
  ApiWorksheet.prototype.SetName = function(name) {
    this.worksheet.setName(name);
  };

  /**
   * Returns an object that represents the range
   * @memberof ApiWorksheet
   * @param {string} sRange
   * @returns {ApiRange}
   */
  ApiWorksheet.prototype.GetRange = function(sRange) {
    return new ApiRange(this.worksheet.getRange2(sRange));
  };

  /**
   * Format as table
   * @memberof ApiWorksheet
   * @param {string} sRange
   */
  ApiWorksheet.prototype.FormatAsTable = function(sRange) {
    this.worksheet.autoFilters.addAutoFilter('TableStyleLight9', AscCommonExcel.g_oRangeCache.getAscRange(sRange));
  };

  /**
   * Set column width
   * @memberof ApiWorksheet
   * @param {number} column
   * @param {number} width
   */
  ApiWorksheet.prototype.SetColumnWidth = function(column, width) {
    this.worksheet.setColWidth(width, column, column);
  };

  /**
   * Set column width
   * @memberof ApiWorksheet
   * @param {string} sDataRange
   * @param {bool} bInRows
   * @param {ChartType} sType
   * @param {number} nStyleIndex
   * @param {number} nFromCol
   * @param {number} nFromRow
   * @param {number} nToCol
   * @param {number} nToRow
   */
  ApiWorksheet.prototype.AddChart = function(sDataRange, bInRows, sType, nStyleIndex, nFromCol, nFromRow, nToCol, nToRow) {

    History.Create_NewPoint();
    var settings = new AscCommon.asc_ChartSettings();
    switch (sType)
    {
      case "bar" :
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal;
        break;
      }
      case "barStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStacked;
        break;
      }
      case "barStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStackedPer;
        break;
      }
      case "bar3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal3d;
        break;
      }
      case "barStacked3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStacked3d;
        break;
      }
      case "barStackedPercent3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barStackedPer3d;
        break;
      }
      case "barStackedPercent3DPerspective":
      {
        settings.type = Asc.c_oAscChartTypeSettings.barNormal3dPerspective;
        break;
      }
      case "horizontalBar":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarNormal;
        break;
      }
      case "horizontalBarStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStacked;
        break;
      }
      case "horizontalBarStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStackedPer;
        break;
      }
      case "horizontalBar3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarNormal3d;
        break;
      }
      case "horizontalBarStacked3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStacked3d;
        break;
      }
      case "horizontalBarStackedPercent3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.hBarStackedPer3d;
        break;
      }
      case "lineNormal":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineNormal;
        break;
      }
      case "lineStacked":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineStacked;
        break;
      }
      case "lineStackedPercent":
      {
        settings.type = Asc.c_oAscChartTypeSettings.lineStackedPer;
        break;
      }
      case "line3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.line3d;
        break;
      }
      case "pie":
      {
        settings.type = Asc.c_oAscChartTypeSettings.pie;
        break;
      }
      case "pie3D":
      {
        settings.type = Asc.c_oAscChartTypeSettings.pie3d;
        break;
      }
      case "doughnut":
      {
        settings.type = Asc.c_oAscChartTypeSettings.doughnut;
        break;
      }
      case "scatter":
      {
        settings.type = Asc.c_oAscChartTypeSettings.scatter;
        break;
      }
      case "stock":
      {
        settings.type = Asc.c_oAscChartTypeSettings.stock;
        break;
      }
    }
    settings.style = nStyleIndex;
    settings.inColumns = !bInRows;
    settings.range = sDataRange;
    var oChart = AscFormat.DrawingObjectsController.prototype.getChartSpace(this.worksheet, settings);
    oChart.setWorksheet(this.worksheet);
    oChart.setBFromSerialize(true);
    oChart.addToDrawingObjects();
    oChart.setDrawingBaseCoords(nFromCol, 0, nFromRow, 0, nToCol, 0, nToRow, 0, 0, 0, 0, 0);
    if(AscFormat.isRealNumber(nStyleIndex))
    {
      oChart.setStyle(nStyleIndex);
    }
  };

  /**
   * Set cell value
   * @memberof ApiRange
   * @param {string} val
   */
  ApiRange.prototype.SetValue = function(val) {
    this.range.setValue(val);
  };

  /**
   * Set text color in the rgb format.
   * @param {byte} r
   * @param {byte} g
   * @param {byte} b
   */
  ApiRange.prototype.SetFontColor = function(r, g, b) {
    this.range.setFontcolor(new AscCommonExcel.RgbColor((r << 16) +  (g << 8) +  b));
  };

  /**
   * Set font size
   * @param {number} size
   */
  ApiRange.prototype.SetFontSize = function(size) {
    this.range.setFontsize(size);
  };

  /**
   * Set font name
   * @param {string} name
   */
  ApiRange.prototype.SetFontName = function(name) {
    this.range.setFontname(name);
  };

  /**
   * Set align vertical
   * @param {'center' | 'bottom' | 'top'} value
   */
  ApiRange.prototype.SetAlignVertical = function(value) {
    this.range.setAlignVertical(value);
  };

  /**
   * Set align horizontal
   * @param {'left' | 'right' | 'center' | 'justify'} value
   */
  ApiRange.prototype.SetAlignHorizontal = function(value) {
    this.range.setAlignHorizontal(value);
  };

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // Export
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  Api.prototype["GetActiveSheet"] = Api.prototype.GetActiveSheet;

  ApiWorksheet.prototype["SetName"] = ApiWorksheet.prototype.SetName;
  ApiWorksheet.prototype["GetRange"] = ApiWorksheet.prototype.GetRange;
  ApiWorksheet.prototype["FormatAsTable"] = ApiWorksheet.prototype.FormatAsTable;
  ApiWorksheet.prototype["SetColumnWidth"] = ApiWorksheet.prototype.SetColumnWidth;
  ApiWorksheet.prototype["AddChart"] = ApiWorksheet.prototype.AddChart;

  ApiRange.prototype["SetValue"] = ApiRange.prototype.SetValue;
  ApiRange.prototype["SetFontColor"] = ApiRange.prototype.SetFontColor;
  ApiRange.prototype["SetFontSize"] = ApiRange.prototype.SetFontSize;
  ApiRange.prototype["SetFontName"] = ApiRange.prototype.SetFontName;
  ApiRange.prototype["SetAlignVertical"] = ApiRange.prototype.SetAlignVertical;
  ApiRange.prototype["SetAlignHorizontal"] = ApiRange.prototype.SetAlignHorizontal;
}(window, null));
<|endoftext|>


<commit_before>module.exports = "css-file-stub";
<commit_msg>fix copypasta<commit_after>module.exports = "wasm-file-stub";
<|endoftext|>


<commit_before>
var koa = require('koa');

var app = module.exports = koa();

app.use(function* () {

})
<commit_msg>finished 07-content-headers<commit_after>var koa = require('koa');

var app = module.exports = koa();

app.use(function * () {
	if (this.request.is('application/json')) {

		//response type is implicitly setted by koa
		this.body = {
			message: 'hi!'
		};
	} else {
		this.response.type = 'text/plain';
		this.body = 'ok';
	}
})<|endoftext|>


<commit_before>//= require ./composite_view

function extendWithAutoloading(superclass) {
  return superclass.extend({
    constructor: function(options){
      superclass.prototype.constructor.apply(this, arguments);
      this.collection.loadMore();
      this.collection.on('add', _.bind(function(){
        this.emptyViewOff();
      },this));
      this.collection.on('stopLoading', this.afterLoad, this);

    },

    bottomOfViewReached: function() {
      var bottomOfTheViewport = window.pageYOffset + window.innerHeight;
      var bottomOfEl = this.$el.offset().top + this.$el.outerHeight();

      if ( bottomOfEl < bottomOfTheViewport ) {
        return true;
      } else if ($(document).height() - ($(window).scrollTop() + $(window).height()) < 700) {
        return true;
      } else {
        return false;
      }
    },

    afterLoad: function() {
      if(!this.collection._loading) {
        if (this.collection.length === 0) {
          this.emptyViewOn();
        }

        if ( this.bottomOfViewReached()) {
          this.collection.loadMore();
        }
      }
    },

    bindScroll: function() {
      this.unbindScroll();
      $(window).on('scroll.' + this.cid, _.bind(function MCBiggah() {
        this.afterLoad();
      }, this));
    },

    unbindScroll: function() {
      $(window).off('scroll.' + this.cid);
    },

    close: function() {
      superclass.prototype.close.apply(this, arguments);
      this.unbindScroll();
    },

    render: function() {
      superclass.prototype.render.apply(this, arguments);
      this.bindScroll();
    },

    reset: function(e){
      this.collection.stopLoading();
      superclass.prototype.reset.apply(this, arguments);
    },

    // TODO: replace this by standard empty view functionality by marionette.
    emptyViewOn: function(){},
    emptyViewOff: function(){}

  });
}
window.AutoloadingCompositeView = extendWithAutoloading(Backbone.Factlink.CompositeView);
<commit_msg>switch on empty state after removal of fact if applicable<commit_after>//= require ./composite_view

function extendWithAutoloading(superclass) {
  return superclass.extend({
    constructor: function(options){
      superclass.prototype.constructor.apply(this, arguments);
      this.collection.loadMore();
      this.collection.on('add', _.bind(function(){
        this.emptyViewOff();
      },this));
      this.collection.on('remove stopLoading', this.afterLoad, this);

    },

    bottomOfViewReached: function() {
      var bottomOfTheViewport = window.pageYOffset + window.innerHeight;
      var bottomOfEl = this.$el.offset().top + this.$el.outerHeight();

      if ( bottomOfEl < bottomOfTheViewport ) {
        return true;
      } else if ($(document).height() - ($(window).scrollTop() + $(window).height()) < 700) {
        return true;
      } else {
        return false;
      }
    },

    afterLoad: function() {
      if(!this.collection._loading) {
        if (this.collection.length === 0) {
          this.emptyViewOn();
        }

        if ( this.bottomOfViewReached()) {
          this.collection.loadMore();
        }
      }
    },

    bindScroll: function() {
      this.unbindScroll();
      $(window).on('scroll.' + this.cid, _.bind(function MCBiggah() {
        this.afterLoad();
      }, this));
    },

    unbindScroll: function() {
      $(window).off('scroll.' + this.cid);
    },

    close: function() {
      superclass.prototype.close.apply(this, arguments);
      this.unbindScroll();
    },

    render: function() {
      superclass.prototype.render.apply(this, arguments);
      this.bindScroll();
    },

    reset: function(e){
      this.collection.stopLoading();
      superclass.prototype.reset.apply(this, arguments);
    },

    // TODO: replace this by standard empty view functionality by marionette.
    emptyViewOn: function(){},
    emptyViewOff: function(){}

  });
}
window.AutoloadingCompositeView = extendWithAutoloading(Backbone.Factlink.CompositeView);
<|endoftext|>


<commit_before>// User service
// 	responsible for providing API resources for user management
//	consumed by client applications and other services
//
// author @sauliuz

// dependencies
var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
//securableEndpoints = ['hello'];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// fhlint-begin: custom-routes
app.use('/projects', require('./apis/projects.js')());
app.use('/', require('./apis/unused.js')());
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001;
var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var server = app.listen(port, host, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<commit_msg>swaping local port 8001 to 8002<commit_after>// User service
// 	responsible for providing API resources for user management
//	consumed by client applications and other services
//
// author @sauliuz

// dependencies
var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
//securableEndpoints = ['hello'];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// fhlint-begin: custom-routes
app.use('/projects', require('./apis/projects.js')());
app.use('/', require('./apis/unused.js')());
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8002;
var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var server = app.listen(port, host, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var copy = require( '@stdlib/utils/copy' );
var parseJSON = require( '@stdlib/utils/parse-json' );
var Complex128 = require( '@stdlib/types/complex/complex128' );
var reviver = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof reviver, 'function', 'main export is a function' );
	t.end();
});

tape( 'values which are not recognized as serialized 128-bit complex numbers are unaffected', function test( t ) {
	var expected;
	var actual;

	expected = {
		'beep': 'boop'
	};
	actual = parseJSON( '{"beep":"boop"}', reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	// Null edge case:
	actual = parseJSON( 'null', reviver );
	t.strictEqual( actual, null, 'equals null' );

	t.end();
});

tape( 'an object must have a recognized "type" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Boop',
		're': 5.0,
		'im': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );
	t.end();
});

tape( 'an object must have a numeric "re" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Complex128',
		'im': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		'im': 3.0,
		're': '5.0'
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		'im': 3.0,
		're': null
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	t.end();
});

tape( 'an object must have a numeric "im" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Complex128',
		're': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		're': 3.0,
		'im': '5.0'
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		're': 3.0,
		'im': null
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	t.end();
});

tape( 'the function will revive a JSON-serialized 128-bit number', function test( t ) {
	var json;
	var z;
	var w;

	z = new Complex128( 5.0, 3.0 );
	json = JSON.stringify( z );

	w = parseJSON( json, reviver );

	t.strictEqual( w instanceof Complex128, true, 'is an instance' );
	t.strictEqual( w.re, z.re, true, 'has expected property value' );
	t.strictEqual( w.im, z.im, true, 'has expected property value' );

	t.end();
});

tape( 'the function will revive deeply nested serialized 128-bit complex numbers (array)', function test( t ) {
	var actual;
	var arr;
	var i;

	arr = [
		new Complex128( 5.0, 3.0 ),
		new Complex128( -2.0, -4.0 )
	];

	actual = parseJSON( JSON.stringify( arr ), reviver );

	for ( i = 0; i < arr.length; i++ ) {
		t.strictEqual( actual[i] instanceof Complex128, true, 'is an instance' );
		t.strictEqual( actual[i].re, arr[i].re, 'has expected property value' );
		t.strictEqual( actual[i].im, arr[i].im, 'has expected property value' );
	}
	t.end();
});

tape( 'the function will revive deeply nested serialized 128-bit complex numbers (object)', function test( t ) {
	var actual;
	var json;

	json = {
		'beep': {
			'boop': new Complex128( 5.0, 3.0 )
		}
	};
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.strictEqual( actual.beep.boop instanceof Complex128, true, 'is an instance' );
	t.strictEqual( actual.beep.boop.re, json.beep.boop.re, 'has expected property value' );
	t.strictEqual( actual.beep.boop.im, json.beep.boop.im, 'has expected property value' );

	t.end();
});
<commit_msg>Update test description<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var copy = require( '@stdlib/utils/copy' );
var parseJSON = require( '@stdlib/utils/parse-json' );
var Complex128 = require( '@stdlib/types/complex/complex128' );
var reviver = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof reviver, 'function', 'main export is a function' );
	t.end();
});

tape( 'values which are not recognized as serialized 128-bit complex numbers are unaffected', function test( t ) {
	var expected;
	var actual;

	expected = {
		'beep': 'boop'
	};
	actual = parseJSON( '{"beep":"boop"}', reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	// Null edge case:
	actual = parseJSON( 'null', reviver );
	t.strictEqual( actual, null, 'equals null' );

	t.end();
});

tape( 'an object must have a recognized "type" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Boop',
		're': 5.0,
		'im': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );
	t.end();
});

tape( 'an object must have a numeric "re" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Complex128',
		'im': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		'im': 3.0,
		're': '5.0'
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		'im': 3.0,
		're': null
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	t.end();
});

tape( 'an object must have a numeric "im" field in order to be revived', function test( t ) {
	var expected;
	var actual;
	var json;

	json = {
		'type': 'Complex128',
		're': 3.0
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		're': 3.0,
		'im': '5.0'
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	json = {
		'type': 'Complex128',
		're': 3.0,
		'im': null
	};

	expected = copy( json );
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.deepEqual( actual, expected, 'deep equal' );

	t.end();
});

tape( 'the function will revive a JSON-serialized 128-bit complex number', function test( t ) {
	var json;
	var z;
	var w;

	z = new Complex128( 5.0, 3.0 );
	json = JSON.stringify( z );

	w = parseJSON( json, reviver );

	t.strictEqual( w instanceof Complex128, true, 'is an instance' );
	t.strictEqual( w.re, z.re, true, 'has expected property value' );
	t.strictEqual( w.im, z.im, true, 'has expected property value' );

	t.end();
});

tape( 'the function will revive deeply nested serialized 128-bit complex numbers (array)', function test( t ) {
	var actual;
	var arr;
	var i;

	arr = [
		new Complex128( 5.0, 3.0 ),
		new Complex128( -2.0, -4.0 )
	];

	actual = parseJSON( JSON.stringify( arr ), reviver );

	for ( i = 0; i < arr.length; i++ ) {
		t.strictEqual( actual[i] instanceof Complex128, true, 'is an instance' );
		t.strictEqual( actual[i].re, arr[i].re, 'has expected property value' );
		t.strictEqual( actual[i].im, arr[i].im, 'has expected property value' );
	}
	t.end();
});

tape( 'the function will revive deeply nested serialized 128-bit complex numbers (object)', function test( t ) {
	var actual;
	var json;

	json = {
		'beep': {
			'boop': new Complex128( 5.0, 3.0 )
		}
	};
	actual = parseJSON( JSON.stringify( json ), reviver );

	t.strictEqual( actual.beep.boop instanceof Complex128, true, 'is an instance' );
	t.strictEqual( actual.beep.boop.re, json.beep.boop.re, 'has expected property value' );
	t.strictEqual( actual.beep.boop.im, json.beep.boop.im, 'has expected property value' );

	t.end();
});
<|endoftext|>


<commit_before>'use strict';

// TYPED ARRAY FUNCTIONS //

/*
* Create functions for copying typed arrays.
*/
var ctors = [
	'Int8Array',
	'Uint8Array',
	'Uint8ClampedArray',
	'Int16Array',
	'Uint16Array',
	'Int32Array',
	'Uint32Array',
	'Float32Array',
	'Float64Array'
];
var typedArrays = {};

(function createTypedArrayFcns() {
	/* jshint evil:true */ // TODO: eslint
	var ctor;
	var i;
	for ( i = 0; i < ctors.length; i++ ) {
		ctor = ctors[ i ];
		typedArrays[ ctor.toLowerCase() ] = new Function( 'arr', 'return new '+ctor+'( arr );' );
	}
})();

// EXPORTS //

module.exports = typedArrays;
<commit_msg>Remove unnecessary IIFE<commit_after>'use strict';

// TYPED ARRAY FUNCTIONS //

/*
* Create functions for copying typed arrays.
*/
var ctors = [
	'Int8Array',
	'Uint8Array',
	'Uint8ClampedArray',
	'Int16Array',
	'Uint16Array',
	'Int32Array',
	'Uint32Array',
	'Float32Array',
	'Float64Array'
];
var typedArrays = {};

/* jshint evil:true */ // TODO: eslint
var ctor;
var i;
for ( i = 0; i < ctors.length; i++ ) {
	ctor = ctors[ i ];
	typedArrays[ ctor.toLowerCase() ] = new Function( 'arr', 'return new '+ctor+'( arr );' );
}

// EXPORTS //

module.exports = typedArrays;
<|endoftext|>