<commit_before>import { dispatch } from 'd3';
import { SvgStrategy, strategies } from '../../svg/SvgStrategy';
import { svgAsDataUri } from '../../utils/image';

/**
 * Base class, which includes common methods for all the charts
 * @export
 * @class Chart
 */
export default class Chart {
    /**
     * This is a non-instanciable Chart. This is the pattern class for all the ones (Linechart, Barchart, etc.)
     *
     * @param {any} d
     * @param {any} config Configuration of the chart.
     *
     * @memberOf Chart
     */
    constructor(d, config) {
        var clazz = this.constructor.name;
        if (clazz === 'Chart') {
            throw new Error(clazz + ' is non-instanciable');
        }

        this.events = {};

        if (!d && !config) {
            throw new Error('Missing constructor parameters');
        }

        let dataFormat = d.constructor.name;
        let nArguments = (d && config) ? 2 : 1;

        switch (dataFormat) {
            case 'WebsocketDatasource':
                this.datasource = d;
                this.data = [];
                this._configureDatasource();
                break;
            case 'Array':
                this.data = d;
                break;
            default:
                throw TypeError('Wrong data format');
        }
        //if only 1 parameter is specified, take default config. Else, take the second argument as config.
        this.config = (nArguments === 1) ? {} : config;

        this._initializeSVGContext();
    }

    /**
     * Private method. Initialize the API by creating methods dinamically. It creates N method, one per configuration paremeter
     *
     * @param {any} properties An array that contains the name of the methods
     *
     * @memberOf Chart
     */
    _initializeAPI(properties) {
        let clazz = this.constructor;
        properties.forEach((method) => {
            clazz.prototype[method] = function (value) {
                return this.change(method, value);
            }
        });
    }

    /**
     * Return the chart context: data, configuration and type
     *
     * @returns chart context
     *
     * @memberOf Chart
     */
    _getChartContext() {
        return {
            data: this.data,
            config: this.config,
            cType: this.constructor.name
        };
    }

    /**
     * Initialize the SVG context, by dinamically creating an <svg> tag in the specified selector. It is automatically invoked
     * by the chart constructor
     *
     * @memberOf Chart
     */
    _initializeSVGContext() {
        this._svg = new SvgStrategy(strategies[this.constructor.name](this._getChartContext()));
    }

    /**
     * Paint data into the chart. If no data is specified, it takes by default the last dataset (very useful when some configuration
     * option change)
     *
     * @param {any} [data=this.data]
     *
     * @memberOf Chart
     */
    draw(data = this.data) {
        this._svg.draw(data);
    }

    /**
     * Make and download an image of the current state of the chart.
     *
     *
     * @memberOf Chart
     */
    download() {
        let selector = this._svg.strategy.config.selector + ' ' + 'svg';
        svgAsDataUri(d3.select(selector).node(), {}, (uri, err) => {
            if (err) {
                throw Error('Error converting to image ' + err);
            }
            else {
                let link = document.createElement('a');
                link.style = 'position: fixed; left -10000px;'; // making it invisible
                link.href = uri
                link.download = this.constructor.name + '.svg';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        });
    }

    _keepDrawingByAdding(datum) {
        var datumType = datum.constructor;

        if (datumType === Array) {
            this.data = this.data.concat(datum);
        }
        else {
            this.data.push(datum);
        }

        this.draw(JSON.parse(JSON.stringify(this.data)));
    }

    _keepDrawingByReplacing(datum) {
        var datumType = datum.constructor;
        if (datumType === Array) {
            this.data = datum;
        }
        else {
            //TODO: find key by datum.x and replace it with new value
        }

        this.draw(JSON.parse(JSON.stringify(this.data)));
    }

    keepDrawing(datum, method) {
        if (method === 'add') {
            this._keepDrawingByAdding(datum);
        }
        else {
            this._keepDrawingByReplacing(datum);
        }

    }

    _configureDatasource() {
        this.dispatcher = dispatch('onmessage', 'onopen', 'onerror');

        this.datasource.configure(this.dispatcher);

        this.dispatcher.on('onmessage', (data) => this.keepDrawing(data));

        this.dispatcher.on('onopen', (event) => {
            console.log('onopen', event);
        });

        this.dispatcher.on('onerror', (error) => {
            console.log('onerror', error);
        });
    }
    /**
     * Change a configuration property. They all are also available through a method with the same name of the property.
     *
     * @param {any} property property name
     * @param {any} value the new property value
     * @returns the instance of the current chart
     *
     * @memberOf Chart
     */
    change(property, value) {
        this._svg.strategy.changeConfigProperty(property, value);
        return this;
    }
}<commit_msg>Add chart docs<commit_after>import { dispatch } from 'd3';
import { SvgStrategy, strategies } from '../../svg/SvgStrategy';
import { svgAsDataUri } from '../../utils/image';

/**
 * Base class, which includes common methods for all the charts
 * @export Chart
 * @class Chart
 */
export default class Chart {
    /**
     * Non-instanciable Chart. This is the parent class for all the ones (Linechart, Barchart, etc.)
     *
     * @param {any} d Data. This object could be an array of data points or a datasource. Examples:
     * <pre class="prettyprint">
     * //With datasource
     * var data = {
     *       endpoint: 'ws://192.168.3.32:3000/barchart'
     * };
     *  var dataSource = new proteic.WebsocketDatasource(data);
     *
     * barchart = new proteic.Barchart(dataSource);
     *
     * //With data
     * barchart = new proteic.Barchart([{x:"SP", y:2},{x:"FR", y:6}]);
     * </pre>
     * @param {any} config Configuration of the chart.
     *
     * @memberOf Chart
     */
    constructor(d, config) {
        var clazz = this.constructor.name;
        if (clazz === 'Chart') {
            throw new Error(clazz + ' is non-instanciable');
        }

        this.events = {};

        if (!d && !config) {
            throw new Error('Missing constructor parameters');
        }

        let dataFormat = d.constructor.name;
        let nArguments = (d && config) ? 2 : 1;

        switch (dataFormat) {
            case 'WebsocketDatasource':
                this.datasource = d;
                this.data = [];
                this._configureDatasource();
                break;
            case 'Array':
                this.data = d;
                break;
            default:
                throw TypeError('Wrong data format');
        }
        //if only 1 parameter is specified, take default config. Else, take the second argument as config.
        this.config = (nArguments === 1) ? {} : config;

        this._initializeSVGContext();
    }

    /**
     * Private method. Initialize the API by dinamically creating methods. It creates N method, one per configuration option
     *
     * @param {any} properties An array that contains the name of the methods
     *
     * @memberOf Chart
     */
    _initializeAPI(properties) {
        let clazz = this.constructor;
        properties.forEach((method) => {
            clazz.prototype[method] = function (value) {
                return this.change(method, value);
            }
        });
    }

    /**
     * Return the chart context: data, configuration and type
     *
     * @returns chart Chart context
     *
     * @memberOf Chart
     */
    _getChartContext() {
        return {
            data: this.data,
            config: this.config,
            cType: this.constructor.name
        };
    }

    /**
     * Initialize the SVG context, by dinamically creating an <svg> tag in the specified selector. It is automatically invoked
     * by the chart constructor and should not be used outside of this instance.
     *
     * @memberOf Chart
     */
    _initializeSVGContext() {
        this._svg = new SvgStrategy(strategies[this.constructor.name](this._getChartContext()));
    }

    /**
     * Paint data into the chart. If no data is specified, it takes by default the last dataset (very useful when repaintng charts )
     *
     * @param {any} data Data to be painted
     *
     * @memberOf Chart
     */
    draw(data = this.data) {
        this._svg.draw(data);
    }

