<commit_before>define([
    'uijet_dir/uijet',
    'project_widgets/LegendItem',
    'controllers/LegendsList'
], function (uijet) {

    function chartMode () {
        // reset the state of selected legend item
        this.current_index = null;
        this.$element.removeClass('picking');
        this.picking = false;
        this.resource.each(function (model) {
            model.set('disabled', false);
        });
    }

    uijet.Factory('LegendItem', {
        type    : 'LegendItem',
        config  : {
            mixins          : ['Templated', 'Translated'],
            template_name   : 'legend_item',
            dont_fetch      : true,
            data_events     : {
                'change:state'      : function (model, state) {
                    var count = state.selected.length;
                    this.$element.find('.selected_nodes_count').text(count);
                    uijet.publish('selected_nodes_count.updated', count);
                },
                'change:muni'       : function (model, value) {
                    this.$element.find('.entity').text(value.get('name'));
                },
                'change:color'      : function (model, color) {
                    this.setColor(color);
                },
                'change:title'      : function (model, value) {
                    uijet.publish('legend_item_title.updated', {
                        id      : model.id,
                        title   : value
                    });
                },
                'change:disabled'   : function (model, value) {
                    value ? this.disable() : this.enable();
                }
            },
            signals         : {
                post_init   : 'wake'
            },
            app_events      : {
                'add_legend.clicked': function () {
                    this.resource.set('disabled', true);
                }
            }
        }
    })
    .Factory('LegendOverlay', {
        type    : 'Overlay',
        config  : {
            app_events  : {
                'add_legend.clicked'        : 'wake',
                'add_legend_cancel.clicked' : 'sleep',
                'entities_list.selected'    : 'sleep'
            }
        }
    });

    return [{
        type    : 'Button',
        config  : {
            element     : '#add_legend',
            position    : 'top:44px left:277px',
            signals     : {
                pre_click   : 'disable',
                pre_wake    : 'awaking'
            },
            app_events  : {
                'entities_list.selected'    : 'enable',
                'add_legend_cancel.clicked' : 'enable',
                'picker_done.clicked'       : 'wake',
                'nodes_picker.awake'        : 'sleep',
                'welcome'                   : 'wake'
            }
        }
    }, {
        type    : 'Button',
        config  : {
            element     : '#add_legend_cancel',
            dont_wake   : true,
            signals     : {
                pre_click   : 'sleep'
            },
            app_events  : {
                'add_legend.clicked'    : 'wake',
                'entities_list.selected': 'sleep'
            }
        }
    }, {
        type    : 'Pane',
        config  : {
            element     : '#legends_list',
            mixins      : ['Scrolled'],
            adapters    : ['LegendsList', 'jqWheelScroll'],
            resource    : 'LegendItems',
            position    : 'top|45px left:277px bottom',
            style       : {
                height  : 'auto'
            },
            data_events : {
                remove  : function () { this.resource.setColors(); },
                add     : function () { this.resource.setColors(); },
                reset   : 'resetItems'
            },
            signals     : {
                post_init   : 'createOverlay'
            },
            app_events  : {
                chart_colors                : function (colors) {
                    this.resource.colors = colors;
                },
                'legends_list.duplicate'    : 'addItem+',
                'legends_list.selected'     : 'selectItem+',
                'legends_list.delete'       : 'removeItem+',
                'entities_list.selected'    : function (muni_id) {
                    this.addItem()
                        .setEntity(muni_id)
                        .updateState();
                },
                'nodes_list.selection'      : 'updateSelection+',
                'picker_done.clicked'       : chartMode,
                'chart_reset'               : chartMode,
                'add_legend_cancel.clicked' : chartMode,
                'legend_item_added'         : 'scroll',
                'nodes_picker.awake'        : function () {
                    this.position({ top : 0 })
                        .scroll()
                        .$element.addClass('picking');
                    this.picking = true;
                },
                'add_legend.awaking'        : function () {
                    var top = this.processed_position.top;
                    this.position({ top : top.size + (top.unit || 'px') })
                        .scroll()
                        .$element.removeClass('picking');
                    this.picking = false;
                },
                'amount_type.updated'       : function (type) {
                    this.resource.at(this.current_index).set('amount_type', type);
                }
            }
        }
    }];

});
<commit_msg>Fixed error caused by lazy loading of Overlay widget during init<commit_after>define([
    'uijet_dir/uijet',
    'widgets/Overlay',
    'project_widgets/LegendItem',
    'controllers/LegendsList'
], function (uijet) {

    function chartMode () {
        // reset the state of selected legend item
        this.current_index = null;
        this.$element.removeClass('picking');
        this.picking = false;
        this.resource.each(function (model) {
            model.set('disabled', false);
        });
    }

    uijet.Factory('LegendItem', {
        type    : 'LegendItem',
        config  : {
            mixins          : ['Templated', 'Translated'],
            template_name   : 'legend_item',
            dont_fetch      : true,
            data_events     : {
                'change:state'      : function (model, state) {
                    var count = state.selected.length;
                    this.$element.find('.selected_nodes_count').text(count);
                    uijet.publish('selected_nodes_count.updated', count);
                },
                'change:muni'       : function (model, value) {
                    this.$element.find('.entity').text(value.get('name'));
                },
                'change:color'      : function (model, color) {
                    this.setColor(color);
                },
                'change:title'      : function (model, value) {
                    uijet.publish('legend_item_title.updated', {
                        id      : model.id,
                        title   : value
                    });
                },
                'change:disabled'   : function (model, value) {
                    value ? this.disable() : this.enable();
                }
            },
            signals         : {
                post_init   : 'wake'
            },
            app_events      : {
                'add_legend.clicked': function () {
                    this.resource.set('disabled', true);
                }
            }
        }
    })
    .Factory('LegendOverlay', {
        type    : 'Overlay',
        config  : {
            app_events  : {
                'add_legend.clicked'        : 'wake',
                'add_legend_cancel.clicked' : 'sleep',
                'entities_list.selected'    : 'sleep'
            }
        }
    });

    return [{
        type    : 'Button',
        config  : {
            element     : '#add_legend',
            position    : 'top:44px left:277px',
            signals     : {
                pre_click   : 'disable',
                pre_wake    : 'awaking'
            },
            app_events  : {
                'entities_list.selected'    : 'enable',
                'add_legend_cancel.clicked' : 'enable',
                'picker_done.clicked'       : 'wake',
                'nodes_picker.awake'        : 'sleep',
                'welcome'                   : 'wake'
            }
        }
    }, {
        type    : 'Button',
        config  : {
            element     : '#add_legend_cancel',
            dont_wake   : true,
            signals     : {
                pre_click   : 'sleep'
            },
            app_events  : {
                'add_legend.clicked'    : 'wake',
                'entities_list.selected': 'sleep'
            }
        }
    }, {
        type    : 'Pane',
        config  : {
            element     : '#legends_list',
            mixins      : ['Scrolled'],
            adapters    : ['LegendsList', 'jqWheelScroll'],
            resource    : 'LegendItems',
            position    : 'top|45px left:277px bottom',
            style       : {
                height  : 'auto'
            },
            data_events : {
                remove  : function () { this.resource.setColors(); },
                add     : function () { this.resource.setColors(); },
                reset   : 'resetItems'
            },
            signals     : {
                post_init   : 'createOverlay'
            },
            app_events  : {
                chart_colors                : function (colors) {
                    this.resource.colors = colors;
                },
                'legends_list.duplicate'    : 'addItem+',
                'legends_list.selected'     : 'selectItem+',
                'legends_list.delete'       : 'removeItem+',
                'entities_list.selected'    : function (muni_id) {
                    this.addItem()
                        .setEntity(muni_id)
                        .updateState();
                },
                'nodes_list.selection'      : 'updateSelection+',
                'picker_done.clicked'       : chartMode,
                'chart_reset'               : chartMode,
                'add_legend_cancel.clicked' : chartMode,
                'legend_item_added'         : 'scroll',
                'nodes_picker.awake'        : function () {
                    this.position({ top : 0 })
                        .scroll()
                        .$element.addClass('picking');
                    this.picking = true;
                },
                'add_legend.awaking'        : function () {
                    var top = this.processed_position.top;
                    this.position({ top : top.size + (top.unit || 'px') })
                        .scroll()
                        .$element.removeClass('picking');
                    this.picking = false;
                },
                'amount_type.updated'       : function (type) {
                    this.resource.at(this.current_index).set('amount_type', type);
                }
            }
        }
    }];

});
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 * @emails oncall+draft_js
 */