    /**
     * Make and download an image of the current state of the chart.
     *
     * @memberOf Chart
     */
    download() {
        let selector = this._svg.strategy.config.selector + ' ' + 'svg';
        svgAsDataUri(d3.select(selector).node(), {}, (uri, err) => {
            if (err) {
                throw Error('Error converting to image ' + err);
            }
            else {
                let link = document.createElement('a');
                link.style = 'position: fixed; left -10000px;'; // making it invisible
                link.href = uri
                link.download = this.constructor.name + '.svg';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        });
    }

    _keepDrawingByAdding(datum) {
        var datumType = datum.constructor;

        if (datumType === Array) {
            this.data = this.data.concat(datum);
        }
        else {
            this.data.push(datum);
        }

        this.draw(JSON.parse(JSON.stringify(this.data)));
    }

    _keepDrawingByReplacing(datum) {
        var datumType = datum.constructor;
        if (datumType === Array) {
            this.data = datum;
        }
        else {
            //TODO: find key by datum.x and replace it with new value
        }

        this.draw(JSON.parse(JSON.stringify(this.data)));
    }

    /**
     *
     * This method add a data record / array of data into the current data.
     * @param {any} datum
     * @param {any} method
     *
     * @memberOf Chart

     */
    keepDrawing(datum, method) {
        if (method === 'add') {
            this._keepDrawingByAdding(datum);
        }
        else {
            this._keepDrawingByReplacing(datum);
        }

    }

    _configureDatasource() {
        this.dispatcher = dispatch('onmessage', 'onopen', 'onerror');

        this.datasource.configure(this.dispatcher);

        this.dispatcher.on('onmessage', (data) => this.keepDrawing(data));

        this.dispatcher.on('onopen', (event) => {
            console.log('onopen', event);
        });

        this.dispatcher.on('onerror', (error) => {
            console.log('onerror', error);
        });
    }

    /**
     * Change a configuration property. They all are also available through a method with the same name of the property.
     *
     * @param {any} property property name
     * @param {any} value the new property value
     * @returns the instance of the current chart
     *
     * @memberOf Chart
     */
    change(property, value) {
        this._svg.strategy.changeConfigProperty(property, value);
        return this;
    }
}<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

//@ts-check

'use strict';

const withDefaults = require('../shared.webpack.config');

module.exports = withDefaults({
	context: __dirname,
	resolve: {
		mainFields: ['module', 'main']
	},
	entry: {
		extension: './src/extension.ts',
	}
});
<commit_msg>Try moving keytar to externals<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

//@ts-check

'use strict';

const withDefaults = require('../shared.webpack.config');

module.exports = withDefaults({
	context: __dirname,
	resolve: {
		mainFields: ['module', 'main']
	},
	entry: {
		extension: './src/extension.ts',
	},
	externals: {
		'keytar': 'commonjs keytar',
	},
});
<|endoftext|>


<commit_before>// global css
import './theme/theme.scss'

// classes you want to use immediately
import {App} from './App'
import reqwest from 'reqwest'
import queryString from 'query-string'
// import './vendor/scrollsnap-polyfill.bundled'
/**
 * entrance code for SPA
 */
function main() {
  document.title = 'Loading...'

  // Query string format: ?loc=us|au&filter=bad|good|mixed
  var dom = document.querySelector('.content')
  var hash = queryString.parse(location.search)
  var loc = 'au'
  var filter = null
  var lang = navigator.language || navigator.userLanguage

  if (hash.loc === 'us' || (!hash.loc && lang === 'en-US')) {
    loc = 'us'
  }

  if (hash.filter === 'neg' | hash.filter === 'pos' | hash.filter === 'mixed') {
    filter = hash.filter
  }

  const app = new App({
    dom: dom
  })

  reqwest({
    url: `https://s3.amazonaws.com/data.newsemote/${loc}/latest.json`,
    type: 'json',
    crossOrigin: true,
    success: (resp) => app.render(resp, loc, filter)
  })

  // we can make requests to multiple domains, check out proxy/rules.js

  // send request to github.com
  // http.get('https://s3.amazonaws.com/data.newsemote/us/latest.json').then((res) => {
  //   const data = JSON.parse(res)
  //   app.render(data)
  //   document.title = 'App Started'
  // })

  // // send request to npmjs.org
  // http.get('/node-1').then((json) => console.log('From npmjs.org: ', json))

  // console.log([1, 2, 3, 4].includes(1)) // ES7: Array.prototype.includes
}

document.addEventListener('DOMContentLoaded', main)
<commit_msg>add uk option<commit_after>// global css
import './theme/theme.scss'

// classes you want to use immediately
import {App} from './App'
import reqwest from 'reqwest'
import queryString from 'query-string'
// import './vendor/scrollsnap-polyfill.bundled'
/**
 * entrance code for SPA
 */
function main() {
  document.title = 'Loading...'

  // Query string format: ?loc=us|au&filter=bad|good|mixed
  var dom = document.querySelector('.content')
  var hash = queryString.parse(location.search)
  var loc = 'au'
  var filter = null
  var lang = navigator.language || navigator.userLanguage

  if (hash.loc === 'us' || (!hash.loc && lang.toLowerCase() === 'en-us')) {
    loc = 'us'
  } else if (hash.loc === 'uk') {
    loc = 'uk'
  }

  if (hash.filter === 'neg' | hash.filter === 'pos' | hash.filter === 'mixed') {
    filter = hash.filter
  }

  const app = new App({
    dom: dom
  })

  reqwest({
    url: `https://s3.amazonaws.com/data.newsemote/${loc}/latest.json`,
    type: 'json',
    crossOrigin: true,
    success: (resp) => app.render(resp, loc, filter)
  })

  // we can make requests to multiple domains, check out proxy/rules.js

  // send request to github.com
  // http.get('https://s3.amazonaws.com/data.newsemote/us/latest.json').then((res) => {
  //   const data = JSON.parse(res)
  //   app.render(data)
  //   document.title = 'App Started'
  // })

  // // send request to npmjs.org
  // http.get('/node-1').then((json) => console.log('From npmjs.org: ', json))

  // console.log([1, 2, 3, 4].includes(1)) // ES7: Array.prototype.includes
}

document.addEventListener('DOMContentLoaded', main)
<|endoftext|>


<commit_before>require("dotenv/config")

const chalk = require("chalk")

// @ts-check
const glob = require("glob")
const mime = require("mime")
const path = require("path")
const s3 = require("s3")
const { last } = require("lodash")

const options = {
  root: "public",
  files: path.join(__dirname, "../../**/public/**"),
  key: process.env.S3_KEY,
  secret: process.env.S3_SECRET,
  bucket: process.env.S3_BUCKET,
}

// See: https://www.npmjs.com/package/s3 for more options
const client = s3.createClient({
  s3Options: {
    accessKeyId: options.key,
    secretAccessKey: options.secret,
  },
})

const files = glob.sync(options.files, {
  ignore: "node_modules",
  nodir: true,
})

const generateHeaders = file => {
  const extension = path.extname(file)
  const contentType = mime.getType(extension)
  return {
    ACL: "public-read",
    CacheControl: "max-age=315360000, public",
    ContentType: contentType,
  }
}

console.log(chalk.green("[uploadToS3] Starting S3 sync...\n"))

files.forEach(file => {
  const s3Path = last(file.split(options.root)).substring(1)
  const uploader = client.uploadFile({
    localFile: file,

    // See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
    s3Params: {
      Bucket: options.bucket,
      Key: s3Path,
      ...generateHeaders(file),
    },
  })

  const start = Date.now()
  uploader.on("error", err => {
    console.error(
      chalk.red(`[uploadToS3] Error uploading ${s3Path}.\n`),
      err.stack,
      "\n"
    )
  })

  uploader.on("progress", () => {
    const now = Date.now()
    console.log(
      `[uploadToS3] ${s3Path} ${uploader.progressAmount} ${
        uploader.progressTotal
      } - ${now - start}ms`
    )
  })

  uploader.on("end", () => {
    const now = Date.now()
    console.log(`[uploadToS3] ${s3Path} - ${now - start}ms`)
  })
})
<commit_msg>fix(ci): Fix s3 upload path<commit_after>require("dotenv/config")

const chalk = require("chalk")

// @ts-check
const glob = require("glob")
const mime = require("mime")
const path = require("path")
const s3 = require("s3")
const { last } = require("lodash")

const options = {
  root: "public",
  files: path.join(__dirname, "../**/public/**"),
  key: process.env.S3_KEY,
  secret: process.env.S3_SECRET,
  bucket: process.env.S3_BUCKET,
}

// See: https://www.npmjs.com/package/s3 for more options
const client = s3.createClient({
  s3Options: {
    accessKeyId: options.key,
    secretAccessKey: options.secret,
  },
})

const files = glob.sync(options.files, {
  ignore: "node_modules",
  nodir: true,
})

const generateHeaders = file => {
  const extension = path.extname(file)
  const contentType = mime.getType(extension)
  return {
    ACL: "public-read",
    CacheControl: "max-age=315360000, public",
    ContentType: contentType,
  }
}

console.log(chalk.green("[uploadToS3] Starting S3 sync...\n"))

files.forEach(file => {
  const s3Path = last(file.split(options.root)).substring(1)
  const uploader = client.uploadFile({
    localFile: file,

    // See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
    s3Params: {
      Bucket: options.bucket,
      Key: s3Path,
      ...generateHeaders(file),
    },
  })

  const start = Date.now()
  uploader.on("error", err => {
    console.error(
      chalk.red(`[uploadToS3] Error uploading ${s3Path}.\n`),
      err.stack,
      "\n"
    )
  })

  uploader.on("progress", () => {
    const now = Date.now()
    console.log(
      `[uploadToS3] ${s3Path} ${uploader.progressAmount} ${
        uploader.progressTotal
      } - ${now - start}ms`
    )
  })

  uploader.on("end", () => {
    const now = Date.now()
    console.log(`[uploadToS3] ${s3Path} - ${now - start}ms`)
  })
})
<|endoftext|>


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

var prePackage = require('./package');
var fluid = require('fluid-publish');
prePackage.prepare();
var options = {
	devTag: 'nightly',
	changesCmd: 'git status -s -uno > /dev/null',
	publishCmd: 'npm publish --tag=nightly'
};
fluid.dev(false, options);
prePackage.restore();
<commit_msg>chore(devOps): fix import package to publish nightly<commit_after>#!/usr/bin/env node

var prePackage = require('./package-json');
var fluid = require('fluid-publish');
prePackage.prepare();
var options = {
	devTag: 'nightly',
	changesCmd: 'git status -s -uno > /dev/null',
	publishCmd: 'npm publish --tag=nightly'
};
fluid.dev(false, options);
prePackage.restore();
<|endoftext|>


<commit_before>
(function(){

  window.SteemMoreInfo.Events.addEventListener(window, 'voters-list-show', function(e) {
    var votersList = e.state;
    if(!votersList.hasClass('smi-voting-info-shown')){

      var author;
      var permlink;

      var hentry = votersList.closest('.hentry');
      if(hentry.is('article') || votersList.closest('.smi-post-footer-wrapper-2').length){
        var url = window.location.pathname;
        var match = url.match(/\/[^\/]*\/@([^\/]*)\/(.*)$/);
        author = match[1];
        permlink = match[2];
      }else{
        var id = hentry.attr('id');
        var match = id.match(/\#@([^\/]*)\/(.*)$/);
        author = match[1];
        permlink = match[2];
      }
      if(!author || !permlink){
        return;
      }

      votersList.addClass('smi-voting-info-shown');
      var moreButtonLi;
      var voteElsByVoter = {};

      // prevent page scroll if mouse is no top of the list
      votersList.bind('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
            bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
      });

      votersList.children().each(function(){
        var li = $(this);
        if(!li.has('a').length){
          moreButtonLi = li;
          return;
        }
        var voteWeigth = $('');
        var voteDollar = $('');
        li.append(voteWeigth);
        li.append(voteDollar);

        var href = li.find('a').attr('href');
        var voter = href.substring(2);

        voteElsByVoter[voter] = voteElsByVoter[voter] || [];
        voteElsByVoter[voter].push(li);
      });

      window.SteemMoreInfo.Utils.getContent(author, permlink, function(err, result){
        if(!result){
          return;
        }
        var newElCount = 0;
        var active_votes = _.sortBy(result.active_votes, function(v){
          return -parseInt(v.rshares);
        });
        _.each(active_votes, function(vote) {
          var voter = vote.voter;
          var voteDollar = vote.voteDollar;
          var votePercent = Math.round(vote.percent / 100);
          if(voteDollar){
            var voteEls = voteElsByVoter[voter] || [];
            if(!voteEls.length){
              var newEl = $('
' +
                '' +
                (votePercent >= 0 ? '+' : '-') + ' ' + voter +
                '' +
                '' +
                '' +
                '
');
              votersList.append(newEl);
              newElCount++;
              voteEls.push(newEl);
            }
            _.each(voteEls, function(voteEl) {
              voteEl.find('.vote-weight').text(votePercent + '%');
              voteEl.find('.vote-dollar').text('≈ ' + voteDollar + '$');
            });
          }
        });
        if(newElCount && moreButtonLi){
          moreButtonLi.remove();
        }
      });

    }
  });

})();
<commit_msg>Fix votes list<commit_after>
(function(){

  window.SteemMoreInfo.Events.addEventListener(window, 'voters-list-show', function(e) {
    var votersList = e.state;
    if(!votersList.hasClass('smi-voting-info-shown')){

      var author;
      var permlink;

      var hentry = votersList.closest('.hentry');
      var hrefA = hentry.length && hentry.find('.PostFull__responses a');
      if(hrefA.length){
        var url = hrefA.attr('href');
        var match = url.match(/\/[^\/]*\/@([^\/]*)\/(.*)$/);
        author = match[1];
        permlink = match[2];
      }else if(hentry.is('article') || votersList.closest('.smi-post-footer-wrapper-2').length){
        var url = window.location.pathname;
        var match = url.match(/\/[^\/]*\/@([^\/]*)\/(.*)$/);
        author = match[1];
        permlink = match[2];
      }else{
        var id = hentry.attr('id');
        var match = id.match(/\#@([^\/]*)\/(.*)$/);
        author = match[1];
        permlink = match[2];
      }
      if(!author || !permlink){
        return;
      }

      votersList.addClass('smi-voting-info-shown');
      var moreButtonLi;
      var voteElsByVoter = {};

      // prevent page scroll if mouse is no top of the list
      votersList.bind('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
            bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
      });

      votersList.children().each(function(){
        var li = $(this);
        if(!li.has('a').length){
          moreButtonLi = li;
          return;
        }
        var voteWeigth = $('');
        var voteDollar = $('');
        li.append(voteWeigth);
        li.append(voteDollar);

        var href = li.find('a').attr('href');
        var voter = href.substring(2);

        voteElsByVoter[voter] = voteElsByVoter[voter] || [];
        voteElsByVoter[voter].push(li);
      });

      window.SteemMoreInfo.Utils.getContent(author, permlink, function(err, result){
        if(!result){
          return;
        }
        var newElCount = 0;
        var active_votes = _.sortBy(result.active_votes, function(v){
          return -parseInt(v.rshares);
        });
        _.each(active_votes, function(vote) {
          var voter = vote.voter;
          var voteDollar = vote.voteDollar;
          var votePercent = Math.round(vote.percent / 100);
          if(voteDollar){
            var voteEls = voteElsByVoter[voter] || [];
            if(!voteEls.length){
              var newEl = $('
' +
                '' +
                (votePercent >= 0 ? '+' : '-') + ' ' + voter +
                '' +
                '' +
                '' +
                '
');
              votersList.append(newEl);
              newElCount++;
              voteEls.push(newEl);
            }
            _.each(voteEls, function(voteEl) {
              voteEl.find('.vote-weight').text(votePercent + '%');
              voteEl.find('.vote-dollar').text('≈ ' + voteDollar + '$');
            });
          }
        });
        if(newElCount && moreButtonLi){
          moreButtonLi.remove();
        }
      });

    }
  });

})();
<|endoftext|>


<commit_before>module.exports = createTask

var changelog = require('changelog')
  // , packageDetails = require('../package.json')

function createTask (pliers) {

  pliers('buildChangelog', function (done) {

    var content = []
      , previousVersion = ''

    changelog.generate('gulp').then(function (data) {
      data.versions.forEach(function (version) {
        var currentVersion = 'v' + version.version
          , versions = previousVersion + '...' + currentVersion

        if (previousVersion.length) {
          content.push('### Changes')
          content.push('[' + versions + '](' + data.project.repository + '/compare/' + versions + ')')
          content.push('')
        }

        content.push('## ' + currentVersion + ' / ' + version.date)
        content.push('')
        content.push('### Highlights')

        data.versions.forEach(function (version) {
          content.push('* ' + version.message)
        })

        content.push('')

        previousVersion = currentVersion
      })

      console.log(content.join('\n'))

      done()
    })

  })

}
<commit_msg>> Adds changes to output<commit_after>module.exports = createTask

var changelog = require('changelog')
  , packageDetails = require('../package.json')

function createTask (pliers) {

  pliers('buildChangelog', function (done) {

    var content = []
      , previousVersion = ''

    changelog.generate(packageDetails.name, packageDetails.version).then(function (data) {
      data.versions.forEach(function (version) {
        var currentVersion = 'v' + version.version
          , versions = previousVersion + '...' + currentVersion

        if (previousVersion.length) {
          content.push('### Changes')
          content.push('[' + versions + '](' + data.project.repository + '/compare/' + versions + ')')
          content.push('')
        }

        content.push('## ' + currentVersion + ' / ' + version.date)
        content.push('')
        content.push('### Highlights')

        version.changes.forEach(function (change) {
          var message = change.message.split('\n')[0]

          if (message && message.match(/^[^>v]/gm)) {
            content.push('* ' + message)
          }
        })

        content.push('')

        previousVersion = currentVersion
      })

      console.log(content.join('\n'))

      done()
    })

  })

}
<|endoftext|>


<commit_before>describe("Dragdealer API", function() {

  beforeEach(function() {
    this.addMatchers(matchers);
    jasmine.Clock.useMock();
  });

  it("should set .disabled class on disable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider');

    expect($('#simple-slider .handle')).not.toHaveClass('disabled');
    dragdealer.disable();
    expect($('#simple-slider .handle')).toHaveClass('disabled');
  });

  // FIXME
  xit("should unset .disabled class on enable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      disabled: true
    });

    expect($('#simple-slider .handle')).toHaveClass('disabled');
    dragdealer.enable();
    expect($('#simple-slider .handle')).not.toHaveClass('disabled');
  });

  it("should disable dragging on disable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      slide: false
    });

    helpers.dragTo('simple-slider', 100, 0);
    helpers.drop('simple-slider');
    expect('simple-slider').toHavePosition(100, 0);

    dragdealer.disable();
    helpers.dragTo('simple-slider', 200, 0);
    expect('simple-slider').toHavePosition(100, 0);
  });

  it("should enable dragging on enable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      disabled: true,
      slide: false
    });

    helpers.dragTo('simple-slider', 100, 0);
    helpers.drop('simple-slider');
    expect('simple-slider').toHavePosition(0, 0);

    dragdealer.enable();
    helpers.dragTo('simple-slider', 200, 0);
    expect('simple-slider').toHavePosition(200, 0);
  });
});
<commit_msg>Add (some failing) specs for API methods #1<commit_after>describe("Dragdealer API", function() {

  beforeEach(function() {
    this.addMatchers(matchers);
    jasmine.Clock.useMock();
  });

  it("should set .disabled class on disable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider');

    expect($('#simple-slider .handle')).not.toHaveClass('disabled');
    dragdealer.disable();
    expect($('#simple-slider .handle')).toHaveClass('disabled');
  });

  // FIXME
  xit("should unset .disabled class on enable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      disabled: true
    });

    expect($('#simple-slider .handle')).toHaveClass('disabled');
    dragdealer.enable();
    expect($('#simple-slider .handle')).not.toHaveClass('disabled');
  });

  it("should disable dragging on disable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      slide: false
    });

    helpers.dragTo('simple-slider', 100, 0);
    helpers.drop('simple-slider');
    expect('simple-slider').toHavePosition(100, 0);

    dragdealer.disable();
    helpers.dragTo('simple-slider', 200, 0);
    expect('simple-slider').toHavePosition(100, 0);
  });

  it("should enable dragging on enable()", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      disabled: true,
      slide: false
    });

    helpers.dragTo('simple-slider', 100, 0);
    helpers.drop('simple-slider');
    expect('simple-slider').toHavePosition(0, 0);

    dragdealer.enable();
    helpers.dragTo('simple-slider', 200, 0);
    expect('simple-slider').toHavePosition(200, 0);
  });

  it("should slide handle to position on setValue(x, y)", function() {
    var dragdealer = helpers.initDragdealer('square-slider', {
      horizontal: true,
      vertical: true
    });

    dragdealer.setValue(1, 0.5);
    jasmine.Clock.tick(3000);
    expect('square-slider').toHavePosition(400, 200);
  });

  // FIXME
  xit("should snap handle to position on setValue(x, y, true)", function() {
    var dragdealer = helpers.initDragdealer('square-slider', {
      horizontal: true,
      vertical: true
    });

    dragdealer.setValue(1, 0.5, true);
    jasmine.Clock.tick(25);
    expect('square-slider').toHavePosition(400, 200);
  });

  it("should slide handle to step position on setStep(x, y)", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      steps: 6
    });

    dragdealer.setStep(2, 0);
    jasmine.Clock.tick(3000);
    expect('simple-slider').toHavePosition(80, 0);
  });

  // FIXME
  xit("should snap handle to step position on setStep(x, y, true)", function() {
    var dragdealer = helpers.initDragdealer('simple-slider', {
      steps: 6
    });

    dragdealer.setStep(2, 0, true);
    jasmine.Clock.tick(25);
    expect('simple-slider').toHavePosition(80, 0);
  });
});
<|endoftext|>