'use strict';

import type {DraftTextAlignment} from 'DraftTextAlignment';
import type EditorState from 'EditorState';

const React = require('React');

const cx = require('cx');
const shallowEqual = require('shallowEqual');

type Props = {
  accessibilityID: string,
  className?: string,
  editorState: EditorState,
  text: string,
  textAlignment: DraftTextAlignment,
  ...
};

/**
 * This component is responsible for rendering placeholder text for the
 * `DraftEditor` component.
 *
 * Override placeholder style via CSS.
 */
class DraftEditorPlaceholder extends React.Component<Props> {
  shouldComponentUpdate(nextProps: Props): boolean {
    const {editorState, ...otherProps} = this.props;
    const {editorState: nextEditorState, ...nextOtherProps} = nextProps;
    return (
      editorState.getSelection().getHasFocus() !==
        nextEditorState.getSelection().getHasFocus() ||
      shallowEqual(otherProps, nextOtherProps)
    );
  }

  render(): React.Node {
    const innerClassName =
      // We can't use joinClasses since the fbjs flow definition is wrong. Using
      // cx to concatenate is rising issues with haste internally.
      // eslint-disable-next-line fb-www/cx-concat
      cx('public/DraftEditorPlaceholder/inner') +
      (this.props.className != null ? ` ${this.props.className}` : '');

    return (
      <div
        className={cx({
          'public/DraftEditorPlaceholder/root': true,
          'public/DraftEditorPlaceholder/hasFocus': this.props.editorState
            .getSelection()
            .getHasFocus(),
        })}>
        <div
          className={innerClassName}
          id={this.props.accessibilityID}
          style={{
            whiteSpace: 'pre-wrap',
          }}>
          {this.props.text}
        </div>
      </div>
    );
  }
}

module.exports = DraftEditorPlaceholder;
<commit_msg>Fix DraftEditorPlaceholder shouldComponetUpdate<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 * @emails oncall+draft_js
 */

'use strict';

import type {DraftTextAlignment} from 'DraftTextAlignment';
import type EditorState from 'EditorState';

const React = require('React');

const cx = require('cx');
const shallowEqual = require('shallowEqual');

type Props = {
  accessibilityID: string,
  className?: string,
  editorState: EditorState,
  text: string,
  textAlignment: DraftTextAlignment,
  ...
};

/**
 * This component is responsible for rendering placeholder text for the
 * `DraftEditor` component.
 *
 * Override placeholder style via CSS.
 */
class DraftEditorPlaceholder extends React.Component<Props> {
  shouldComponentUpdate(nextProps: Props): boolean {
    const {editorState, ...otherProps} = this.props;
    const {editorState: nextEditorState, ...nextOtherProps} = nextProps;
    return (
      editorState.getSelection().getHasFocus() !==
        nextEditorState.getSelection().getHasFocus() ||
      !shallowEqual(otherProps, nextOtherProps)
    );
  }

  render(): React.Node {
    const innerClassName =
      // We can't use joinClasses since the fbjs flow definition is wrong. Using
      // cx to concatenate is rising issues with haste internally.
      // eslint-disable-next-line fb-www/cx-concat
      cx('public/DraftEditorPlaceholder/inner') +
      (this.props.className != null ? ` ${this.props.className}` : '');

    return (
      <div
        className={cx({
          'public/DraftEditorPlaceholder/root': true,
          'public/DraftEditorPlaceholder/hasFocus': this.props.editorState
            .getSelection()
            .getHasFocus(),
        })}>
        <div
          className={innerClassName}
          id={this.props.accessibilityID}
          style={{
            whiteSpace: 'pre-wrap',
          }}>
          {this.props.text}
        </div>
      </div>
    );
  }
}

module.exports = DraftEditorPlaceholder;
<|endoftext|>


<commit_before>function K(){}K.n={},K.r=[],K.d=function(n,e){return{n:n,p:e,c:Array.prototype.slice.call(arguments,2)}},K.redraw=function(n,e,r){K.r=[],K.a(n,e,r);var o=Object.keys(K.n);o.length!==K.r&&o.forEach(function(n){-1===K.r.indexOf(n)&&(K.n[n].remove(),delete K.n[n])})},K.e=function(n,e,r){e instanceof Array&&e.forEach(function(e,o){console.log(e),K.a(n,e,r+(!e.p||e.p.id)+o+".")})},K.a=function(n,e,r){K.e(n,e,r),K.node||(K.node=n,K.root=e),n=n||K.node,e=e||K.root,r=r||"0.";var o=e.n,t=e.p,c=e.c;if("boolean"!=typeof e){if(K.r.push(r),"function"==typeof o)return K.a(n,new o(t,c).render(),r);if("string"==typeof e)return n.innerText=e;var a=K.n[r]||document.createElement(o);t&&Object.keys(t).forEach(function(n){a[n]!==t[n]&&(a[n]=t[n])}),n.appendChild(K.n[r]=a),K.e(a,c,r)}},K.append=K.a;var Kek=K;<commit_msg>rm console.log<commit_after>function K(){}K.n={},K.r=[],K.d=function(n,e){return{n:n,p:e,c:Array.prototype.slice.call(arguments,2)}},K.redraw=function(n,e,r){K.r=[],K.a(n,e,r);var o=Object.keys(K.n);o.length!==K.r&&o.forEach(function(n){-1===K.r.indexOf(n)&&(K.n[n].remove(),delete K.n[n])})},K.e=function(n,e,r){e instanceof Array&&e.forEach(function(e,o){K.a(n,e,r+(!e.p||e.p.id)+o+".")})},K.a=function(n,e,r){K.e(n,e,r),K.node||(K.node=n,K.root=e),n=n||K.node,e=e||K.root,r=r||"0.";var o=e.n,t=e.p,a=e.c;if("boolean"!=typeof e){if(K.r.push(r),"function"==typeof o)return K.a(n,new o(t,a).render(),r);if("string"==typeof e)return n.innerText=e;var c=K.n[r]||document.createElement(o);t&&Object.keys(t).forEach(function(n){c[n]!==t[n]&&(c[n]=t[n])}),n.appendChild(K.n[r]=c),K.e(c,a,r)}},K.append=K.a;var Kek=K;<|endoftext|>


<commit_before>import * as mats from './matrices';
import { intMatrices, matrices, residueClassRing } from './types';

const iops = intMatrices;
const fops = matrices;

const p = 9999991;
const pops = mats.extend(residueClassRing(p), ['Integer'], true);

const invModP = M => {
  const ops = pops;
  const n = M.length;
  const A = M.map((row, i) => row.concat(ops.unitVector(n, i)));
  const E = ops.rowEchelonForm(A);

  return E.map(row => row.slice(n));
};

const numberOfPAdicStepsNeeded = (A, b) => {
  const lengths = M => fops.transposed(M).map(r => fops.norm(r));
  const max = v => v.reduce((x, y) => x > y ? x : y);
  const product = v => v.reduce((x, y) => x * y);

  const ls = lengths(A).concat(max(lengths(b)));
  const delta = product(ls.sort().slice(A[0].length));
  const golden = (1 + Math.sqrt(5)) / 2;

  return Math.ceil(2 * Math.log(delta * golden) / Math.log(p));
};

const rationalReconstruction = (s, h) => {
  const ops = iops;
  let u = [h, s];
  let v = [0, 1];
  let sign = 1;

  while (ops.gt(ops.times(u[1], u[1]), h)) {
    const q = ops.idiv(u[0], u[1]);

    u = [u[1], ops.minus(u[0], ops.times(q, u[1]))];
    v = [v[1], ops.plus(v[0], ops.times(q, v[1]))];
    sign *= -1;
  }

  return fops.div(ops.times(sign, u[1]), v[1]);
};