<commit_before>export { default as moduleFor } from './legacy-2-x/module-for';
export { default as moduleForComponent } from './legacy-2-x/module-for-component';
export { default as moduleForModel } from './legacy-2-x/module-for-model';
export { default as QUnitAdapter } from './adapter';
export { module, test, skip, only, todo } from 'qunit';
export { loadTests } from './test-loader';

import { deprecate } from '@ember/debug';
import { loadTests } from './test-loader';
import Ember from 'ember';
import QUnit from 'qunit';
import QUnitAdapter from './adapter';
import {
  setResolver as upstreamSetResolver,
  render as upstreamRender,
  clearRender as upstreamClearRender,
  settled as upstreamSettled,
  pauseTest as upstreamPauseTest,
  resumeTest as upstreamResumeTest,
  setupContext,
  teardownContext,
  setupRenderingContext,
  teardownRenderingContext,
  setupApplicationContext,
  teardownApplicationContext,
  validateErrorHandler,
} from '@ember/test-helpers';

export function setResolver() {
  deprecate(
    '`setResolver` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.setResolver',
      until: '4.0.0',
    }
  );

  return upstreamSetResolver(...arguments);
}

export function render() {
  deprecate(
    '`render` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.render',
      until: '4.0.0',
    }
  );

  return upstreamRender(...arguments);
}

export function clearRender() {
  deprecate(
    '`clearRender` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.clearRender',
      until: '4.0.0',
    }
  );

  return upstreamClearRender(...arguments);
}

export function settled() {
  deprecate(
    '`settled` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.settled',
      until: '4.0.0',
    }
  );

  return upstreamSettled(...arguments);
}

export function pauseTest() {
  deprecate(
    '`pauseTest` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.pauseTest',
      until: '4.0.0',
    }
  );

  return upstreamPauseTest(...arguments);
}

export function resumeTest() {
  deprecate(
    '`resumeTest` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.resumeTest',
      until: '4.0.0',
    }
  );

  return upstreamResumeTest(...arguments);
}

export function setupTest(hooks, options) {
  hooks.beforeEach(function(assert) {
    return setupContext(this, options).then(() => {
      let originalPauseTest = this.pauseTest;
      this.pauseTest = function QUnit_pauseTest() {
        assert.timeout(-1); // prevent the test from timing out

        return originalPauseTest.call(this);
      };
    });
  });

  hooks.afterEach(function() {
    return teardownContext(this);
  });
}

export function setupRenderingTest(hooks, options) {
  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupRenderingContext(this);
  });

  hooks.afterEach(function() {
    return teardownRenderingContext(this);
  });
}

export function setupApplicationTest(hooks, options) {
  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupApplicationContext(this);
  });

  hooks.afterEach(function() {
    return teardownApplicationContext(this);
  });
}

/**
   Uses current URL configuration to setup the test container.

   * If `?nocontainer` is set, the test container will be hidden.
   * If `?dockcontainer` or `?devmode` are set the test container will be
     absolutely positioned.
   * If `?devmode` is set, the test container will be made full screen.

   @method setupTestContainer
 */
export function setupTestContainer() {
  let testContainer = document.getElementById('ember-testing-container');
  if (!testContainer) {
    return;
  }

  let params = QUnit.urlParams;

  let containerVisibility = params.nocontainer ? 'hidden' : 'visible';
  let containerPosition = params.dockcontainer || params.devmode ? 'fixed' : 'relative';

  if (params.devmode) {
    testContainer.className = ' full-screen';
  }

  testContainer.style.visibility = containerVisibility;
  testContainer.style.position = containerPosition;

  let qunitContainer = document.getElementById('qunit');
  if (params.dockcontainer) {
    qunitContainer.style.marginBottom = window.getComputedStyle(testContainer).height;
  }
}

/**
   Instruct QUnit to start the tests.
   @method startTests
 */
export function startTests() {
  QUnit.start();
}

/**
   Sets up the `Ember.Test` adapter for usage with QUnit 2.x.

   @method setupTestAdapter
 */
export function setupTestAdapter() {
  Ember.Test.adapter = QUnitAdapter.create();
}

/**
  Ensures that `Ember.testing` is set to `true` before each test begins
  (including `before` / `beforeEach`), and reset to `false` after each test is
  completed. This is done via `QUnit.testStart` and `QUnit.testDone`.

 */
export function setupEmberTesting() {
  QUnit.testStart(() => {
    Ember.testing = true;
  });

  QUnit.testDone(() => {
    Ember.testing = false;
  });
}

/**
  Ensures that `Ember.onerror` (if present) is properly configured to re-throw
  errors that occur while `Ember.testing` is `true`.
*/
export function setupEmberOnerrorValidation() {
  QUnit.module('ember-qunit: Ember.onerror validation', function() {
    QUnit.test('Ember.onerror is functioning properly', function(assert) {
      let result = validateErrorHandler();
      assert.ok(
        result.isValid,
        `Ember.onerror handler with invalid testing behavior detected. An Ember.onerror handler _must_ rethrow exceptions when \`Ember.testing\` is \`true\` or the test suite is unreliable. See https://git.io/vbine for more details.`
      );
    });
  });
}

/**
   @method start
   @param {Object} [options] Options to be used for enabling/disabling behaviors
   @param {Boolean} [options.loadTests] If `false` tests will not be loaded automatically.
   @param {Boolean} [options.setupTestContainer] If `false` the test container will not
   be setup based on `devmode`, `dockcontainer`, or `nocontainer` URL params.
   @param {Boolean} [options.startTests] If `false` tests will not be automatically started
   (you must run `QUnit.start()` to kick them off).
   @param {Boolean} [options.setupTestAdapter] If `false` the default Ember.Test adapter will
   not be updated.
   @param {Boolean} [options.setupEmberTesting] `false` opts out of the
   default behavior of setting `Ember.testing` to `true` before all tests and
   back to `false` after each test will.
   @param {Boolean} [options.setupEmberOnerrorValidation] If `false` validation
   of `Ember.onerror` will be disabled.
 */
export function start(options = {}) {
  if (options.loadTests !== false) {
    loadTests();
  }

  if (options.setupTestContainer !== false) {
    setupTestContainer();
  }

  if (options.setupTestAdapter !== false) {
    setupTestAdapter();
  }

  if (options.setupEmberTesting !== false) {
    setupEmberTesting();
  }

  if (options.setupEmberOnerrorValidation !== false) {
    setupEmberOnerrorValidation();
  }

  if (options.startTests !== false) {
    startTests();
  }
}
<commit_msg>Add assert.expect to Ember.onerror validation test<commit_after>export { default as moduleFor } from './legacy-2-x/module-for';
export { default as moduleForComponent } from './legacy-2-x/module-for-component';
export { default as moduleForModel } from './legacy-2-x/module-for-model';
export { default as QUnitAdapter } from './adapter';
export { module, test, skip, only, todo } from 'qunit';
export { loadTests } from './test-loader';

import { deprecate } from '@ember/debug';
import { loadTests } from './test-loader';
import Ember from 'ember';
import QUnit from 'qunit';
import QUnitAdapter from './adapter';
import {
  setResolver as upstreamSetResolver,
  render as upstreamRender,
  clearRender as upstreamClearRender,
  settled as upstreamSettled,
  pauseTest as upstreamPauseTest,
  resumeTest as upstreamResumeTest,
  setupContext,
  teardownContext,
  setupRenderingContext,
  teardownRenderingContext,
  setupApplicationContext,
  teardownApplicationContext,
  validateErrorHandler,
} from '@ember/test-helpers';

export function setResolver() {
  deprecate(
    '`setResolver` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.setResolver',
      until: '4.0.0',
    }
  );

  return upstreamSetResolver(...arguments);
}

export function render() {
  deprecate(
    '`render` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.render',
      until: '4.0.0',
    }
  );

  return upstreamRender(...arguments);
}

export function clearRender() {
  deprecate(
    '`clearRender` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.clearRender',
      until: '4.0.0',
    }
  );

  return upstreamClearRender(...arguments);
}

export function settled() {
  deprecate(
    '`settled` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.settled',
      until: '4.0.0',
    }
  );

  return upstreamSettled(...arguments);
}

export function pauseTest() {
  deprecate(
    '`pauseTest` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.pauseTest',
      until: '4.0.0',
    }
  );

  return upstreamPauseTest(...arguments);
}

export function resumeTest() {
  deprecate(
    '`resumeTest` should be imported from `@ember/test-helpers`, but was imported from `ember-qunit`',
    false,
    {
      id: 'ember-qunit.deprecated-reexports.resumeTest',
      until: '4.0.0',
    }
  );

  return upstreamResumeTest(...arguments);
}

export function setupTest(hooks, options) {
  hooks.beforeEach(function(assert) {
    return setupContext(this, options).then(() => {
      let originalPauseTest = this.pauseTest;
      this.pauseTest = function QUnit_pauseTest() {
        assert.timeout(-1); // prevent the test from timing out

        return originalPauseTest.call(this);
      };
    });
  });

  hooks.afterEach(function() {
    return teardownContext(this);
  });
}