export default function solve(A, b) {
  console.log(`solve(${A}, ${b})`);
  const C = invModP(A);
  console.log(`  C = ${C}`);
  console.log(`  A * C = ${pops.times(A, C)}`);

  const nrSteps = numberOfPAdicStepsNeeded(A, b);
  console.log(`  nrSteps = ${nrSteps}`);

  let bi = b;
  let pi = 1;
  let si = 0;

  for (let i = 0; i < nrSteps; ++i) {
    const xi = pops.times(C, bi);
    bi = iops.idiv(iops.minus(bi, iops.times(A, xi)), p);
    si = iops.plus(si, iops.times(pi, xi));
    pi = iops.times(pi, p);
  }
  const s = si;
  console.log(`  s = ${s}`);

  const r = s.map(row => row.map(x => rationalReconstruction(x, pi)));
  console.log(`  r = ${r}`);

  return r;
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  solve(
    [ [  4, -4 ],
      [  1,  0 ] ],
    [ [  1,  1,  1 ],
      [  0,  0,  0 ] ]
  );
}
<commit_msg>remove logging from solver function<commit_after>import * as mats from './matrices';
import { intMatrices, matrices, residueClassRing } from './types';

const iops = intMatrices;
const fops = matrices;

const p = 9999991;
const pops = mats.extend(residueClassRing(p), ['Integer'], true);

const invModP = M => {
  const ops = pops;
  const n = M.length;
  const A = M.map((row, i) => row.concat(ops.unitVector(n, i)));
  const E = ops.rowEchelonForm(A);

  return E.map(row => row.slice(n));
};

const numberOfPAdicStepsNeeded = (A, b) => {
  const lengths = M => fops.transposed(M).map(r => fops.norm(r));
  const max = v => v.reduce((x, y) => x > y ? x : y);
  const product = v => v.reduce((x, y) => x * y);

  const ls = lengths(A).concat(max(lengths(b)));
  const delta = product(ls.sort().slice(A[0].length));
  const golden = (1 + Math.sqrt(5)) / 2;

  return Math.ceil(2 * Math.log(delta * golden) / Math.log(p));
};

const rationalReconstruction = (s, h) => {
  const ops = iops;
  let u = [h, s];
  let v = [0, 1];
  let sign = 1;

  while (ops.gt(ops.times(u[1], u[1]), h)) {
    const q = ops.idiv(u[0], u[1]);

    u = [u[1], ops.minus(u[0], ops.times(q, u[1]))];
    v = [v[1], ops.plus(v[0], ops.times(q, v[1]))];
    sign *= -1;
  }

  return fops.div(ops.times(sign, u[1]), v[1]);
};

export default function solve(A, b) {
  const C = invModP(A);
  const nrSteps = numberOfPAdicStepsNeeded(A, b);

  let bi = b;
  let pi = 1;
  let si = 0;

  for (let i = 0; i < nrSteps; ++i) {
    const xi = pops.times(C, bi);
    bi = iops.idiv(iops.minus(bi, iops.times(A, xi)), p);
    si = iops.plus(si, iops.times(pi, xi));
    pi = iops.times(pi, p);
  }

  return si.map(row => row.map(x => rationalReconstruction(x, pi)));
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  const testSolver = (A, b) => {
    console.log();
    console.log(`solving ${A} * x = ${b}`);
    const x = solve(A, b);
    console.log(`  x = ${x}`);
    console.log(`  A * x = ${fops.times(A, x)}`);
  };

  testSolver(
    [ [  4, -4 ],
      [  1,  0 ] ],
    [ [  1,  1,  1 ],
      [  0,  0,  0 ] ]
  );
}
<|endoftext|>


<commit_before>"use strict";

var AbstractTransport = require("./abstract-transport.js");
var WebSocketClient = require("../platform/web-socket-client.js");

function WsTransport(address, timeout, messageHandler, initialConnectCallback) {
  AbstractTransport.call(this, address, timeout, messageHandler);

  this.initialConnect(initialConnectCallback);
}

WsTransport.prototype = Object.create(AbstractTransport.prototype);

WsTransport.prototype.constructor = WsTransport;

WsTransport.prototype.connect = function (callback) {
  this.webSocketClient = new WebSocketClient(this.address, undefined, undefined, undefined, { timeout: this.timeout });
  var messageHandler = function () { };
  this.webSocketClient.onopen = function () {
    callback(null);
    callback = function () { };
    messageHandler = this.messageHandler;
  }.bind(this);
  this.webSocketClient.onmessage = function (message) {
    messageHandler(null, JSON.parse(message.data));
  }.bind(this);
  this.webSocketClient.onerror = function () {
    // unfortunately, we get no error details: https://www.w3.org/TR/websockets/#concept-websocket-close-fail
    messageHandler(new Error("Web socket error."), null);
  }.bind(this);
  this.webSocketClient.onclose = function () {
    callback(new Error("Web socket closed without opening, usually means failed connection."));
    callback = function () { };
  }.bind(this);
};

WsTransport.prototype.submitRpcRequest = function (rpcJso, errorCallback) {
  try {
    this.webSocketClient.send(JSON.stringify(rpcJso));
  } catch (error) {
    if (error.code === "INVALID_STATE_ERR") error.retryable = true;
    if (error.message === "cannot call send() while not connected") error.retryable = true;
    errorCallback(error);
  }
};

module.exports = WsTransport;
<commit_msg>Removed unnecessary binds<commit_after>"use strict";

var AbstractTransport = require("./abstract-transport.js");
var WebSocketClient = require("../platform/web-socket-client.js");

function WsTransport(address, timeout, messageHandler, initialConnectCallback) {
  AbstractTransport.call(this, address, timeout, messageHandler);

  this.initialConnect(initialConnectCallback);
}

WsTransport.prototype = Object.create(AbstractTransport.prototype);

WsTransport.prototype.constructor = WsTransport;

WsTransport.prototype.connect = function (callback) {
  var messageHandler = function () { };
  this.webSocketClient = new WebSocketClient(this.address, undefined, undefined, undefined, { timeout: this.timeout });
  this.webSocketClient.onopen = function () {
    callback(null);
    callback = function () { };
    messageHandler = this.messageHandler;
  };
  this.webSocketClient.onmessage = function (message) {
    messageHandler(null, JSON.parse(message.data));
  };
  this.webSocketClient.onerror = function () {
    // unfortunately, we get no error details: https://www.w3.org/TR/websockets/#concept-websocket-close-fail
    messageHandler(new Error("Web socket error."), null);
  };
  this.webSocketClient.onclose = function () {
    callback(new Error("Web socket closed without opening, usually means failed connection."));
    callback = function () { };
  };
};

WsTransport.prototype.submitRpcRequest = function (rpcJso, errorCallback) {
  try {
    this.webSocketClient.send(JSON.stringify(rpcJso));
  } catch (error) {
    if (error.code === "INVALID_STATE_ERR") error.retryable = true;
    if (error.message === "cannot call send() while not connected") error.retryable = true;
    errorCallback(error);
  }
};

module.exports = WsTransport;
<|endoftext|>


<commit_before>#!/usr/bin/env node
var os = require('os')
  , path = require('path')
  , fs = require('vigour-fs-promised')
  , homedir = process.env.USERPROFILE || process.env.HOME
  , configPath = path.join(homedir, '.gaston', 'config.json')
  , initialConfig = {
      "http-port": 8080,
      "api-port": 64571,
      "base-path": process.env.HOME || process.env.USERPROFILE,
      "source-maps": false,
      "smaps": true,

      "push-state": false,
      "index-path": false,
      "css-compiler": "less",
      "aliases": {}
    };

fs.existsAsync( configPath )
  .then(function(exists){
    if(!exists){
      fs.writeJSONAsync( configPath, initialConfig, { space: 2, mkdirp: true } );
    }
  });<commit_msg>changed default global config<commit_after>#!/usr/bin/env node
var os = require('os')
  , path = require('path')
  , fs = require('vigour-fs-promised')
  , homedir = process.env.USERPROFILE || process.env.HOME
  , configPath = path.join(homedir, '.gaston', 'config.json')
  , initialConfig = {
      "http-port": 8080,
      "api-port": 64571,
      "base-path": process.env.HOME || process.env.USERPROFILE,
      "source-maps": false,
      "smaps": true,

      "push-state": false,
      "index-path": false,
      "css-compiler": "less"
    };

fs.existsAsync( configPath )
  .then(function(exists){
    if(!exists){
      fs.writeJSONAsync( configPath, initialConfig, { space: 2, mkdirp: true } );
    }
  });<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import { play, pause } from '../modules/player'

/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the counter:   */

import PlayerView from '../components/PlayerView'

/*  Object of action creators (can also be function that returns object).
    Keys will be passed as props to presentational components. Here we are
    implementing our wrapper around increment; the component doesn't care   */

const mapActionCreators = {
  play,
  pause
}

const mapStateToProps = (state) => ({
  player: state.player
})

/*  Note: mapStateToProps is where you should use `reselect` to create selectors, ie:

    import { createSelector } from 'reselect'
    const counter = (state) => state.counter
    const tripleCount = createSelector(counter, (count) => count * 3)
    const mapStateToProps = (state) => ({
      counter: tripleCount(state)
    })

    Selectors can compute derived data, allowing Redux to store the minimal possible state.
    Selectors are efficient. A selector is not recomputed unless one of its arguments change.
    Selectors are composable. They can be used as input to other selectors.
    https://github.com/reactjs/reselect    */

export default connect(mapStateToProps, mapActionCreators)(PlayerView)
<commit_msg>Pass fetchQueue action to Player component<commit_after>import { connect } from 'react-redux'
import { play, pause } from '../modules/player'
import { fetchQueue } from '../Queue/modules/queue'
import PlayerView from '../components/PlayerView'

const mapActionCreators = {
  play,
  pause,
  fetchQueue
}

const mapStateToProps = (state) => ({
  queue: state.queue,
  isPlaying: state.player.isPlaying,
  isFetching: state.player.isFetching,
})

export default connect(mapStateToProps, mapActionCreators)(PlayerView)
<|endoftext|>


<commit_before>/*!
* PopConfirm 0.1
* http://ifnot.github.io/PopConfirm/
*
* Use jQuery & Bootstrap
* http://jquery.com/
* http://getbootstrap.com/
*
* Copyright 2014 Anael Favre and other contributors
* Released under the MIT license
* https://raw.github.com/AnaelFavre/PopConfirm/master/LICENCE
*/

(function($){
  $.fn.extend({
    popConfirm: function(options) {
      var defaults = {
        title: 'Confirmation',
        content: 'Are you really sure ?',
        placement: 'right',
        container: 'body',
        yesBtn:   'Yes',
        noBtn:    'No'
      };
      var options =  $.extend(defaults, options);
      var last = null;

      return this.each(function() {
        var self = $(this);
        var arrayActions = [];
        var arrayDelegatedActions = [];
        var eventToConfirm;

        // If there are jquery click events
        if (typeof(jQuery._data(this, "events")) != "undefined" && typeof(jQuery._data(this, "events")['click']) != "undefined") {

          // Save all click handlers
          for (var i = 0; i < jQuery._data(this, "events")['click'].length; i++) {
            arrayActions.push(jQuery._data(this, "events")['click'][i].handler);
          }

          // unbind it to prevent it firing
          $(self).unbind("click");
        }

        // If there are jquery delegated click events
        if (self.data('remote') && typeof(jQuery._data(document, "events")) != "undefined" && typeof(jQuery._data(document, "events")['click']) != "undefined") {

          // Save all delegated click handlers that apply
          for (var i = 0; i < jQuery._data(document, "events")['click'].length; i++) {
            var elmType = self[0].tagName.toLowerCase();
            if(typeof jQuery._data(document, "events")['click'][i].selector != "undefined" && jQuery._data(document, "events")['click'][i].selector.indexOf(elmType + "[data-remote]") > -1)
              arrayDelegatedActions.push(jQuery._data(document, "events")['click'][i].handler);
          }
        }

        // If there are hard onclick attribute
        if(typeof self.attr('onclick') != 'undefined') {
          // Extracting the onclick code to evaluate and bring it into a closure
          var code = self.attr('onclick');
          arrayActions.push(function() {
            eval(code);
          });
          $(self).removeAttr('onclick');
        }

        // If there are href link defined
        if(!self.data('remote') && typeof self.attr('href') != 'undefined') {
          // Assume there is a href attribute to redirect to
          arrayActions.push(function() {
            window.location.href = self.attr('href');
          });
        }

        // If the button is a submit one
        if(typeof self.attr('type') != 'undefined' && self.attr('type') == 'submit') {
          // Get the form related to this button then store submiting in closure
          var form = $(this).parents('form:first');
          arrayActions.push(function() {
            form.submit();
          });
        }

        self.popover({
          trigger: 'manual',
          title: options.title,
          html: true,
          placement: options.placement,
          container: options.container,
          content: options.content + '\

\
          <button type="button" class="btn btn-small btn-danger confirm-dialog-btn-confirm">' + options.yesBtn + '</button>\
          <button type="button" class="btn btn-small confirm-dialog-btn-abord">' + options.noBtn + '</button>\

'
        }).click(function(e) {
          if(last && last !== self) last.popover('hide');
          last = self;
        });

        $(document).on('click', function(){
          if (last) last.popover('hide');
        });

        self.bind('click', function(e) {
          eventToConfirm = e;

          e.preventDefault();
          e.stopPropagation();

          self.popover('show');

          $(document).find('.popover .confirm-dialog-btn-confirm').bind('click', function(e) {
            for(var i = 0; i < arrayActions.length; i++) {
              arrayActions[i].apply(self);
            }

            for(var i = 0; i < arrayDelegatedActions.length; i++) {
              arrayDelegatedActions[i].apply(self, [eventToConfirm.originalEvent]);
            }

            self.popover('hide');
          });
          $(document).find('.popover .confirm-dialog-btn-abord').bind('click', function(e) {
            self.popover('hide');
          });
        });
      });
    }
  });
})(jQuery);
<commit_msg>prevent multiple on screen at a time<commit_after>/*!
* PopConfirm 0.1
* http://ifnot.github.io/PopConfirm/
*
* Use jQuery & Bootstrap
* http://jquery.com/
* http://getbootstrap.com/
*
* Copyright 2014 Anael Favre and other contributors
* Released under the MIT license
* https://raw.github.com/AnaelFavre/PopConfirm/master/LICENCE
*/