export function setupRenderingTest(hooks, options) {
  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupRenderingContext(this);
  });

  hooks.afterEach(function() {
    return teardownRenderingContext(this);
  });
}

export function setupApplicationTest(hooks, options) {
  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupApplicationContext(this);
  });

  hooks.afterEach(function() {
    return teardownApplicationContext(this);
  });
}

/**
   Uses current URL configuration to setup the test container.

   * If `?nocontainer` is set, the test container will be hidden.
   * If `?dockcontainer` or `?devmode` are set the test container will be
     absolutely positioned.
   * If `?devmode` is set, the test container will be made full screen.

   @method setupTestContainer
 */
export function setupTestContainer() {
  let testContainer = document.getElementById('ember-testing-container');
  if (!testContainer) {
    return;
  }

  let params = QUnit.urlParams;

  let containerVisibility = params.nocontainer ? 'hidden' : 'visible';
  let containerPosition = params.dockcontainer || params.devmode ? 'fixed' : 'relative';

  if (params.devmode) {
    testContainer.className = ' full-screen';
  }

  testContainer.style.visibility = containerVisibility;
  testContainer.style.position = containerPosition;

  let qunitContainer = document.getElementById('qunit');
  if (params.dockcontainer) {
    qunitContainer.style.marginBottom = window.getComputedStyle(testContainer).height;
  }
}

/**
   Instruct QUnit to start the tests.
   @method startTests
 */
export function startTests() {
  QUnit.start();
}

/**
   Sets up the `Ember.Test` adapter for usage with QUnit 2.x.

   @method setupTestAdapter
 */
export function setupTestAdapter() {
  Ember.Test.adapter = QUnitAdapter.create();
}

/**
  Ensures that `Ember.testing` is set to `true` before each test begins
  (including `before` / `beforeEach`), and reset to `false` after each test is
  completed. This is done via `QUnit.testStart` and `QUnit.testDone`.

 */
export function setupEmberTesting() {
  QUnit.testStart(() => {
    Ember.testing = true;
  });

  QUnit.testDone(() => {
    Ember.testing = false;
  });
}

/**
  Ensures that `Ember.onerror` (if present) is properly configured to re-throw
  errors that occur while `Ember.testing` is `true`.
*/
export function setupEmberOnerrorValidation() {
  QUnit.module('ember-qunit: Ember.onerror validation', function() {
    QUnit.test('Ember.onerror is functioning properly', function(assert) {
      assert.expect(1);
      let result = validateErrorHandler();
      assert.ok(
        result.isValid,
        `Ember.onerror handler with invalid testing behavior detected. An Ember.onerror handler _must_ rethrow exceptions when \`Ember.testing\` is \`true\` or the test suite is unreliable. See https://git.io/vbine for more details.`
      );
    });
  });
}

/**
   @method start
   @param {Object} [options] Options to be used for enabling/disabling behaviors
   @param {Boolean} [options.loadTests] If `false` tests will not be loaded automatically.
   @param {Boolean} [options.setupTestContainer] If `false` the test container will not
   be setup based on `devmode`, `dockcontainer`, or `nocontainer` URL params.
   @param {Boolean} [options.startTests] If `false` tests will not be automatically started
   (you must run `QUnit.start()` to kick them off).
   @param {Boolean} [options.setupTestAdapter] If `false` the default Ember.Test adapter will
   not be updated.
   @param {Boolean} [options.setupEmberTesting] `false` opts out of the
   default behavior of setting `Ember.testing` to `true` before all tests and
   back to `false` after each test will.
   @param {Boolean} [options.setupEmberOnerrorValidation] If `false` validation
   of `Ember.onerror` will be disabled.
 */
export function start(options = {}) {
  if (options.loadTests !== false) {
    loadTests();
  }

  if (options.setupTestContainer !== false) {
    setupTestContainer();
  }

  if (options.setupTestAdapter !== false) {
    setupTestAdapter();
  }

  if (options.setupEmberTesting !== false) {
    setupEmberTesting();
  }

  if (options.setupEmberOnerrorValidation !== false) {
    setupEmberOnerrorValidation();
  }

  if (options.startTests !== false) {
    startTests();
  }
}
<|endoftext|>


<commit_before>var expect = require("chai").expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
}

function add(A, B){
  if (A === "zero" && B === "zero"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "one"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "two"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "three"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "four"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "five"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "six"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "seven"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "eight"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "zero" && B === "nine"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "zero"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "one"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "two"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "three"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "four"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "five"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "six"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "seven"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "eight"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "one" && B === "nine"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "zero"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "one"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "two"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "three"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "four"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "five"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "six"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "seven"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "eight"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "two" && B === "nine"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "zero"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "one"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "two"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "three"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "four"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "five"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "six"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "seven"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "eight"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "three" && B === "nine"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "zero"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "one"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "two"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "three"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "four"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "five"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "six"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "seven"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "eight"){
    return toNumber(A) + toNumber(B);
  }
  if (A === "four" && B === "nine"){
    return toNumber(A) + toNumber(B);
  }
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1);
expect(toNumber("two")).to.equal(2);
expect(toNumber("three")).to.equal(3);
expect(toNumber("four")).to.equal(4);
expect(toNumber("five")).to.equal(5);
expect(toNumber("six")).to.equal(6);
expect(toNumber("seven")).to.equal(7);
expect(toNumber("eight")).to.equal(8);
expect(toNumber("nine")).to.equal(9);

expect(add).to.exist;
expect(add("zero", "zero")).to.equal(0);
expect(add("zero", "one")).to.equal(1);
expect(add("zero", "two")).to.equal(2);
expect(add("zero", "three")).to.equal(3);
expect(add("zero", "four")).to.equal(4);
expect(add("zero", "five")).to.equal(5);
expect(add("zero", "six")).to.equal(6);
expect(add("zero", "seven")).to.equal(7);
expect(add("zero", "eight")).to.equal(8);
expect(add("zero", "nine")).to.equal(9);
expect(add("one", "zero")).to.equal(1);
expect(add("one", "one")).to.equal(2);
expect(add("one", "two")).to.equal(3);
expect(add("one", "three")).to.equal(4);
expect(add("one", "four")).to.equal(5);
expect(add("one", "five")).to.equal(6);
expect(add("one", "six")).to.equal(7);
expect(add("one", "seven")).to.equal(8);
expect(add("one", "eight")).to.equal(9);
expect(add("one", "nine")).to.equal(10);
expect(add("two", "zero")).to.equal(2);
expect(add("two", "one")).to.equal(3);
expect(add("two", "two")).to.equal(4);
expect(add("two", "three")).to.equal(5);
expect(add("two", "four")).to.equal(6);
expect(add("two", "five")).to.equal(7);
expect(add("two", "six")).to.equal(8);
expect(add("two", "seven")).to.equal(9);
expect(add("two", "eight")).to.equal(10);
expect(add("two", "nine")).to.equal(11);
expect(add("three", "zero")).to.equal(3);
expect(add("three", "one")).to.equal(4);
expect(add("three", "two")).to.equal(5);
expect(add("three", "three")).to.equal(6);
expect(add("three", "four")).to.equal(7);
expect(add("three", "five")).to.equal(8);
expect(add("three", "six")).to.equal(9);
expect(add("three", "seven")).to.equal(10);
expect(add("three", "eight")).to.equal(11);
expect(add("three", "nine")).to.equal(12);
expect(add("four", "zero")).to.equal(4);
expect(add("four", "one")).to.equal(5);
expect(add("four", "two")).to.equal(6);
expect(add("four", "three")).to.equal(7);
expect(add("four", "four")).to.equal(8);
expect(add("four", "five")).to.equal(9);
expect(add("four", "six")).to.equal(10);
expect(add("four", "seven")).to.equal(11);
expect(add("four", "eight")).to.equal(12);
expect(add("four", "nine")).to.equal(13);
expect(add("five", "zero")).to.equal(5);
expect(add("five", "one")).to.equal(6);
expect(add("five", "two")).to.equal(7);
expect(add("five", "three")).to.equal(8);
expect(add("five", "four")).to.equal(9);
expect(add("five", "five")).to.equal(10);
expect(add("five", "six")).to.equal(11);
expect(add("five", "seven")).to.equal(12);
expect(add("five", "eight")).to.equal(13);
expect(add("five", "nine")).to.equal(14);

console.log(add("zero", "one"))

console.log(1/9)

// NIGHTMARE MODE

/* function plus(A, B){
  return (toNumber(A) + toNumber(B));
}

function minus(A, B){
  return (toNumber(A) - toNumber(B));
}

function multiply(A, B){
  return (toNumber(A) * toNumber(B));
}

function divide(A, B){
  return (toNumber(A) / toNumber(B));
}

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);

expect(minus).to.exist;
expect(minus("four", "two")).to.equal(2);

expect(multiply).to.exist;
expect(multiply("five", "three")).to.equal(15);

console.log(multiply("three", "four"))

expect(divide).to.exist;
expect(divide("five", "one").to.equal(5) */
<commit_msg>redoing adding up to five,nine. I was thinking too 'Nightmare mode', thanks @mstaehling<commit_after>var expect = require("chai").expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
}