(function($){
  $.fn.extend({
    popConfirm: function(options) {
      var defaults = {
        title: 'Confirmation',
        content: 'Are you really sure ?',
        placement: 'right',
        container: 'body',
        yesBtn:   'Yes',
        noBtn:    'No'
      };
      var options =  $.extend(defaults, options);
      var last = null;

      return this.each(function() {
        var self = $(this);
        var arrayActions = [];
        var arrayDelegatedActions = [];
        var eventToConfirm;

        // If there are jquery click events
        if (typeof(jQuery._data(this, "events")) != "undefined" && typeof(jQuery._data(this, "events")['click']) != "undefined") {

          // Save all click handlers
          for (var i = 0; i < jQuery._data(this, "events")['click'].length; i++) {
            arrayActions.push(jQuery._data(this, "events")['click'][i].handler);
          }

          // unbind it to prevent it firing
          $(self).unbind("click");
        }

        // If there are jquery delegated click events
        if (self.data('remote') && typeof(jQuery._data(document, "events")) != "undefined" && typeof(jQuery._data(document, "events")['click']) != "undefined") {

          // Save all delegated click handlers that apply
          for (var i = 0; i < jQuery._data(document, "events")['click'].length; i++) {
            var elmType = self[0].tagName.toLowerCase();
            if(typeof jQuery._data(document, "events")['click'][i].selector != "undefined" && jQuery._data(document, "events")['click'][i].selector.indexOf(elmType + "[data-remote]") > -1)
              arrayDelegatedActions.push(jQuery._data(document, "events")['click'][i].handler);
          }
        }

        // If there are hard onclick attribute
        if(typeof self.attr('onclick') != 'undefined') {
          // Extracting the onclick code to evaluate and bring it into a closure
          var code = self.attr('onclick');
          arrayActions.push(function() {
            eval(code);
          });
          $(self).removeAttr('onclick');
        }

        // If there are href link defined
        if(!self.data('remote') && typeof self.attr('href') != 'undefined') {
          // Assume there is a href attribute to redirect to
          arrayActions.push(function() {
            window.location.href = self.attr('href');
          });
        }

        // If the button is a submit one
        if(typeof self.attr('type') != 'undefined' && self.attr('type') == 'submit') {
          // Get the form related to this button then store submiting in closure
          var form = $(this).parents('form:first');
          arrayActions.push(function() {
            form.submit();
          });
        }

        self.popover({
          trigger: 'manual',
          title: options.title,
          html: true,
          placement: options.placement,
          container: options.container,
          content: options.content + '\

\
          <button type="button" class="btn btn-small btn-danger confirm-dialog-btn-confirm">' + options.yesBtn + '</button>\
          <button type="button" class="btn btn-small confirm-dialog-btn-abord">' + options.noBtn + '</button>\

'
        }).click(function(e) {
          if(last && last !== self) last.popover('hide').removeClass('popconfirm-active');
          last = self;
        });

        $(document).on('click', function(){
          if (last) last.popover('hide').removeClass('popconfirm-active');
        });

        self.bind('click', function(e) {
          eventToConfirm = e;

          e.preventDefault();
          e.stopPropagation();

          $('.popconfirm-active').popover('hide').removeClass('popconfirm-active');
          self.popover('show').addClass('popconfirm-active');

          $(document).find('.popover .confirm-dialog-btn-confirm').bind('click', function(e) {
            for(var i = 0; i < arrayActions.length; i++) {
              arrayActions[i].apply(self);
            }

            for(var i = 0; i < arrayDelegatedActions.length; i++) {
              arrayDelegatedActions[i].apply(self, [eventToConfirm.originalEvent]);
            }

            self.popover('hide').removeClass('popover-active');
          });
          $(document).find('.popover .confirm-dialog-btn-abord').bind('click', function(e) {
            self.popover('hide').removeClass('popover-active');
          });
        });
      });
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>import RethinkObject from '../reTHINKObject/RethinkObject';

import CatalogueDataObject from './CatalogueDataObject';
import {CatalogueObjectType} from './CatalogueDataObject';
import {DataObjectSourceLanguage} from './CatalogueDataObject';

import SourcePackage from './SourcePackage';

import HypertyDescriptor from './HypertyDescriptor';
import {HypertyType} from './HypertyDescriptor';

import ProtocolStubDescriptor from './ProtocolStubDescriptor';

import HypertyRuntimeDescriptor from './HypertyRuntimeDescriptor';
import {RuntimeType} from './HypertyRuntimeDescriptor';
import {RuntimeProtocolCapabilityType} from './HypertyRuntimeDescriptor';
import {RuntimeHypertyCapabilityType} from './HypertyRuntimeDescriptor';

import PolicyEnforcerDescriptor from './PolicyEnforcerDescriptor';
import DataObjectSchema from './DataObjectSchema';

class CatalogueDataObjectFactory extends RethinkObject {

    /**
     * Constructor
     * @param {boolean} validation
     * @param {URL.URL } schema - link to the schema
     */
    constructor(validation, schema) {
        super(validation, schema);
    }

    createCatalogueDataObject(guid, type, objectName, description, language, sourcePackageURL) {
        if (
            typeof guid === "undefined"
            || typeof type === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new CatalogueDataObject(guid, type, objectName, description, language, sourcePackageURL);
    }

    createHypertyDescriptorObject(guid, objectName, description, language, sourcePackageURL, hypertyType,
                                  dataObjects) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof hypertyType === "undefined"
            || typeof dataObjects === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new HypertyDescriptor(guid, CatalogueObjectType.HYPERTY, objectName, description,
            language, sourcePackageURL, hypertyType, dataObjects);
    }

    createProtoStubDescriptorObject(guid, objectName, description, language, sourcePackageURL, messageSchemas,
                                    configuration, constraints) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof messageSchemas === "undefined"
            || typeof configuration === "undefined"
            || typeof constraints === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new ProtocolStubDescriptor(guid, CatalogueObjectType.PROTOSTUB, objectName, description,
            language, sourcePackageURL, messageSchemas, configuration, constraints);
    }

    createHypertyRuntimeDescriptorObject(guid, objectName, description, language, sourcePackageURL,
                                         runtimeType, hypertyCapabilities, protocolCapabilities) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof runtimeType === "undefined"
            || typeof hypertyCapabilities === "undefined"
            || typeof protocolCapabilities === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new HypertyRuntimeDescriptor(guid, CatalogueObjectType.HYPERTY_RUNTIME, objectName,
            description, language, sourcePackageURL, runtimeType, hypertyCapabilities, protocolCapabilities);
    }

    createPolicyEnforcerDescriptorObject(guid, objectName, description, language, sourcePackageURL, configuration,
                                         policies) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof configuration === "undefined"
            || typeof policies === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new PolicyEnforcerDescriptor(guid, CatalogueObjectType.POLICY_ENFORCER, objectName,
            description, language, sourcePackageURL, configuration, policies);
    }

    createDataObjectSchema(guid, type, objectName, description, language, sourcePackageURL) {
        if (
            typeof guid === "undefined"
            || typeof type === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new DataObjectSchema(guid, type, objectName, description, language, sourcePackageURL);
    }

    createSourcePackage(sourceCode, sourceCodeClassname) {
        if (
            typeof sourceCode === "undefined"
            || typeof sourceCodeClassname === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new SourcePackage(sourceCode, sourceCodeClassname);

    }
}

export default CatalogueDataObjectFactory;<commit_msg>catalogue-factory: minor fix<commit_after>import RethinkObject from '../reTHINKObject/RethinkObject';

import CatalogueDataObject from './CatalogueDataObject';
import {CatalogueObjectType} from './CatalogueDataObject';
import {DataObjectSourceLanguage} from './CatalogueDataObject';

import SourcePackage from './SourcePackage';

import HypertyDescriptor from './HypertyDescriptor';
import {HypertyType} from './HypertyDescriptor';

import ProtocolStubDescriptor from './ProtocolStubDescriptor';

import HypertyRuntimeDescriptor from './HypertyRuntimeDescriptor';
import {RuntimeType} from './HypertyRuntimeDescriptor';
import {RuntimeProtocolCapabilityType} from './HypertyRuntimeDescriptor';
import {RuntimeHypertyCapabilityType} from './HypertyRuntimeDescriptor';

import PolicyEnforcerDescriptor from './PolicyEnforcerDescriptor';
import DataObjectSchema from './DataObjectSchema';

class CatalogueDataObjectFactory extends RethinkObject {

    /**
     * Constructor
     * @param {boolean} validation
     * @param {URL.URL } schema - link to the schema
     */
    constructor(validation, schema) {
        super(validation, schema);
    }

    createCatalogueDataObject(guid, type, objectName, description, language, sourcePackageURL) {
        if (
            typeof guid === "undefined"
            || typeof type === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new CatalogueDataObject(guid, type, objectName, description, language, sourcePackageURL);
    }

    createHypertyDescriptorObject(guid, objectName, description, language, sourcePackageURL, hypertyType,
                                  dataObjects) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof hypertyType === "undefined"
            || typeof dataObjects === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new HypertyDescriptor(guid, CatalogueObjectType.HYPERTY, objectName, description,
            language, sourcePackageURL, hypertyType, dataObjects);
    }

    createProtoStubDescriptorObject(guid, objectName, description, language, sourcePackageURL, messageSchemas,
                                    configuration, constraints) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof messageSchemas === "undefined"
            || typeof configuration === "undefined"
            || typeof constraints === "undefined"
        )
            throw new Error("Invalid parameters!");
        return new ProtocolStubDescriptor(guid, CatalogueObjectType.PROTOSTUB, objectName, description,
            language, sourcePackageURL, messageSchemas, configuration, constraints);
    }

    createHypertyRuntimeDescriptorObject(guid, objectName, description, language, sourcePackageURL,
                                         runtimeType, hypertyCapabilities, protocolCapabilities) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof runtimeType === "undefined"
            || typeof hypertyCapabilities === "undefined"
            || typeof protocolCapabilities === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new HypertyRuntimeDescriptor(guid, CatalogueObjectType.HYPERTY_RUNTIME, objectName,
            description, language, sourcePackageURL, runtimeType, hypertyCapabilities, protocolCapabilities);
    }

    createPolicyEnforcerDescriptorObject(guid, objectName, description, language, sourcePackageURL, configuration,
                                         policies) {
        if (
            typeof guid === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
            || typeof configuration === "undefined"
            || typeof policies === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new PolicyEnforcerDescriptor(guid, CatalogueObjectType.POLICY_ENFORCER, objectName,
            description, language, sourcePackageURL, configuration, policies);
    }

    createDataObjectSchema(guid, type, objectName, description, language, sourcePackageURL) {
        if (
            typeof guid === "undefined"
            || typeof type === "undefined"
            || typeof objectName === "undefined"
            || typeof description === "undefined"
            || typeof language === "undefined"
            || typeof sourcePackageURL === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new DataObjectSchema(guid, type, objectName, description, language, sourcePackageURL);
    }

    createSourcePackage(sourceCodeClassname, sourceCode) {
        if (
            typeof sourceCode === "undefined"
            || typeof sourceCodeClassname === "undefined"
        )
            throw new Error("Invalid parameters!");

        return new SourcePackage(sourceCodeClassname, sourceCode);

    }
}

export default CatalogueDataObjectFactory;<|endoftext|>


<commit_before>/*jshint browser: true, jasmine: true */
/*global angular, inject, module, $ */

describe('Grid toolbars', function () {
    'use strict';

    var basicGridHtml,
        bbViewKeeperBuilder,
        $compile,
        $document,
        el,
        dataSet1,
        fxOff,
        locals,
        $scope,
        options;

    function setUpGrid(gridHtml, setLocals) {
        var el = angular.element(gridHtml);

        $document.find('body').eq(0).append(el);

        if (angular.isDefined(setLocals)) {
            $scope.locals = setLocals;
        } else {
            $scope.locals = locals;
        }

        $compile(el)($scope);

        $scope.$digest();

        return el;
    }

    function getAddButton(el) {
        return el.find('.bb-grid-container .bb-grid-toolbar-container .bb-grid-toolbar-btn.btn-success');
    }

    function setGridData(data) {
        $scope.locals.gridOptions.data = data;
        $scope.$digest();
    }

    function setOptions(options) {
        locals.gridOptions = options;
        $scope.$digest();
    }

    beforeEach(module('ngMock'));
    beforeEach(module(
        'sky.grids',
        'sky.templates'
    ));

    beforeEach(inject(function (_$rootScope_, _$compile_, _$document_, _bbViewKeeperBuilder_) {
        $scope = _$rootScope_;
        $compile = _$compile_;

        $document = _$document_;

        bbViewKeeperBuilder = _bbViewKeeperBuilder_;

        locals = {
        };

        options =  {
            columns: [
                {
                    caption: 'Name',
                    jsonmap: 'name',
                    id: 1,
                    name: 'name'
                },
                {
                    caption: 'Instrument',
                    jsonmap: 'instrument',
                    id: 2,
                    name: 'instrument'
                },
                {
                    caption: 'Biography',
                    jsonmap: 'bio',
                    id: 3,
                    name: 'bio'
                }
            ],
            data: [],
            selectedColumnIds: [1, 2, 3]
        };

        basicGridHtml = '
<bb-grid bb-grid-options="locals.gridOptions"></bb-grid>
';

        dataSet1 = [
            {
                id: 'blarrrg',
                name: 'John',
                instrument: 'Rhythm guitar'
            },
            {
                name: 'Paul',
                instrument: 'Bass',
                bio: 'Lorem'
            },
            {
                name: 'George',
                instrument: 'Lead guitar'
            },
            {
                name: 'Ringo',
                instrument: 'Drums'
            }
        ];

        el = {};
        fxOff =  $.fx.off;
        //turn off jquery animate.
        $.fx.off = true;

    }));

    afterEach(function () {
        if (angular.isDefined(el)) {
            if (angular.isFunction(el.remove)) {
                el.remove();
            }
        }
        $.fx.off = fxOff;
    });

    describe('inline filters', function () {
        it('will toggle the visibility of the filters if the hasInlineFilters option is specified and it will react to options.filtersAreActive change', function () {

            var inlineHtml = '
<bb-grid bb-grid-options="locals.gridOptions">
<input class="hehe" type="checkbox" ng-model="locals.gridOptions.filters.check"/>
</bb-grid>
',
                filterButtonEl,
                filterInputEl;
            setOptions(options);
            locals.gridOptions.hasInlineFilters = true;
            locals.gridOptions.filters = {
                check: false
            };

            el = setUpGrid(inlineHtml, locals);

            filterInputEl = el.find('.hehe');

            expect(filterInputEl).not.toBeVisible();

            filterButtonEl = el.find('.bb-filter-btn');

            filterButtonEl.click();

            $scope.$digest();

            expect(filterInputEl).toBeVisible();

            $scope.locals.gridOptions.filters.check = true;
            $scope.locals.gridOptions.filtersAreActive = true;
            $scope.$digest();

            expect(filterButtonEl).toHaveClass('bb-filters-inline-active');

            expect($scope.locals.gridOptions.filters.check).toBe(true);

            $scope.locals.gridOptions.filters.check = false;
            $scope.locals.gridOptions.filtersAreActive = false;
            $scope.$digest();

            expect(filterButtonEl).not.toHaveClass('bb-filters-inline-active');

            expect($scope.locals.gridOptions.filters.check).toBe(false);

            filterButtonEl.click();

            $scope.$digest();

            expect(filterInputEl).not.toBeVisible();

        });

        it('will set the visibility of the filters if options.filtersOpen is defined', function () {
            var inlineHtml = '
<bb-grid bb-grid-options="locals.gridOptions">
<input class="hehe" type="checkbox" ng-model="locals.gridOptions.filters.check"/>
</bb-grid>
',
                filterInputEl;
            setOptions(options);
            locals.gridOptions.hasInlineFilters = true;
            locals.gridOptions.filtersOpen = true;

            el = setUpGrid(inlineHtml, locals);

            filterInputEl = el.find('.hehe');

            expect(filterInputEl).toBeVisible();

            locals.gridOptions.filtersOpen = false;
            $scope.$digest();

            expect(filterInputEl).not.toBeVisible();

            $scope.$destroy();

        });
    });

    describe('top scrollbar scrolling', function () {
        it('will have a top horizontal scroll bar that will sync with the bottom scroll bar', function () {
            var topScrollbarEl,
                tableWrapperEl,
                headerViewKeeperEl,
                gridWrapperHtml = '
<bb-grid bb-grid-options="locals.gridOptions"></bb-grid>
';

            setOptions(options);

            locals.gridOptions.columns[0].width_all = 300;
            locals.gridOptions.columns[1].width_all = 300;
            locals.gridOptions.columns[2].width_all = 300;

            spyOn(bbViewKeeperBuilder, 'create').and.returnValue(
                {
                    destroy: function () {

                    },
                    scrollToTop: function () {

                    },
                    syncElPosition: function () {

                    },
                    isFixed: false
                }
            );

            el = setUpGrid(gridWrapperHtml, locals);

            setGridData(dataSet1);

            topScrollbarEl = el.find('.bb-grid-container .bb-grid-toolbar-container .bb-grid-top-scrollbar');

            tableWrapperEl = el.find('.table-responsive');

            topScrollbarEl.scrollLeft(20);

            topScrollbarEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(tableWrapperEl.scrollLeft()).toBe(20);
            } else {
                expect(tableWrapperEl.scrollLeft()).toBe(0);
            }

            tableWrapperEl.scrollLeft(10);

            tableWrapperEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(topScrollbarEl.scrollLeft()).toBe(10);
            } else {
                expect(topScrollbarEl.scrollLeft()).toBe(0);
            }

            topScrollbarEl.scroll();

            headerViewKeeperEl = el.find('.table-responsive .ui-jqgrid-hdiv');
            headerViewKeeperEl.addClass('bb-viewkeeper-fixed');
            topScrollbarEl.scrollLeft(5);

            topScrollbarEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(headerViewKeeperEl.scrollLeft()).toBe(5);
            } else {
                expect(headerViewKeeperEl.scrollLeft()).toBe(0);
            }

            tableWrapperEl.scrollLeft(3);
            tableWrapperEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(3);

            topScrollbarEl.scrollLeft(0);
            topScrollbarEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(0);

            headerViewKeeperEl.removeClass('bb-viewkeeper-fixed');

            tableWrapperEl.scrollLeft(5);
            tableWrapperEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(0);

        });
    });

    describe('add button on toolbar', function () {
        it('can be enabled', function () {
            var addButtonEl;
            setOptions(options);

            locals.gridOptions.onAddClick = function () {

            };

            el = setUpGrid(basicGridHtml, locals);

            addButtonEl = getAddButton(el);

            expect(addButtonEl).toBeVisible();
        });

        it('can call the onAddClick function when the add button is clicked', function () {
            var addButtonCalled = false,
                addButtonEl;

            el = setUpGrid(basicGridHtml, locals);

            setOptions(options);

            locals.gridOptions.onAddClick = function () {
                addButtonCalled = true;
            };

            addButtonEl = getAddButton(el);

            expect(addButtonCalled).toBe(false);

            addButtonEl.click();

            expect(addButtonCalled).toBe(true);
        });
    });

    describe('searching', function () {
        it('sets searchText on search', function () {
            var searchEl,
                searchIconEl;

            el = setUpGrid(basicGridHtml);
            setOptions(options);

            setGridData(dataSet1);

            searchEl = el.find('.bb-grid-toolbar-container .bb-search-container input');

            searchEl.eq(0).val('John').trigger('change');

            searchIconEl = el.find('.bb-grid-toolbar-container .bb-search-container .bb-search-icon');
            searchIconEl.eq(0).click();

            $scope.$digest();

            expect($scope.locals.gridOptions.searchText).toBe('John');

        });

        it('responds to consumer searchText change', function () {
            var searchEl;

            el = setUpGrid(basicGridHtml);
            setOptions(options);

            setGridData(dataSet1);

            searchEl = el.find('.bb-grid-toolbar-container .bb-search-container input');

            expect(searchEl).toHaveValue('');

            $scope.locals.gridOptions.searchText = 'John';

            $scope.$digest();

            expect(searchEl).toHaveValue('John');
        });
    });

    describe('custom toolbar', function () {
        it('can have custom controls on the toolbar', function () {
            var customClicked = false,
                customToolbarGridHtml = '
<bb-grid bb-grid-options="locals.gridOptions" bb-grid-custom-toolbar><bb-grid-toolbar><button type="button" class="btn bb-btn-secondary bb-grid-toolbar-btn bb-test-button" ng-click="locals.clickCustom()">This is a custom button</button></bb-grid-toolbar></bb-grid>
';
            locals.clickCustom = function () {
                customClicked = true;
            };

            el = setUpGrid(customToolbarGridHtml, locals);
            setOptions(options);

            el.find('.bb-test-button').click();

            expect(customClicked).toBe(true);
        });
    });
});
<commit_msg>Update gridtoolbar.spec.js<commit_after>/*jshint browser: true, jasmine: true */
/*global angular, inject, module, $ */