function add(A, B){
  if (A === "zero" && B === "zero"){
    var A = 0;
    var B = 0;
  }
  if (A === "zero" && B === "one"){
    var A = 0;
    var B = 1;
  }
  if (A === "zero" && B === "two"){
    var A = 0;
    var B = 2;
  }
  if (A === "zero" && B === "three"){
    var A = 0;
    var B = 3;
  }
  if (A === "zero" && B === "four"){
    var A = 0;
    var B = 4;
  }
  if (A === "zero" && B === "five"){
    var A = 0;
    var B = 5;
  }
  if (A === "zero" && B === "six"){
    var A = 0;
    var B = 6;
  }
  if (A === "zero" && B === "seven"){
    var A = 0;
    var B = 7;
  }
  if (A === "zero" && B === "eight"){
    var A = 0;
    var B = 8;
  }
  if (A === "zero" && B === "nine"){
    var A = 0;
    var B = 9;
  }
  if (A === "one" && B === "zero"){
    var A = 1;
    var B = 0;
  }
  if (A === "one" && B === "one"){
    var A = 1;
    var B = 1;
  }
  if (A === "one" && B === "two"){
    var A = 1;
    var B = 2;
  }
  if (A === "one" && B === "three"){
    var A = 1;
    var B = 3;
  }
  if (A === "one" && B === "four"){
    var A = 1;
    var B = 4;
  }
  if (A === "one" && B === "five"){
    var A = 1;
    var B = 5;
  }
  if (A === "one" && B === "six"){
    var A = 1;
    var B = 6;
  }
  if (A === "one" && B === "seven"){
    var A = 1;
    var B = 7;
  }
  if (A === "one" && B === "eight"){
    var A = 1;
    var B = 8;
  }
  if (A === "one" && B === "nine"){
    var A = 1;
    var B = 9;
  }
  if (A === "two" && B === "zero"){
    var A = 2;
    var B = 0;
  }
  if (A === "two" && B === "one"){
    var A = 2;
    var B = 1;
  }
  if (A === "two" && B === "two"){
    var A = 2;
    var B = 2;
  }
  if (A === "two" && B === "three"){
    var A = 2;
    var B = 3;
  }
  if (A === "two" && B === "four"){
    var A = 2;
    var B = 4;
  }
  if (A === "two" && B === "five"){
    var A = 2;
    var B = 5;
  }
  if (A === "two" && B === "six"){
    var A = 2;
    var B = 6;
  }
  if (A === "two" && B === "seven"){
    var A = 2;
    var B = 7;
  }
  if (A === "two" && B === "eight"){
    var A = 2;
    var B = 8;
  }
  if (A === "two" && B === "nine"){
    var A = 2;
    var B = 9;
  }
  if (A === "three" && B === "zero"){
    var A = 3;
    var B = 0;
  }
  if (A === "three" && B === "one"){
    var A = 3;
    var B = 1;
  }
  if (A === "three" && B === "two"){
    var A = 3;
    var B = 2;
  }
  if (A === "three" && B === "three"){
    var A = 3;
    var B = 3;
  }
  if (A === "three" && B === "four"){
    var A = 3;
    var B = 4;
  }
  if (A === "three" && B === "five"){
    var A = 3;
    var B = 5;
  }
  if (A === "three" && B === "six"){
    var A = 3;
    var B = 6;
  }
  if (A === "three" && B === "seven"){
    var A = 3;
    var B = 7;
  }
  if (A === "three" && B === "eight"){
    var A = 3;
    var B = 8;
  }
  if (A === "three" && B === "nine"){
    var A = 3;
    var B = 9;
  }
  if (A === "four" && B === "zero"){
    var A = 4;
    var B = 0;
  }
  if (A === "four" && B === "one"){
    var A = 4;
    var B = 1;
  }
  if (A === "four" && B === "two"){
    var A = 4;
    var B = 2;
  }
  if (A === "four" && B === "three"){
    var A = 4;
    var B = 3;
  }
  if (A === "four" && B === "four"){
    var A = 4;
    var B = 4;
  }
  if (A === "four" && B === "five"){
    var A = 4;
    var B = 5;
  }
  if (A === "four" && B === "six"){
    var A = 4;
    var B = 6;
  }
  if (A === "four" && B === "seven"){
    var A = 4;
    var B = 7;
  }
  if (A === "four" && B === "eight"){
    var A = 4;
    var B = 8;
  }
  if (A === "four" && B === "nine"){
    var A = 4;
    var B = 9;
  }
  if (A === "five" && B === "zero"){
    var A = 5;
    var B = 0;
  }
  if (A === "five" && B === "one"){
    var A = 5;
    var B = 1;
  }
  if (A === "five" && B === "two"){
    var A = 5;
    var B = 2;
  }
  if (A === "five" && B === "three"){
    var A = 5;
    var B = 3;
  }
  if (A === "five" && B === "four"){
    var A = 5;
    var B = 4;
  }
  if (A === "five" && B === "five"){
    var A = 5;
    var B = 5;
  }
  if (A === "five" && B === "six"){
    var A = 5;
    var B = 6;
  }
  if (A === "five" && B === "seven"){
    var A = 5;
    var B = 7;
  }
  if (A === "five" && B ==="eight"){
    var A = 5
    var B = 8
  }
  if (A === "five" && B === "nine"){
    var A = 5
    var B = 9
  }
  return A + B
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1);
expect(toNumber("two")).to.equal(2);
expect(toNumber("three")).to.equal(3);
expect(toNumber("four")).to.equal(4);
expect(toNumber("five")).to.equal(5);
expect(toNumber("six")).to.equal(6);
expect(toNumber("seven")).to.equal(7);
expect(toNumber("eight")).to.equal(8);
expect(toNumber("nine")).to.equal(9);

expect(add).to.exist;
expect(add("zero", "zero")).to.equal(0);
expect(add("zero", "one")).to.equal(1);
expect(add("zero", "two")).to.equal(2);
expect(add("zero", "three")).to.equal(3);
expect(add("zero", "four")).to.equal(4);
expect(add("zero", "five")).to.equal(5);
expect(add("zero", "six")).to.equal(6);
expect(add("zero", "seven")).to.equal(7);
expect(add("zero", "eight")).to.equal(8);
expect(add("zero", "nine")).to.equal(9);
expect(add("one", "zero")).to.equal(1);
expect(add("one", "one")).to.equal(2);
expect(add("one", "two")).to.equal(3);
expect(add("one", "three")).to.equal(4);
expect(add("one", "four")).to.equal(5);
expect(add("one", "five")).to.equal(6);
expect(add("one", "six")).to.equal(7);
expect(add("one", "seven")).to.equal(8);
expect(add("one", "eight")).to.equal(9);
expect(add("one", "nine")).to.equal(10);
expect(add("two", "zero")).to.equal(2);
expect(add("two", "one")).to.equal(3);
expect(add("two", "two")).to.equal(4);
expect(add("two", "three")).to.equal(5);
expect(add("two", "four")).to.equal(6);
expect(add("two", "five")).to.equal(7);
expect(add("two", "six")).to.equal(8);
expect(add("two", "seven")).to.equal(9);
expect(add("two", "eight")).to.equal(10);
expect(add("two", "nine")).to.equal(11);
expect(add("three", "zero")).to.equal(3);
expect(add("three", "one")).to.equal(4);
expect(add("three", "two")).to.equal(5);
expect(add("three", "three")).to.equal(6);
expect(add("three", "four")).to.equal(7);
expect(add("three", "five")).to.equal(8);
expect(add("three", "six")).to.equal(9);
expect(add("three", "seven")).to.equal(10);
expect(add("three", "eight")).to.equal(11);
expect(add("three", "nine")).to.equal(12);
expect(add("four", "zero")).to.equal(4);
expect(add("four", "one")).to.equal(5);
expect(add("four", "two")).to.equal(6);
expect(add("four", "three")).to.equal(7);
expect(add("four", "four")).to.equal(8);
expect(add("four", "five")).to.equal(9);
expect(add("four", "six")).to.equal(10);
expect(add("four", "seven")).to.equal(11);
expect(add("four", "eight")).to.equal(12);
expect(add("four", "nine")).to.equal(13);
expect(add("five", "zero")).to.equal(5);
expect(add("five", "one")).to.equal(6);
expect(add("five", "two")).to.equal(7);
expect(add("five", "three")).to.equal(8);
expect(add("five", "four")).to.equal(9);
expect(add("five", "five")).to.equal(10);
expect(add("five", "six")).to.equal(11);
expect(add("five", "seven")).to.equal(12);
expect(add("five", "eight")).to.equal(13);
expect(add("five", "nine")).to.equal(14);

console.log(add("five", "seven"))

console.log(1/9)

// NIGHTMARE MODE

/* function plus(A, B){
  return (toNumber(A) + toNumber(B));
}

function minus(A, B){
  return (toNumber(A) - toNumber(B));
}

function multiply(A, B){
  return (toNumber(A) * toNumber(B));
}

function divide(A, B){
  return (toNumber(A) / toNumber(B));
}

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);

expect(minus).to.exist;
expect(minus("four", "two")).to.equal(2);

expect(multiply).to.exist;
expect(multiply("five", "three")).to.equal(15);

console.log(multiply("three", "four"))

expect(divide).to.exist;
expect(divide("five", "one").to.equal(5) */
<|endoftext|>