describe('Grid toolbars', function () {
    'use strict';

    var basicGridHtml,
        bbViewKeeperBuilder,
        $compile,
        $document,
        el,
        dataSet1,
        fxOff,
        locals,
        $scope,
        options;

    function setUpGrid(gridHtml, setLocals) {
        var el = angular.element(gridHtml);

        $document.find('body').eq(0).append(el);

        if (angular.isDefined(setLocals)) {
            $scope.locals = setLocals;
        } else {
            $scope.locals = locals;
        }

        $compile(el)($scope);

        $scope.$digest();

        return el;
    }

    function getAddButton(el) {
        return el.find('.bb-grid-container .bb-grid-toolbar-container .bb-grid-toolbar-btn.btn-primary');
    }

    function setGridData(data) {
        $scope.locals.gridOptions.data = data;
        $scope.$digest();
    }

    function setOptions(options) {
        locals.gridOptions = options;
        $scope.$digest();
    }

    beforeEach(module('ngMock'));
    beforeEach(module(
        'sky.grids',
        'sky.templates'
    ));

    beforeEach(inject(function (_$rootScope_, _$compile_, _$document_, _bbViewKeeperBuilder_) {
        $scope = _$rootScope_;
        $compile = _$compile_;

        $document = _$document_;

        bbViewKeeperBuilder = _bbViewKeeperBuilder_;

        locals = {
        };

        options =  {
            columns: [
                {
                    caption: 'Name',
                    jsonmap: 'name',
                    id: 1,
                    name: 'name'
                },
                {
                    caption: 'Instrument',
                    jsonmap: 'instrument',
                    id: 2,
                    name: 'instrument'
                },
                {
                    caption: 'Biography',
                    jsonmap: 'bio',
                    id: 3,
                    name: 'bio'
                }
            ],
            data: [],
            selectedColumnIds: [1, 2, 3]
        };

        basicGridHtml = '
<bb-grid bb-grid-options="locals.gridOptions"></bb-grid>
';

        dataSet1 = [
            {
                id: 'blarrrg',
                name: 'John',
                instrument: 'Rhythm guitar'
            },
            {
                name: 'Paul',
                instrument: 'Bass',
                bio: 'Lorem'
            },
            {
                name: 'George',
                instrument: 'Lead guitar'
            },
            {
                name: 'Ringo',
                instrument: 'Drums'
            }
        ];

        el = {};
        fxOff =  $.fx.off;
        //turn off jquery animate.
        $.fx.off = true;

    }));

    afterEach(function () {
        if (angular.isDefined(el)) {
            if (angular.isFunction(el.remove)) {
                el.remove();
            }
        }
        $.fx.off = fxOff;
    });

    describe('inline filters', function () {
        it('will toggle the visibility of the filters if the hasInlineFilters option is specified and it will react to options.filtersAreActive change', function () {

            var inlineHtml = '
<bb-grid bb-grid-options="locals.gridOptions">
<input class="hehe" type="checkbox" ng-model="locals.gridOptions.filters.check"/>
</bb-grid>
',
                filterButtonEl,
                filterInputEl;
            setOptions(options);
            locals.gridOptions.hasInlineFilters = true;
            locals.gridOptions.filters = {
                check: false
            };

            el = setUpGrid(inlineHtml, locals);

            filterInputEl = el.find('.hehe');

            expect(filterInputEl).not.toBeVisible();

            filterButtonEl = el.find('.bb-filter-btn');

            filterButtonEl.click();

            $scope.$digest();

            expect(filterInputEl).toBeVisible();

            $scope.locals.gridOptions.filters.check = true;
            $scope.locals.gridOptions.filtersAreActive = true;
            $scope.$digest();

            expect(filterButtonEl).toHaveClass('bb-filters-inline-active');

            expect($scope.locals.gridOptions.filters.check).toBe(true);

            $scope.locals.gridOptions.filters.check = false;
            $scope.locals.gridOptions.filtersAreActive = false;
            $scope.$digest();

            expect(filterButtonEl).not.toHaveClass('bb-filters-inline-active');

            expect($scope.locals.gridOptions.filters.check).toBe(false);

            filterButtonEl.click();

            $scope.$digest();

            expect(filterInputEl).not.toBeVisible();

        });

        it('will set the visibility of the filters if options.filtersOpen is defined', function () {
            var inlineHtml = '
<bb-grid bb-grid-options="locals.gridOptions">
<input class="hehe" type="checkbox" ng-model="locals.gridOptions.filters.check"/>
</bb-grid>
',
                filterInputEl;
            setOptions(options);
            locals.gridOptions.hasInlineFilters = true;
            locals.gridOptions.filtersOpen = true;

            el = setUpGrid(inlineHtml, locals);

            filterInputEl = el.find('.hehe');

            expect(filterInputEl).toBeVisible();

            locals.gridOptions.filtersOpen = false;
            $scope.$digest();

            expect(filterInputEl).not.toBeVisible();

            $scope.$destroy();

        });
    });

    describe('top scrollbar scrolling', function () {
        it('will have a top horizontal scroll bar that will sync with the bottom scroll bar', function () {
            var topScrollbarEl,
                tableWrapperEl,
                headerViewKeeperEl,
                gridWrapperHtml = '
<bb-grid bb-grid-options="locals.gridOptions"></bb-grid>
';

            setOptions(options);

            locals.gridOptions.columns[0].width_all = 300;
            locals.gridOptions.columns[1].width_all = 300;
            locals.gridOptions.columns[2].width_all = 300;

            spyOn(bbViewKeeperBuilder, 'create').and.returnValue(
                {
                    destroy: function () {

                    },
                    scrollToTop: function () {

                    },
                    syncElPosition: function () {

                    },
                    isFixed: false
                }
            );

            el = setUpGrid(gridWrapperHtml, locals);

            setGridData(dataSet1);

            topScrollbarEl = el.find('.bb-grid-container .bb-grid-toolbar-container .bb-grid-top-scrollbar');

            tableWrapperEl = el.find('.table-responsive');

            topScrollbarEl.scrollLeft(20);

            topScrollbarEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(tableWrapperEl.scrollLeft()).toBe(20);
            } else {
                expect(tableWrapperEl.scrollLeft()).toBe(0);
            }

            tableWrapperEl.scrollLeft(10);

            tableWrapperEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(topScrollbarEl.scrollLeft()).toBe(10);
            } else {
                expect(topScrollbarEl.scrollLeft()).toBe(0);
            }

            topScrollbarEl.scroll();

            headerViewKeeperEl = el.find('.table-responsive .ui-jqgrid-hdiv');
            headerViewKeeperEl.addClass('bb-viewkeeper-fixed');
            topScrollbarEl.scrollLeft(5);

            topScrollbarEl.scroll();

            if (topScrollbarEl.height() > 0) {
                expect(headerViewKeeperEl.scrollLeft()).toBe(5);
            } else {
                expect(headerViewKeeperEl.scrollLeft()).toBe(0);
            }

            tableWrapperEl.scrollLeft(3);
            tableWrapperEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(3);

            topScrollbarEl.scrollLeft(0);
            topScrollbarEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(0);

            headerViewKeeperEl.removeClass('bb-viewkeeper-fixed');

            tableWrapperEl.scrollLeft(5);
            tableWrapperEl.scroll();

            expect(headerViewKeeperEl.scrollLeft()).toBe(0);

        });
    });

    describe('add button on toolbar', function () {
        it('can be enabled', function () {
            var addButtonEl;
            setOptions(options);

            locals.gridOptions.onAddClick = function () {

            };

            el = setUpGrid(basicGridHtml, locals);

            addButtonEl = getAddButton(el);

            expect(addButtonEl).toBeVisible();
        });

        it('can call the onAddClick function when the add button is clicked', function () {
            var addButtonCalled = false,
                addButtonEl;

            el = setUpGrid(basicGridHtml, locals);

            setOptions(options);

            locals.gridOptions.onAddClick = function () {
                addButtonCalled = true;
            };

            addButtonEl = getAddButton(el);

            expect(addButtonCalled).toBe(false);

            addButtonEl.click();

            expect(addButtonCalled).toBe(true);
        });
    });

    describe('searching', function () {
        it('sets searchText on search', function () {
            var searchEl,
                searchIconEl;

            el = setUpGrid(basicGridHtml);
            setOptions(options);

            setGridData(dataSet1);

            searchEl = el.find('.bb-grid-toolbar-container .bb-search-container input');

            searchEl.eq(0).val('John').trigger('change');

            searchIconEl = el.find('.bb-grid-toolbar-container .bb-search-container .bb-search-icon');
            searchIconEl.eq(0).click();

            $scope.$digest();

            expect($scope.locals.gridOptions.searchText).toBe('John');

        });

        it('responds to consumer searchText change', function () {
            var searchEl;

            el = setUpGrid(basicGridHtml);
            setOptions(options);

            setGridData(dataSet1);

            searchEl = el.find('.bb-grid-toolbar-container .bb-search-container input');

            expect(searchEl).toHaveValue('');

            $scope.locals.gridOptions.searchText = 'John';

            $scope.$digest();

            expect(searchEl).toHaveValue('John');
        });
    });

    describe('custom toolbar', function () {
        it('can have custom controls on the toolbar', function () {
            var customClicked = false,
                customToolbarGridHtml = '
<bb-grid bb-grid-options="locals.gridOptions" bb-grid-custom-toolbar><bb-grid-toolbar><button type="button" class="btn bb-btn-secondary bb-grid-toolbar-btn bb-test-button" ng-click="locals.clickCustom()">This is a custom button</button></bb-grid-toolbar></bb-grid>
';
            locals.clickCustom = function () {
                customClicked = true;
            };

            el = setUpGrid(customToolbarGridHtml, locals);
            setOptions(options);

            el.find('.bb-test-button').click();

            expect(customClicked).toBe(true);
        });
    });
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move = move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move = move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var computerMove();
    var playerMove();
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    computerMove = getComputerMove();
        playerMove = getPlayerMove();

        if (computerMove == playerMove) {
            winner = "tie";
        }
        else if ((computerMove == "rock" && playerMove == "scissors") || (computerMove == "scissors" && playerMove == "paper") || (computerMove == "paper" && playerMove == "rock")) {
            winner = "computer";
        }
        else {
            winner = "player";
        }
        return winner;
    }

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<commit_msg>new and complete RPS code after unit 5<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    move = move || getInput();
    return move;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    move = move || randomPlay();
    return move;
}

// getWinner();
// getWinner("rock", "scissors");

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.

    // computerMove = getComputerMove();
    // playerMove = getPlayerMove();

    if (computerMove === playerMove) {
        winner = "tie";
    } else if ((computerMove === "rock" && playerMove === "scissors") || (computerMove === "scissors" && playerMove === "paper") || (computerMove === "paper" && playerMove === "rock")) {
        winner = "computer";
    } else {
        winner = "player";
    }
    return winner;
}

function playGame() {
    var winner;
    var playerMove;
    var computerMove;

    playerMove = getPlayerMove(); // scissors
    computerMove = getComputerMove(); // rock

    winner = getWinner(playerMove, computerMove); // "computer"
    console.log("You chose " + playerMove + ", and your opponent chose " + computerMove + ".");
    console.log(winner + " wins!");

    return winner; // "computer"
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0; // count how many times the player has won
    var computerWins = 0;

    while(playerWins < 5 && computerWins < 5) {
        var winner = playGame();
        if (winner === 'player'){
            playerWins += 1;
        }
        else if (winner === 'computer'){
            computerWins += 1;
        }
        console.log("The score is " + playerWins + " to " + computerWins);
    }
    return [playerWins, computerWins];
}
playToFive();
<|endoftext|>