<commit_before>define(
  [
    'underscore',
    'dispatchers/Dispatcher',
    'stores/Store',
    'rsvp',
    'collections/InstanceCollection',
    'models/Instance',
    'constants/InstanceConstants',
    'controllers/NotificationController',
    'stores/IdentityStore',
    'actions/ProjectActions'
  ],
  function (_, Dispatcher, Store, RSVP, InstanceCollection, Instance, InstanceConstants, NotificationController, IdentityStore, ProjectActions) {

    var _instances = null;
    var _isFetching = false;
    var validStates = ["active", "error", "active - deploy_error", "suspended"];
    var pollingFrequency = 10*1000;

    //
    // CRUD Operations
    //

    var fetchInstancesFor = function (providerId, identityId) {
      var promise = new RSVP.Promise(function (resolve, reject) {
        var instances = new InstanceCollection(null, {
          provider_id: providerId,
          identity_id: identityId
        });
        // make sure promise returns the right instances collection
        // for when this function is called multiple times
        (function(instances, resolve){
          instances.fetch().done(function(){
            resolve(instances);
          });
        })(instances, resolve)
      });
      return promise;
    };

    var fetchInstances = function (identities) {
      if(!_isFetching && identities) {
        _isFetching = true;

        // return an array of promises (one for each volume collection being fetched)
        var promises = identities.map(function (identity) {
          var providerId = identity.get('provider_id');
          var identityId = identity.get('id');
          return fetchInstancesFor(providerId, identityId);
        });

        // When all instance collections are fetched...
        RSVP.all(promises).then(function (instanceCollections) {
          // Combine results into a single volume collection
          var instances = new InstanceCollection();
          for (var i = 0; i < instanceCollections.length; i++) {
            instances.add(instanceCollections[i].toJSON());
          }

          // Start polling for any instances that are in transition states
          instances.forEach(function(instance){
            if(validStates.indexOf(instance.get("status")) < 0){
              pollUntilBuildIsFinished(instance);
            }
          });

          // Save the results to local cache
          _isFetching = false;
          _instances = instances;
          InstanceStore.emitChange();
        });
      }
    };

    function update(instance){
      instance.save({name: instance.get('name')}, {patch: true}).done(function(){
        var successMessage = "Instance " + instance.get('name') + " updated.";
        //NotificationController.success(successMessage);
        InstanceStore.emitChange();
      }).fail(function(){
        var failureMessage = "Error updating Instance " + instance.get('name') + ".";
        NotificationController.error(failureMessage);
        InstanceStore.emitChange();
      });
    }

    var suspend = function(instance){
      instance.suspend({
        success: function (model) {
          //NotificationController.success("Success", "Your instance is now suspended");
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error("Error", "Your instance could not be suspended");
          InstanceStore.emitChange();
        }
      });
    };

    var resume = function(instance){
      instance.resume({
        success: function (model) {
          //NotificationController.success("Success", "Your instance is resuming");
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error("Error", "Your instance could not be resumed");
          InstanceStore.emitChange();
        }
      });
    };

    var stop = function(instance){
      instance.stop({
        success: function (model) {
          //NotificationController.success('Stop Instance', 'Instance successfully stopped');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be stopped');
          InstanceStore.emitChange();
        }
      });
    };

    var start = function(instance){
      instance.start({
        success: function (model) {
          //NotificationController.success('Start Instance', 'Instance successfully started');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be started');
          InstanceStore.emitChange();
        }
      });
    };

    var terminate = function(instance){
      instance.destroy({
        success: function (model) {
          //NotificationController.success('Terminate Instance', 'Instance termination started');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be terminated');
          _instances.add(instance);
          InstanceStore.emitChange();
        }
      });
      _instances.remove(instance);
    };

    var launch = function(identity, machineId, sizeId, instanceName, project){
      var instance = new Instance({
        identity: {
          id: identity.id,
          provider: identity.get('provider_id')
        }
      });

      var params = {
        machine_alias: machineId,
        size_alias: sizeId,
        name: instanceName
      };

      instance.save(params, {
        success: function (model) {
          //NotificationController.success('Launch Instance', 'Instance successfully launched');
          pollUntilBuildIsFinished(instance);
          ProjectActions.addItemToProject(project, instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be launched');
          _instances.remove(instance);
          InstanceStore.emitChange();
        }
      });
      _instances.add(instance);
    };

    var _instancesBuilding = [];
    var pollUntilBuildIsFinished = function(instance){
      _instancesBuilding.push(instance);
      fetchAndRemoveIfFinished(instance);
    };

    var fetchAndRemoveIfFinished = function(instance){
      setTimeout(function(){
        instance.fetch().done(function(){
          var index = _instancesBuilding.indexOf(instance);
          if(validStates.indexOf(instance.get("status")) >= 0){
            _instancesBuilding.slice(index, 1);
          }else{
            fetchAndRemoveIfFinished(instance);
          }
          InstanceStore.emitChange();
        });
      }, pollingFrequency);
    };

    //
    // Instance Store
    //

    var InstanceStore = {

      getAll: function () {
        if(!_instances) {
          var identities = IdentityStore.getAll();
          if(identities) {
            fetchInstances(identities);
          }
        }
        return _instances;
      },

      get: function (instanceId) {
        if(!_instances) {
          var identities = IdentityStore.getAll();
          if(identities) {
            fetchInstances(identities);
          }
        } else {
          return _instances.get(instanceId);
        }
      }

    };

    Dispatcher.register(function (payload) {
      var action = payload.action;

      switch (action.actionType) {
        case InstanceConstants.INSTANCE_UPDATE:
          update(action.instance);
          break;

        case InstanceConstants.INSTANCE_SUSPEND:
          suspend(action.instance);
          break;

        case InstanceConstants.INSTANCE_RESUME:
          resume(action.instance);
          break;

        case InstanceConstants.INSTANCE_STOP:
          stop(action.instance);
          break;

        case InstanceConstants.INSTANCE_START:
          start(action.instance);
          break;

        case InstanceConstants.INSTANCE_TERMINATE:
          terminate(action.instance);
          break;

        case InstanceConstants.INSTANCE_LAUNCH:
          launch(action.identity, action.machineId, action.sizeId, action.instanceName, action.project);
          break;

        default:
          return true;
      }

      InstanceStore.emitChange();

      return true;
    });

    _.extend(InstanceStore, Store);

    return InstanceStore;
  });
<commit_msg>prevent instance store from fetching shutoff instances<commit_after>define(
  [
    'underscore',
    'dispatchers/Dispatcher',
    'stores/Store',
    'rsvp',
    'collections/InstanceCollection',
    'models/Instance',
    'constants/InstanceConstants',
    'controllers/NotificationController',
    'stores/IdentityStore',
    'actions/ProjectActions'
  ],
  function (_, Dispatcher, Store, RSVP, InstanceCollection, Instance, InstanceConstants, NotificationController, IdentityStore, ProjectActions) {

    var _instances = null;
    var _isFetching = false;
    var validStates = ["active", "error", "active - deploy_error", "suspended", "shutoff"];
    var pollingFrequency = 10*1000;

    //
    // CRUD Operations
    //

    var fetchInstancesFor = function (providerId, identityId) {
      var promise = new RSVP.Promise(function (resolve, reject) {
        var instances = new InstanceCollection(null, {
          provider_id: providerId,
          identity_id: identityId
        });
        // make sure promise returns the right instances collection
        // for when this function is called multiple times
        (function(instances, resolve){
          instances.fetch().done(function(){
            resolve(instances);
          });
        })(instances, resolve)
      });
      return promise;
    };

    var fetchInstances = function (identities) {
      if(!_isFetching && identities) {
        _isFetching = true;

        // return an array of promises (one for each volume collection being fetched)
        var promises = identities.map(function (identity) {
          var providerId = identity.get('provider_id');
          var identityId = identity.get('id');
          return fetchInstancesFor(providerId, identityId);
        });

        // When all instance collections are fetched...
        RSVP.all(promises).then(function (instanceCollections) {
          // Combine results into a single volume collection
          var instances = new InstanceCollection();
          for (var i = 0; i < instanceCollections.length; i++) {
            instances.add(instanceCollections[i].toJSON());
          }

          // Start polling for any instances that are in transition states
          instances.forEach(function(instance){
            if(validStates.indexOf(instance.get("status")) < 0){
              pollUntilBuildIsFinished(instance);
            }
          });

          // Save the results to local cache
          _isFetching = false;
          _instances = instances;
          InstanceStore.emitChange();
        });
      }
    };

    function update(instance){
      instance.save({name: instance.get('name')}, {patch: true}).done(function(){
        var successMessage = "Instance " + instance.get('name') + " updated.";
        //NotificationController.success(successMessage);
        InstanceStore.emitChange();
      }).fail(function(){
        var failureMessage = "Error updating Instance " + instance.get('name') + ".";
        NotificationController.error(failureMessage);
        InstanceStore.emitChange();
      });
    }

    var suspend = function(instance){
      instance.suspend({
        success: function (model) {
          //NotificationController.success("Success", "Your instance is now suspended");
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error("Error", "Your instance could not be suspended");
          InstanceStore.emitChange();
        }
      });
    };

    var resume = function(instance){
      instance.resume({
        success: function (model) {
          //NotificationController.success("Success", "Your instance is resuming");
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error("Error", "Your instance could not be resumed");
          InstanceStore.emitChange();
        }
      });
    };

    var stop = function(instance){
      instance.stop({
        success: function (model) {
          //NotificationController.success('Stop Instance', 'Instance successfully stopped');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be stopped');
          InstanceStore.emitChange();
        }
      });
    };

    var start = function(instance){
      instance.start({
        success: function (model) {
          //NotificationController.success('Start Instance', 'Instance successfully started');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be started');
          InstanceStore.emitChange();
        }
      });
    };

    var terminate = function(instance){
      instance.destroy({
        success: function (model) {
          //NotificationController.success('Terminate Instance', 'Instance termination started');
          pollUntilBuildIsFinished(instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be terminated');
          _instances.add(instance);
          InstanceStore.emitChange();
        }
      });
      _instances.remove(instance);
    };

    var launch = function(identity, machineId, sizeId, instanceName, project){
      var instance = new Instance({
        identity: {
          id: identity.id,
          provider: identity.get('provider_id')
        }
      });

      var params = {
        machine_alias: machineId,
        size_alias: sizeId,
        name: instanceName
      };

      instance.save(params, {
        success: function (model) {
          //NotificationController.success('Launch Instance', 'Instance successfully launched');
          pollUntilBuildIsFinished(instance);
          ProjectActions.addItemToProject(project, instance);
          InstanceStore.emitChange();
        },
        error: function (response) {
          NotificationController.error('Error', 'Instance could not be launched');
          _instances.remove(instance);
          InstanceStore.emitChange();
        }
      });
      _instances.add(instance);
    };

    var _instancesBuilding = [];
    var pollUntilBuildIsFinished = function(instance){
      _instancesBuilding.push(instance);
      fetchAndRemoveIfFinished(instance);
    };

    var fetchAndRemoveIfFinished = function(instance){
      setTimeout(function(){
        instance.fetch().done(function(){
          var index = _instancesBuilding.indexOf(instance);
          if(validStates.indexOf(instance.get("status")) >= 0){
            _instancesBuilding.slice(index, 1);
          }else{
            fetchAndRemoveIfFinished(instance);
          }
          InstanceStore.emitChange();
        });
      }, pollingFrequency);
    };

    //
    // Instance Store
    //

    var InstanceStore = {

      getAll: function () {
        if(!_instances) {
          var identities = IdentityStore.getAll();
          if(identities) {
            fetchInstances(identities);
          }
        }
        return _instances;
      },

      get: function (instanceId) {
        if(!_instances) {
          var identities = IdentityStore.getAll();
          if(identities) {
            fetchInstances(identities);
          }
        } else {
          return _instances.get(instanceId);
        }
      }

    };

    Dispatcher.register(function (payload) {
      var action = payload.action;

      switch (action.actionType) {
        case InstanceConstants.INSTANCE_UPDATE:
          update(action.instance);
          break;

        case InstanceConstants.INSTANCE_SUSPEND:
          suspend(action.instance);
          break;

        case InstanceConstants.INSTANCE_RESUME:
          resume(action.instance);
          break;

        case InstanceConstants.INSTANCE_STOP:
          stop(action.instance);
          break;

        case InstanceConstants.INSTANCE_START:
          start(action.instance);
          break;

        case InstanceConstants.INSTANCE_TERMINATE:
          terminate(action.instance);
          break;

        case InstanceConstants.INSTANCE_LAUNCH:
          launch(action.identity, action.machineId, action.sizeId, action.instanceName, action.project);
          break;

        default:
          return true;
      }

      InstanceStore.emitChange();

      return true;
    });

    _.extend(InstanceStore, Store);

    return InstanceStore;
  });
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var newsFeedFilter = ("../engine/newsfeed_filter");
var models = require("../../models");
var auth = require('../authorization');
var log = require('../utils/logger');
var toJson = require('../utils/to_json');
var _ = require('lodash');

var moment = require('moment');

var getRecommendationFor = require('../engine/recommendations/events_manager').getRecommendationFor;
var airbrake = require('airbrake').createClient(process.env.AIRBRAKE_PROJECT_ID, process.env.AIRBRAKE_API_KEY);

var OVERALL_LIMIT=7;

var DATE_OPTIONS = { name:"date", after: moment().add(-1000, 'months').toISOString() };

var setupOptions = function (req) {
  var options = {
    user_id: req.user ? req.user.id : -1
  };

  return options;
};

var processRecommendations = function (levelType, req, res, recommendedItemIds, error) {
  var finalIds;

  if (error) {
    finalIds = [];
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus:  500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
  } else {
    finalIds = _.shuffle(recommendedItemIds);
    if (finalIds.length>OVERALL_LIMIT) {
      finalIds = _.dropRight(finalIds, OVERALL_LIMIT);
    }
  }

  log.info("Recommendations domains status", { recommendedItemIds: recommendedItemIds });

  models.Post.findAll({
    where: {
      id: {
        $in: finalIds
      }
    },
    order: [
      [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ]
    ],
    include: [
      {
        // Category
        model: models.Category,
        required: false,
        include: [
          {
            model: models.Image,
            required: false,
            as: 'CategoryIconImages'
          }
        ]
      },
      // Group
      {
        model: models.Group,
        include: [
          {
            model: models.Category,
            required: false
          },
          {
            model: models.Community,
            attributes: ['id','name','theme_id'],
            required: false
          }
        ]
      },
      // User
      {
        model: models.User,
        required: false,
        attributes: models.User.defaultAttributesWithSocialMediaPublic
      },
      // Image
      {
        model: models.Image,
        required: false,
        as: 'PostHeaderImages'
      },
      // PointRevision
      {
        model: models.PostRevision,
        required: false
      }
    ]
  }).then(function(posts) {
    res.send(posts);
  }).catch(function(error) {
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus: 500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
    res.sendStatus(200);
  });
};

router.get('/domains/:id', auth.can('view domain'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    domain_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("domain", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

router.get('/communities/:id', auth.can('view community'),  function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    community_id: req.params.id,
    limit: OVERALL_LIMIT*2
  }, req.user ? req.user.default_locale : null);

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("community", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

router.get('/groups/:id', auth.can('view group'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    group_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("group", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

module.exports = router;<commit_msg>Filter out hidden<commit_after>var express = require('express');
var router = express.Router();
var newsFeedFilter = ("../engine/newsfeed_filter");
var models = require("../../models");
var auth = require('../authorization');
var log = require('../utils/logger');
var toJson = require('../utils/to_json');
var _ = require('lodash');

var moment = require('moment');

var getRecommendationFor = require('../engine/recommendations/events_manager').getRecommendationFor;
var airbrake = require('airbrake').createClient(process.env.AIRBRAKE_PROJECT_ID, process.env.AIRBRAKE_API_KEY);

var OVERALL_LIMIT=7;

var DATE_OPTIONS = { name:"date", after: moment().add(-1000, 'months').toISOString() };

var setupOptions = function (req) {
  var options = {
    user_id: req.user ? req.user.id : -1
  };

  return options;
};

var processRecommendations = function (levelType, req, res, recommendedItemIds, error) {
  var finalIds;

  if (error) {
    finalIds = [];
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus:  500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
  } else {
    finalIds = _.shuffle(recommendedItemIds);
    if (finalIds.length>OVERALL_LIMIT) {
      finalIds = _.dropRight(finalIds, OVERALL_LIMIT);
    }
  }

  log.info("Recommendations domains status", { recommendedItemIds: recommendedItemIds });

  models.Post.findAll({
    where: {
      id: {
        $in: finalIds
      }
    },
    order: [
      [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ]
    ],
    include: [
      {
        // Category
        model: models.Category,
        required: false,
        include: [
          {
            model: models.Image,
            required: false,
            as: 'CategoryIconImages'
          }
        ]
      },
      // Group
      {
        model: models.Group,
        required: true,
        where: {
          status: {
            $in: ['active','featured']
          }
        },
        include: [
          {
            model: models.Category,
            required: false
          },
          {
            model: models.Community,
            attributes: ['id','name','theme_id'],
            required: false
          }
        ]
      },
      // User
      {
        model: models.User,
        required: false,
        attributes: models.User.defaultAttributesWithSocialMediaPublic
      },
      // Image
      {
        model: models.Image,
        required: false,
        as: 'PostHeaderImages'
      },
      // PointRevision
      {
        model: models.PostRevision,
        required: false
      }
    ]
  }).then(function(posts) {
    res.send(posts);
  }).catch(function(error) {
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus: 500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
    res.sendStatus(200);
  });
};

router.get('/domains/:id', auth.can('view domain'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    domain_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("domain", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

router.get('/communities/:id', auth.can('view community'),  function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    community_id: req.params.id,
    limit: OVERALL_LIMIT*2
  }, req.user ? req.user.default_locale : null);

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("community", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

router.get('/groups/:id', auth.can('view group'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    group_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("group", req, res, recommendedItemIds, error);
  }, req.user ? req.user.default_locale : null);
});

module.exports = router;<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiIdentitySrvc,
        rgiNotifier
    ) {
        var limit = 100,
            currentPage = 0,
            totalPages = 0;

        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.busy = false;

        $scope.assessment_filter_options = [
            {value: 'all', text: 'Show all documents'}
            // {value: 'type', text: 'Sort by document type'},
            // {value: 'assessments', text: 'Sort by attached assessments'}
        ];

        $scope.assessment_filter = $scope.assessment_filter_options[0].value;

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    console.log(assessment);
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
            if(response.reason) {
                rgiNotifier.error('Load document data failure');
            } else {
                $scope.count = response.count;
                $scope.documents = response.data;
                totalPages = Math.ceil(response.count / limit);
                currentPage = currentPage + 1;
            }
        }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };
    });
<commit_msg>fix the 'Document Table' directive controller<commit_after>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiNotifier
    ) {
        var currentPage, totalPages, limit = 100;

        $scope.busy = false;
        $scope.assessment_filter_options = [];
        $scope.assessment_filter = '';

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        $scope.$watch('assessment_filter', function(assessment) {
            currentPage = 0;
            totalPages = 0;
            var searchOptions = {skip: currentPage, limit: limit};

            if(assessment) {
                searchOptions.assessments = assessment;
            }

            rgiDocumentSrvc.queryCached(searchOptions, function (response) {
                if(response.reason) {
                    rgiNotifier.error('Load document data failure');
                } else {
                    $scope.count = response.count;
                    $scope.documents = response.data;

                    if($scope.documents.length === 0) {
                        rgiNotifier.error('No documents uploaded');
                    }

                    totalPages = Math.ceil(response.count / limit);
                    currentPage = 1;
                }
            }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
        });

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                var searchOptions = {skip: currentPage, limit: limit};

                if($scope.assessment_filter) {
                    searchOptions.assessments = $scope.assessment_filter;
                }

                rgiDocumentSrvc.query(searchOptions, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };
    });
<|endoftext|>