<commit_before>import React from 'react';
import AceEditor from 'react-ace';
import brace from 'brace';
import EditorActionCreators from '../actions/EditorActionCreators';
import EditorStore from '../stores/EditorStore';
import AlertActions from '../actions/AlertActions';
import EditorToolbar from './EditorToolbar';
import Mousetrap from 'mousetrap';
import smalltalk from 'smalltalk';
import ConsoleOutput from './ConsoleOutput';
import RobotActions from '../actions/RobotActions';
import Ansible from '../utils/Ansible';
import {Panel} from 'react-bootstrap';
import { EditorButton } from './EditorClasses';
import 'brace/mode/python';
// React-ace themes
import 'brace/theme/monokai';
import 'brace/theme/github';
import 'brace/theme/tomorrow';
import 'brace/theme/kuroir';
import 'brace/theme/twilight';
import 'brace/theme/xcode';
import 'brace/theme/textmate';
import 'brace/theme/solarized_dark';
import 'brace/theme/solarized_light';
import 'brace/theme/terminal';

export default React.createClass({
  getInitialState() {
    return {
      showConsole: false,
      filepath: null,
      latestSaveCode: '',
      editorCode: '',
      editorTheme: localStorage.getItem('editorTheme') || 'monokai'
    };
  },
  componentDidMount() {
    Mousetrap.prototype.stopCallback = function(e, element, combo) {
      return false; // Always respond to keyboard combos
    };

    Mousetrap.bind(['mod+s'], (e)=>{
      if (e.preventDefault) {
        e.preventDefault();
      }
      this.saveFile();
    });

    // If possible, reopen the last opened file.
    let lastFile = localStorage.getItem('lastFile');
    if (lastFile !== null) {
      EditorActionCreators.readFilepath(lastFile);
    }

    EditorStore.on('change', this.updateEditorData);
  },
  componentWillUnmount() {
    Mousetrap.unbind(['mod+s']);
    EditorStore.removeListener('change', this.updateEditorData);
  },
  updateEditorData() {
    this.setState({
      filepath: EditorStore.getFilepath(),
      latestSaveCode: EditorStore.getLatestSaveCode(),
      editorCode: EditorStore.getEditorCode()
    });
  },
  openFile() {
    if (this.hasUnsavedChanges()) {
      AlertActions.addAlert(
        'You have unsaved changes.',
        'Please save or discard them before opening another file.');
    } else {
      EditorActionCreators.openFile();
    }
  },
  saveFile() {
    EditorActionCreators.saveFile(this.state.filepath, this.state.editorCode);
  },
  createNewFile() {
    if (this.hasUnsavedChanges()) {
      AlertActions.addAlert(
        'You have unsaved changes!',
        'Please save or discard them before creating a new file.');
    } else {
      EditorActionCreators.createNewFile();
    }
  },
  deleteFile() {
    smalltalk.confirm(
      'Warning:',
      'This will delete your file permanently!').then(()=>{
        EditorActionCreators.deleteFile(this.state.filepath);
      }, ()=>console.log('Cancel.'))
  },
  editorUpdate(newVal) {
    EditorActionCreators.editorUpdate(newVal);
  },
  toggleConsole() {
    this.setState({showConsole: !this.state.showConsole});
    // must call resize method after changing height of ace editor
    setTimeout(()=>this.refs.CodeEditor.editor.resize(), 0.1);
  },
  clearConsole() {
    RobotActions.clearConsole();
  },
  startRobot() {
    Ansible.sendMessage('execute', {
      code: this.state.editorCode
    });
  },
  stopRobot() {
    Ansible.sendMessage('stop', {});
  },
  generateButtons() {
    // The buttons which will be in the button toolbar
    return [
      {
        groupId: 'file-operations-buttons',
        buttons: [
          new EditorButton('save', 'Save', this.saveFile, 'floppy-disk'),
          new EditorButton('open', 'Open', this.openFile, 'folder-open'),
          new EditorButton('create', 'New', this.createNewFile, 'file'),
          new EditorButton('delete', 'Delete', this.deleteFile, 'trash')
        ],
      }, {
        groupId: 'code-execution-buttons',
        buttons: [
          new EditorButton('run', 'Run', this.startRobot, 'play', (this.props.isRunningCode || !this.props.connectionStatus)),
          new EditorButton('stop', 'Stop', this.stopRobot, 'stop', !(this.props.isRunningCode && this.props.connectionStatus)),
          new EditorButton('toggle-console', 'Toggle Console', this.toggleConsole, 'console'),
          new EditorButton('clear-console', 'Clear Console', this.clearConsole, 'remove')
        ]
      }
    ];
  },
  pathToName(filepath) {
    if (filepath !== null) {
      return filepath.split('/').pop();
    } else {
      return '[ New File ]';
    }
  },
  hasUnsavedChanges() {
    return (this.state.latestSaveCode !== this.state.editorCode);
  },
  changeTheme(theme) {
    localStorage.setItem('editorTheme', theme);
    this.setState({editorTheme: theme});
  },
  themes: [
    'monokai',
    'github',
    'tomorrow',
    'kuroir',
    'twilight',
    'xcode',
    'textmate',
    'solarized_dark',
    'solarized_light',
    'terminal'
  ],
  render() {
    let consoleHeight = 250;
    let editorHeight = window.innerHeight * 0.66;
    return (
      <Panel
        header={'Editing: ' + this.pathToName(this.state.filepath) +
          (this.hasUnsavedChanges() ? '*' : '')}
        bsStyle="primary">
        <EditorToolbar
          buttons={ this.generateButtons() }
          unsavedChanges={ this.hasUnsavedChanges() }
          changeTheme={ this.changeTheme }
          editorTheme={ this.state.editorTheme }
          themes={ this.themes }
        />
        <AceEditor
          mode="python"
          theme={ this.state.editorTheme }
          width="100%"
          ref="CodeEditor"
          name="CodeEditor"
          height={String(
            editorHeight - this.state.showConsole * (consoleHeight + 30)) + 'px'}
          value = { this.state.editorCode }
          onChange={ this.editorUpdate }
          editorProps={{$blockScrolling: Infinity}}
        />
        <ConsoleOutput
          show={this.state.showConsole}
          height={String(consoleHeight) + 'px'}
          output={this.props.consoleData}/>
      </Panel>
    );
  }
});
<commit_msg>Editor searchbox<commit_after>import React from 'react';
import AceEditor from 'react-ace';
import brace from 'brace';
import EditorActionCreators from '../actions/EditorActionCreators';
import EditorStore from '../stores/EditorStore';
import AlertActions from '../actions/AlertActions';
import EditorToolbar from './EditorToolbar';
import Mousetrap from 'mousetrap';
import smalltalk from 'smalltalk';
import ConsoleOutput from './ConsoleOutput';
import RobotActions from '../actions/RobotActions';
import Ansible from '../utils/Ansible';
import {Panel} from 'react-bootstrap';
import { EditorButton } from './EditorClasses';
import 'brace/ext/searchbox';
import 'brace/mode/python';
// React-ace themes
import 'brace/theme/monokai';
import 'brace/theme/github';
import 'brace/theme/tomorrow';
import 'brace/theme/kuroir';
import 'brace/theme/twilight';
import 'brace/theme/xcode';
import 'brace/theme/textmate';
import 'brace/theme/solarized_dark';
import 'brace/theme/solarized_light';
import 'brace/theme/terminal';

export default React.createClass({
  getInitialState() {
    return {
      showConsole: false,
      filepath: null,
      latestSaveCode: '',
      editorCode: '',
      editorTheme: localStorage.getItem('editorTheme') || 'monokai'
    };
  },
  componentDidMount() {
    Mousetrap.prototype.stopCallback = function(e, element, combo) {
      return false; // Always respond to keyboard combos
    };

    Mousetrap.bind(['mod+s'], (e)=>{
      if (e.preventDefault) {
        e.preventDefault();
      }
      this.saveFile();
    });

    // If possible, reopen the last opened file.
    let lastFile = localStorage.getItem('lastFile');
    if (lastFile !== null) {
      EditorActionCreators.readFilepath(lastFile);
    }

    EditorStore.on('change', this.updateEditorData);
  },
  componentWillUnmount() {
    Mousetrap.unbind(['mod+s']);
    EditorStore.removeListener('change', this.updateEditorData);
  },
  updateEditorData() {
    this.setState({
      filepath: EditorStore.getFilepath(),
      latestSaveCode: EditorStore.getLatestSaveCode(),
      editorCode: EditorStore.getEditorCode()
    });
  },
  openFile() {
    if (this.hasUnsavedChanges()) {
      AlertActions.addAlert(
        'You have unsaved changes.',
        'Please save or discard them before opening another file.');
    } else {
      EditorActionCreators.openFile();
    }
  },
  saveFile() {
    EditorActionCreators.saveFile(this.state.filepath, this.state.editorCode);
  },
  createNewFile() {
    if (this.hasUnsavedChanges()) {
      AlertActions.addAlert(
        'You have unsaved changes!',
        'Please save or discard them before creating a new file.');
    } else {
      EditorActionCreators.createNewFile();
    }
  },
  deleteFile() {
    smalltalk.confirm(
      'Warning:',
      'This will delete your file permanently!').then(()=>{
        EditorActionCreators.deleteFile(this.state.filepath);
      }, ()=>console.log('Cancel.'))
  },
  editorUpdate(newVal) {
    EditorActionCreators.editorUpdate(newVal);
  },
  toggleConsole() {
    this.setState({showConsole: !this.state.showConsole});
    // must call resize method after changing height of ace editor
    setTimeout(()=>this.refs.CodeEditor.editor.resize(), 0.1);
  },
  clearConsole() {
    RobotActions.clearConsole();
  },
  startRobot() {
    Ansible.sendMessage('execute', {
      code: this.state.editorCode
    });
  },
  stopRobot() {
    Ansible.sendMessage('stop', {});
  },
  generateButtons() {
    // The buttons which will be in the button toolbar
    return [
      {
        groupId: 'file-operations-buttons',
        buttons: [
          new EditorButton('save', 'Save', this.saveFile, 'floppy-disk'),
          new EditorButton('open', 'Open', this.openFile, 'folder-open'),
          new EditorButton('create', 'New', this.createNewFile, 'file'),
          new EditorButton('delete', 'Delete', this.deleteFile, 'trash')
        ],
      }, {
        groupId: 'code-execution-buttons',
        buttons: [
          new EditorButton('run', 'Run', this.startRobot, 'play', (this.props.isRunningCode || !this.props.connectionStatus)),
          new EditorButton('stop', 'Stop', this.stopRobot, 'stop', !(this.props.isRunningCode && this.props.connectionStatus)),
          new EditorButton('toggle-console', 'Toggle Console', this.toggleConsole, 'console'),
          new EditorButton('clear-console', 'Clear Console', this.clearConsole, 'remove')
        ]
      }
    ];
  },
  pathToName(filepath) {
    if (filepath !== null) {
      return filepath.split('/').pop();
    } else {
      return '[ New File ]';
    }
  },
  hasUnsavedChanges() {
    return (this.state.latestSaveCode !== this.state.editorCode);
  },
  changeTheme(theme) {
    localStorage.setItem('editorTheme', theme);
    this.setState({editorTheme: theme});
  },
  themes: [
    'monokai',
    'github',
    'tomorrow',
    'kuroir',
    'twilight',
    'xcode',
    'textmate',
    'solarized_dark',
    'solarized_light',
    'terminal'
  ],
  render() {
    let consoleHeight = 250;
    let editorHeight = window.innerHeight * 0.66;
    return (
      <Panel
        header={'Editing: ' + this.pathToName(this.state.filepath) +
          (this.hasUnsavedChanges() ? '*' : '')}
        bsStyle="primary">
        <EditorToolbar
          buttons={ this.generateButtons() }
          unsavedChanges={ this.hasUnsavedChanges() }
          changeTheme={ this.changeTheme }
          editorTheme={ this.state.editorTheme }
          themes={ this.themes }
        />
        <AceEditor
          mode="python"
          theme={ this.state.editorTheme }
          width="100%"
          ref="CodeEditor"
          name="CodeEditor"
          height={String(
            editorHeight - this.state.showConsole * (consoleHeight + 30)) + 'px'}
          value = { this.state.editorCode }
          onChange={ this.editorUpdate }
          editorProps={{$blockScrolling: Infinity}}
        />
        <ConsoleOutput
          show={this.state.showConsole}
          height={String(consoleHeight) + 'px'}
          output={this.props.consoleData}/>
      </Panel>
    );
  }
});
<|endoftext|>


<commit_before>/**
 * GET /
 * Home page.
 */
import Application from '../../application/HelloWorld';

exports.home = (req, res) => {
  res.render('home', {
    Application,
    applicationName: 'HelloWorld',
    preloadedState: Object.assign({}, Application.preloadedState, {
      otherState: 123,
    }),
    payload: {},
    cache: true,
  });
};
<commit_msg>Add payload 'title' and 'description' to render in 'Home' view.<commit_after>/**
 * GET /
 * Home page.
 */
import Application from '../../application/HelloWorld';

exports.home = (req, res) => {
  res.render('home', {
    Application,
    applicationName: 'HelloWorld',
    preloadedState: Object.assign({}, Application.preloadedState, {
      otherState: 123,
    }),
    payload: {
      title: 'My Application',
      description: 'This is an example.',
    },
    cache: true,
  });
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var passport = require('passport');

var indexCtrl = require('../controllers/index.ctrl');
var userCtrl = require('../controllers/user.ctrl');
var coursesCtrl = require('../controllers/courses.ctrl');

/* API routes */
router.get('/courses', coursesCtrl.list);
router.post('/courses', coursesCtrl.create);

/* Frontend routes */
router.get('/', indexCtrl.getIndex);

router.get('/join', userCtrl.getRegister);
router.post('/register', userCtrl.register);
router.get('/login', userCtrl.getLogin);
router.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }));

router.get('/courses/new', coursesCtrl.getCreate);
router.get('/courses/:courseId/edit', coursesCtrl.getEdit);

router.get('/:user', userCtrl.getUser);

module.exports = router;
<commit_msg>add course edit route<commit_after>var express = require('express');
var router = express.Router();
var passport = require('passport');

var indexCtrl = require('../controllers/index.ctrl');
var userCtrl = require('../controllers/user.ctrl');
var coursesCtrl = require('../controllers/courses.ctrl');

/* API routes */
router.get('/courses', coursesCtrl.list);
router.post('/courses', coursesCtrl.create);
router.post('/courses/:courseId', coursesCtrl.edit);

/* Frontend routes */
router.get('/', indexCtrl.getIndex);

router.get('/join', userCtrl.getRegister);
router.post('/register', userCtrl.register);
router.get('/login', userCtrl.getLogin);
router.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }));

router.get('/courses/new', coursesCtrl.getCreate);
router.get('/courses/:courseId/edit', coursesCtrl.getEdit);

router.get('/:user', userCtrl.getUser);

module.exports = router;
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../utils/Class');
var Systems = require('./Systems');

/**
 * @classdesc
 * A base Phaser.Scene class which you could extend for your own use.
 *
 * @class Scene
 * @memberof Phaser
 * @constructor
 * @since 3.0.0
 *
 * @param {(string|Phaser.Scenes.Settings.Config)} config - Scene specific configuration settings.
 */
var Scene = new Class({

    initialize:

    function Scene (config)
    {
        /**
         * The Scene Systems. You must never overwrite this property, or all hell will break lose.
         *
         * @name Phaser.Scene#sys
         * @type {Phaser.Scenes.Systems}
         * @since 3.0.0
         */
        this.sys = new Systems(this, config);

        /**
         * A reference to the Phaser.Game instance.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#game
         * @type {Phaser.Game}
         * @since 3.0.0
         */
        this.game;

        /**
         * A reference to the global Animation Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#anims
         * @type {Phaser.Animations.AnimationManager}
         * @since 3.0.0
         */
        this.anims;

        /**
         * A reference to the global Cache.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#cache
         * @type {Phaser.Cache.CacheManager}
         * @since 3.0.0
         */
        this.cache;

        /**
         * A reference to the game level Data Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#registry
         * @type {Phaser.Data.DataManager}
         * @since 3.0.0
         */
        this.registry;

        /**
         * A reference to the Sound Manager.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#sound
         * @type {Phaser.Sound.BaseSoundManager}
         * @since 3.0.0
         */
        this.sound;

        /**
         * A reference to the Texture Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#textures
         * @type {Phaser.Textures.TextureManager}
         * @since 3.0.0
         */
        this.textures;

        /**
         * A scene level Event Emitter.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#events
         * @type {Phaser.Events.EventEmitter}
         * @since 3.0.0
         */
        this.events;

        /**
         * A scene level Camera System.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#cameras
         * @type {Phaser.Cameras.Scene2D.CameraManager}
         * @since 3.0.0
         */
        this.cameras;

        /**
         * A scene level Game Object Factory.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#add
         * @type {Phaser.GameObjects.GameObjectFactory}
         * @since 3.0.0
         */
        this.add;

        /**
         * A scene level Game Object Creator.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#make
         * @type {Phaser.GameObjects.GameObjectCreator}
         * @since 3.0.0
         */
        this.make;

        /**
         * A reference to the Scene Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#scene
         * @type {Phaser.Scenes.ScenePlugin}
         * @since 3.0.0
         */
        this.scene;

        /**
         * A scene level Game Object Display List.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#children
         * @type {Phaser.GameObjects.DisplayList}
         * @since 3.0.0
         */
        this.children;

        /**
         * A scene level Lights Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#lights
         * @type {Phaser.GameObjects.LightsManager}
         * @since 3.0.0
         */
        this.lights;

        /**
         * A scene level Data Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#data
         * @type {Phaser.Data.DataManager}
         * @since 3.0.0
         */
        this.data;

        /**
         * A scene level Input Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#input
         * @type {Phaser.Input.InputPlugin}
         * @since 3.0.0
         */
        this.input;

        /**
         * A scene level Loader Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#load
         * @type {Phaser.Loader.LoaderPlugin}
         * @since 3.0.0
         */
        this.load;

        /**
         * A scene level Time and Clock Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#time
         * @type {Phaser.Time.Clock}
         * @since 3.0.0
         */
        this.time;

        /**
         * A scene level Tween Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#tweens
         * @type {Phaser.Tweens.TweenManager}
         * @since 3.0.0
         */
        this.tweens;

        /**
         * A scene level Arcade Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#physics
         * @type {Phaser.Physics.Arcade.ArcadePhysics}
         * @since 3.0.0
         */
        this.physics;

        /**
         * A scene level Impact Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#impact
         * @type {Phaser.Physics.Impact.ImpactPhysics}
         * @since 3.0.0
         */
        this.impact;

        /**
         * A scene level Matter Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#matter
         * @type {Phaser.Physics.Matter.MatterPhysics}
         * @since 3.0.0
         */
        this.matter;

        if(typeof PLUGIN_FBINSTANT){
            /**
             * A scene level Facebook Instant Games Plugin.
             * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
             *
             * @name Phaser.Scene#facebook
             * @type {Phaser.FacebookInstantGamesPlugin}
             * @since 3.12.0
             */
            this.facebook;
        }
    },

    /**
     * Should be overridden by your own Scenes.
     *
     * @method Phaser.Scene#update
     * @override
     * @since 3.0.0
     *
     * @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
     * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
     */
    update: function ()
    {
    }

});

module.exports = Scene;
<commit_msg>lint fix<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../utils/Class');
var Systems = require('./Systems');

/**
 * @classdesc
 * A base Phaser.Scene class which you could extend for your own use.
 *
 * @class Scene
 * @memberof Phaser
 * @constructor
 * @since 3.0.0
 *
 * @param {(string|Phaser.Scenes.Settings.Config)} config - Scene specific configuration settings.
 */
var Scene = new Class({

    initialize:

    function Scene (config)
    {
        /**
         * The Scene Systems. You must never overwrite this property, or all hell will break lose.
         *
         * @name Phaser.Scene#sys
         * @type {Phaser.Scenes.Systems}
         * @since 3.0.0
         */
        this.sys = new Systems(this, config);

        /**
         * A reference to the Phaser.Game instance.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#game
         * @type {Phaser.Game}
         * @since 3.0.0
         */
        this.game;

        /**
         * A reference to the global Animation Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#anims
         * @type {Phaser.Animations.AnimationManager}
         * @since 3.0.0
         */
        this.anims;

        /**
         * A reference to the global Cache.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#cache
         * @type {Phaser.Cache.CacheManager}
         * @since 3.0.0
         */
        this.cache;

        /**
         * A reference to the game level Data Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#registry
         * @type {Phaser.Data.DataManager}
         * @since 3.0.0
         */
        this.registry;

        /**
         * A reference to the Sound Manager.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#sound
         * @type {Phaser.Sound.BaseSoundManager}
         * @since 3.0.0
         */
        this.sound;

        /**
         * A reference to the Texture Manager.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#textures
         * @type {Phaser.Textures.TextureManager}
         * @since 3.0.0
         */
        this.textures;

        /**
         * A scene level Event Emitter.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#events
         * @type {Phaser.Events.EventEmitter}
         * @since 3.0.0
         */
        this.events;

        /**
         * A scene level Camera System.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#cameras
         * @type {Phaser.Cameras.Scene2D.CameraManager}
         * @since 3.0.0
         */
        this.cameras;

        /**
         * A scene level Game Object Factory.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#add
         * @type {Phaser.GameObjects.GameObjectFactory}
         * @since 3.0.0
         */
        this.add;

        /**
         * A scene level Game Object Creator.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#make
         * @type {Phaser.GameObjects.GameObjectCreator}
         * @since 3.0.0
         */
        this.make;

        /**
         * A reference to the Scene Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#scene
         * @type {Phaser.Scenes.ScenePlugin}
         * @since 3.0.0
         */
        this.scene;

        /**
         * A scene level Game Object Display List.
         * This property will only be available if defined in the Scene Injection Map.
         *
         * @name Phaser.Scene#children
         * @type {Phaser.GameObjects.DisplayList}
         * @since 3.0.0
         */
        this.children;

        /**
         * A scene level Lights Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#lights
         * @type {Phaser.GameObjects.LightsManager}
         * @since 3.0.0
         */
        this.lights;

        /**
         * A scene level Data Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#data
         * @type {Phaser.Data.DataManager}
         * @since 3.0.0
         */
        this.data;

        /**
         * A scene level Input Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#input
         * @type {Phaser.Input.InputPlugin}
         * @since 3.0.0
         */
        this.input;

        /**
         * A scene level Loader Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#load
         * @type {Phaser.Loader.LoaderPlugin}
         * @since 3.0.0
         */
        this.load;

        /**
         * A scene level Time and Clock Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#time
         * @type {Phaser.Time.Clock}
         * @since 3.0.0
         */
        this.time;

        /**
         * A scene level Tween Manager Plugin.
         * This property will only be available if defined in the Scene Injection Map and the plugin is installed.
         *
         * @name Phaser.Scene#tweens
         * @type {Phaser.Tweens.TweenManager}
         * @since 3.0.0
         */
        this.tweens;

        /**
         * A scene level Arcade Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#physics
         * @type {Phaser.Physics.Arcade.ArcadePhysics}
         * @since 3.0.0
         */
        this.physics;

        /**
         * A scene level Impact Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#impact
         * @type {Phaser.Physics.Impact.ImpactPhysics}
         * @since 3.0.0
         */
        this.impact;

        /**
         * A scene level Matter Physics Plugin.
         * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
         *
         * @name Phaser.Scene#matter
         * @type {Phaser.Physics.Matter.MatterPhysics}
         * @since 3.0.0
         */
        this.matter;

        if (typeof PLUGIN_FBINSTANT)
        {
            /**
             * A scene level Facebook Instant Games Plugin.
             * This property will only be available if defined in the Scene Injection Map, the plugin is installed and configured.
             *
             * @name Phaser.Scene#facebook
             * @type {Phaser.FacebookInstantGamesPlugin}
             * @since 3.12.0
             */
            this.facebook;
        }
    },

    /**
     * Should be overridden by your own Scenes.
     *
     * @method Phaser.Scene#update
     * @override
     * @since 3.0.0
     *
     * @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
     * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
     */
    update: function ()
    {
    }

});

module.exports = Scene;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const express = require('express');
const Reading = require('../models/Reading');
const moment = require('moment');
const streamBuffers = require('stream-buffers');
const multer = require('multer');
const streamToDB = require('../services/loadFromCsvStream');
const authenticator = require('./authenticator');
const validate = require('jsonschema').validate;

const router = express.Router();

// The upload here ensures that the file is saved to server RAM rather than disk
const upload = multer({ storage: multer.memoryStorage() });

router.use(authenticator);
router.post('/:meter_id', upload.single('csvFile'), async (req, res) => {
	const validParams = {
		type: 'object',
		maxProperties: 1,
		required: ['meter_id'],
		properties: {
			meter_id: {
				type: 'number'
			}
		}
	};
	if (!validate(req.params, validParams).valid || !req.file.buffer) {
		res.sendStatus(400);
	} else {
		try {
			const id = parseInt(req.params.meter_id);
			const myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
				frequency: 10,
				chunkSize: 2048
			});
			myReadableStreamBuffer.put(req.file.buffer);
			// stop() indicates we are done putting the data in our readable stream.
			myReadableStreamBuffer.stop();
			try {
				await streamToDB(myReadableStreamBuffer, row => {
					const readRate = Number(row[0]);
					const endTimestamp = moment(row[1], 'MM/DD/YYYY HH:mm');
					const startTimestamp = moment(row[1], 'MM/DD/YYYY HH:mm').subtract(60, 'minutes');
					return new Reading(id, readRate, startTimestamp, endTimestamp);
				}, (readings, tx) => Reading.insertOrUpdateAll(readings, tx));
				res.status(200).json({ success: true });
			} catch (e) {
				res.status(403).json({ success: false, message: 'Failed to upload data.' });
			}
		} catch (err) {
			res.status(400).send({
				success: false,
				message: 'Incorrect file type.'
			});
		}
	}
});

module.exports = router;
<commit_msg>Fix file processing reading validation<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const express = require('express');
const Reading = require('../models/Reading');
const moment = require('moment');
const streamBuffers = require('stream-buffers');
const multer = require('multer');
const streamToDB = require('../services/loadFromCsvStream');
const authenticator = require('./authenticator');
const validate = require('jsonschema').validate;

const router = express.Router();

// The upload here ensures that the file is saved to server RAM rather than disk
const upload = multer({ storage: multer.memoryStorage() });

router.use(authenticator);
router.post('/:meter_id', upload.single('csvFile'), async (req, res) => {
	const validParams = {
		type: 'object',
		maxProperties: 1,
		required: ['meter_id'],
		properties: {
			meter_id: {
				type: 'string'
			}
		}
	};
	if (!validate(req.params, validParams).valid || !req.file.buffer) {
		res.sendStatus(400);
	} else {
		try {
			const id = parseInt(req.params.meter_id);
			const myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
				frequency: 10,
				chunkSize: 2048
			});
			myReadableStreamBuffer.put(req.file.buffer);
			// stop() indicates we are done putting the data in our readable stream.
			myReadableStreamBuffer.stop();
			try {
				await streamToDB(myReadableStreamBuffer, row => {
					const readRate = Number(row[0]);
					const endTimestamp = moment(row[1], 'MM/DD/YYYY HH:mm');
					const startTimestamp = moment(row[1], 'MM/DD/YYYY HH:mm').subtract(60, 'minutes');
					return new Reading(id, readRate, startTimestamp, endTimestamp);
				}, (readings, tx) => Reading.insertOrUpdateAll(readings, tx));
				res.status(200).json({ success: true });
			} catch (e) {
				res.status(403).json({ success: false, message: 'Failed to upload data.' });
			}
		} catch (err) {
			res.status(400).send({
				success: false,
				message: 'Incorrect file type.'
			});
		}
	}
});

module.exports = router;
<|endoftext|>


<commit_before>var m = require('mithril');
var _ = require('lodash');

var app = {state: {pageY: 0, pageHeight: window.innerHeight}};

var db = m.prop({voters:[],votes:[],constituencies:[]});
m.request({method: "GET", url: "votes.json"}).then(db);

var gridrow = {};

gridrow.controller = function(vote, voteID, gridCtrl) {
    var a=[], d=[], dTot=0;
    vote.withParties.split('').sort().map(function(p, i) {
        if(p === ' ' || vote.withVotes[i] === '-') return;
        if(a.length === 0 || a[a.length-1].p !== p) {
            a.push({p:p, n:0});
        }
        a[a.length-1].n++;
    });
    vote.againstParties.split('').sort().map(function(p, i) {
        if(p == ' ' || vote.againstVotes[i] == '-') return;
        if(d.length === 0 || d[d.length-1].p !== p) {
            d.push({p:p, n:0});
        }
        d[d.length-1].n++;
        dTot++;
    });
    this.isPopped = function() {
        return gridCtrl.popped() == this.vm.vote;
    };
    this.popThis = gridCtrl.popVote.bind(gridCtrl, vote, voteID);
    this.vm = {
        vote: vote,
        voteID: voteID,
        assenting: a,
        dissenting: d,
        dissentingTot: dTot,
    };
};

gridrow.view = function(ctrl) {
    return m('.row', {
        class: ctrl.isPopped() ? 'active' : '',
        key: ctrl.vm.voteID,
        onmouseover: ctrl.popThis,
    }, [
        m('div', {
            style: {
                width: ''+((200-ctrl.vm.dissentingTot)*2)+'px',
            }
        }),
        ctrl.vm.dissenting.map(function(v) {
            return m('div', {
                class: 'dissenting party '+v.p,
                style: {
                    width: ''+(v.n*2)+'px',
                },
            });
        }),
        ctrl.vm.assenting.map(function(v) {
            return m('div', {
                class: 'party '+v.p,
                style: {
                    width: ''+(v.n*2)+'px',
                },
            });
        }),
    ]);
};

var grid = {};

grid.controller = function() {
    this.vm = {
        offsetTop: 0,
        popped: m.prop(),
        session: m.prop({}),
        sessions: m.prop([]),
    };
    this.popVote = function(vote, voteID) {
        this.vm.popped(vote);
    };
    this.shouldShowVote = function(vote) {
        return (this.vm.session().parliament === vote.parliament &&
                this.vm.session().session === vote.session);
    };
    this.popped = this.vm.popped;
    this.setSession = function(s) {
        this.vm.session(s);
        this.vm.popped(null);
    };
    this.sessions = function() {
        if (this.db === db()) return this.vm.sessions();
        this.db = db();
        var saw = {}, s = [];
        this.db.votes.map(function(v) {
            var k = ''+v.parliament+' '+v.session;
            if(!saw[k]) {
                saw[k] = {
                    parliament: v.parliament,
                    session: v.session,
                    dateFirst: v.date,
                    dateLast: v.date,
                };
                s.push(saw[k]);
            } else if(saw[k].dateFirst > v.date) {
                saw[k].dateFirst = v.date;
            } else if(saw[k].dateLast < v.date) {
                saw[k].dateLast = v.date;
            }
        });
        s = s.sort(function(a,b) {
            if(a.parliament == b.parliament) return a.session-b.session;
            return a.parliament-b.parliament;
        });
        if(!this.vm.session()['parliament'] && s.length > 0)
            this.vm.session(s[s.length-1]);
        return this.vm.sessions(s);
    };
};

grid.view = function(ctrl) {
    return m('html', [
        m('body', [
            grid.viewMenu(ctrl),
            grid.viewGrid(ctrl),
            grid.viewPop(ctrl),
        ]),
    ]);
}

grid.viewMenu = function(ctrl) {
    return [
        m('.ui.pointing.menu', ctrl.sessions().map(function(s) {
            return m('a.item[href=javascript:;]', {
                class: ctrl.vm.session() === s ? 'active' : '',
                onclick: ctrl.setSession.bind(ctrl, s),
            }, [
                m('h4', [
                    'P', s.parliament, ' S', s.session,
                ]),
            ]);
        })),
        !ctrl.vm.session()['parliament'] ? null : m('.ui.grid.container', m('.ui.grid.row', m('p', [
            m('h4', [
                'Parliament ', ctrl.vm.session().parliament,
                ', Session ', ctrl.vm.session().session,
            ]),
            m('p', [
                'Party votes from ',
                ctrl.vm.session().dateFirst,
                ' to ',
                ctrl.vm.session().dateLast,
            ]),
        ]))),
    ];
}

grid.viewPop = function(ctrl) {
    var v = ctrl.popped();
    if(!v) return null;

    var loyalCount = 0, rogues = [], partyVote = {};
    ['with', 'against'].map(function(withagainst) {
        v[withagainst+'Parties'].split('').map(function(p) {
            if(p === ' ' || p === 'I') return;
            if(!partyVote[p]) partyVote[p] = {'with': 0, 'against': 0};
            partyVote[p][withagainst]++;
        });
    });
    Object.keys(partyVote).map(function(p) {
        if(partyVote[p]['with'] >= partyVote[p]['against'])
            partyVote[p] = 'with';
        else
            partyVote[p] = 'against';
    });
    ['with', 'against'].map(function(withagainst) {
        v[withagainst+'Parties'].split('').map(function(p, i) {
            if(p === ' ' | p === 'I') return;
            if(partyVote[p] === withagainst) return loyalCount++;
            var rogue = db().voters[i];
            rogues.push(m('.item', [
                m('span', {style:{'float':'left',width:'2em'}}, p),
                rogue.name,
            ]));
        });
    });

    return m('.pop.ui.message', {
        style: {
            position: 'fixed',
            top: '6em',
            right: '2em',
            width: '30%',
            height: '40em',
            padding: '1em',
        },
    }, [
        m('.header', v.date),
        m('p', {
            style: {
                height: '5em',
                overflow: 'hidden',
            },
        }, v.description),
        m('.ui.divider'),
        m('p', 'MPs who voted with their party: ', loyalCount),
        m('.header', 'MPs who voted against their party: ', rogues.length),
        m('.ui.list', rogues),
    ]);
}

grid.viewGrid = function(ctrl) {
    var y = 0;
    return m('.vgrid', {
        config: function(el) { ctrl.vm.offsetTop = el.offsetTop },
        key:'grid',
    }, [
        db().votes.map(function(vote, voteID) {
            if(!ctrl.shouldShowVote(vote)) return;
            y++;
            if((y + 5) * 8 + ctrl.vm.offsetTop < app.state.pageY ||
               (y - 5) * 8 + ctrl.vm.offsetTop > app.state.pageY + app.state.pageHeight)
                return m('.row');
            else
                return m.component(gridrow, vote, voteID, ctrl);
        }),
    ]);
};

document.defaultView.addEventListener("scroll resize", checkScroll);
document.defaultView.setInterval(checkScroll, 100);
function checkScroll() {
    if (app.state.pageY !== document.defaultView.scrollY ||
        app.state.pageHeight !== document.defaultView.innerHeight) {
        app.state.pageY = document.defaultView.scrollY;
        app.state.pageHeight = document.defaultView.innerHeight;
        m.redraw();
    }
}

m.module(document.body, grid);
<commit_msg>Tweak popup css<commit_after>var m = require('mithril');
var _ = require('lodash');

var app = {state: {pageY: 0, pageHeight: window.innerHeight}};

var db = m.prop({voters:[],votes:[],constituencies:[]});
m.request({method: "GET", url: "votes.json"}).then(db);

var gridrow = {};

gridrow.controller = function(vote, voteID, gridCtrl) {
    var a=[], d=[], dTot=0;
    vote.withParties.split('').sort().map(function(p, i) {
        if(p === ' ' || vote.withVotes[i] === '-') return;
        if(a.length === 0 || a[a.length-1].p !== p) {
            a.push({p:p, n:0});
        }
        a[a.length-1].n++;
    });
    vote.againstParties.split('').sort().map(function(p, i) {
        if(p == ' ' || vote.againstVotes[i] == '-') return;
        if(d.length === 0 || d[d.length-1].p !== p) {
            d.push({p:p, n:0});
        }
        d[d.length-1].n++;
        dTot++;
    });
    this.isPopped = function() {
        return gridCtrl.popped() == this.vm.vote;
    };
    this.popThis = gridCtrl.popVote.bind(gridCtrl, vote, voteID);
    this.vm = {
        vote: vote,
        voteID: voteID,
        assenting: a,
        dissenting: d,
        dissentingTot: dTot,
    };
};

gridrow.view = function(ctrl) {
    return m('.row', {
        class: ctrl.isPopped() ? 'active' : '',
        key: ctrl.vm.voteID,
        onmouseover: ctrl.popThis,
    }, [
        m('div', {
            style: {
                width: ''+((200-ctrl.vm.dissentingTot)*2)+'px',
            }
        }),
        ctrl.vm.dissenting.map(function(v) {
            return m('div', {
                class: 'dissenting party '+v.p,
                style: {
                    width: ''+(v.n*2)+'px',
                },
            });
        }),
        ctrl.vm.assenting.map(function(v) {
            return m('div', {
                class: 'party '+v.p,
                style: {
                    width: ''+(v.n*2)+'px',
                },
            });
        }),
    ]);
};

var grid = {};

grid.controller = function() {
    this.vm = {
        offsetTop: 0,
        popped: m.prop(),
        session: m.prop({}),
        sessions: m.prop([]),
    };
    this.popVote = function(vote, voteID) {
        this.vm.popped(vote);
    };
    this.shouldShowVote = function(vote) {
        return (this.vm.session().parliament === vote.parliament &&
                this.vm.session().session === vote.session);
    };
    this.popped = this.vm.popped;
    this.setSession = function(s) {
        this.vm.session(s);
        this.vm.popped(null);
    };
    this.sessions = function() {
        if (this.db === db()) return this.vm.sessions();
        this.db = db();
        var saw = {}, s = [];
        this.db.votes.map(function(v) {
            var k = ''+v.parliament+' '+v.session;
            if(!saw[k]) {
                saw[k] = {
                    parliament: v.parliament,
                    session: v.session,
                    dateFirst: v.date,
                    dateLast: v.date,
                };
                s.push(saw[k]);
            } else if(saw[k].dateFirst > v.date) {
                saw[k].dateFirst = v.date;
            } else if(saw[k].dateLast < v.date) {
                saw[k].dateLast = v.date;
            }
        });
        s = s.sort(function(a,b) {
            if(a.parliament == b.parliament) return a.session-b.session;
            return a.parliament-b.parliament;
        });
        if(!this.vm.session()['parliament'] && s.length > 0)
            this.vm.session(s[s.length-1]);
        return this.vm.sessions(s);
    };
};

grid.view = function(ctrl) {
    return m('html', [
        m('body', [
            grid.viewMenu(ctrl),
            grid.viewGrid(ctrl),
            grid.viewPop(ctrl),
        ]),
    ]);
}

grid.viewMenu = function(ctrl) {
    return [
        m('.ui.pointing.menu', ctrl.sessions().map(function(s) {
            return m('a.item[href=javascript:;]', {
                class: ctrl.vm.session() === s ? 'active' : '',
                onclick: ctrl.setSession.bind(ctrl, s),
            }, [
                m('h4', [
                    'P', s.parliament, ' S', s.session,
                ]),
            ]);
        })),
        !ctrl.vm.session()['parliament'] ? null : m('.ui.grid.container', m('.ui.grid.row', m('p', [
            m('h4', [
                'Parliament ', ctrl.vm.session().parliament,
                ', Session ', ctrl.vm.session().session,
            ]),
            m('p', [
                'Party votes from ',
                ctrl.vm.session().dateFirst,
                ' to ',
                ctrl.vm.session().dateLast,
            ]),
        ]))),
    ];
}

grid.viewPop = function(ctrl) {
    var v = ctrl.popped();
    if(!v) return null;

    var loyalCount = 0, rogues = [], partyVote = {};
    ['with', 'against'].map(function(withagainst) {
        v[withagainst+'Parties'].split('').map(function(p) {
            if(p === ' ' || p === 'I') return;
            if(!partyVote[p]) partyVote[p] = {'with': 0, 'against': 0};
            partyVote[p][withagainst]++;
        });
    });
    Object.keys(partyVote).map(function(p) {
        if(partyVote[p]['with'] >= partyVote[p]['against'])
            partyVote[p] = 'with';
        else
            partyVote[p] = 'against';
    });
    ['with', 'against'].map(function(withagainst) {
        v[withagainst+'Parties'].split('').map(function(p, i) {
            if(p === ' ' | p === 'I') return;
            if(partyVote[p] === withagainst) return loyalCount++;
            var rogue = db().voters[i];
            rogues.push(m('.item', [
                m('span', {style:{'float':'left',width:'2em'}}, p),
                rogue.name,
            ]));
        });
    });

    return m('.pop.ui.message', {
        style: {
            position: 'fixed',
            top: '10%',
            right: '2em',
            width: '30%',
            height: '80%',
            padding: '1em',
            overflowY: 'scroll',
        },
    }, [
        m('.header', v.date),
        m('p', {
            style: {
                height: '5em',
                overflow: 'hidden',
            },
        }, v.description),
        m('.ui.divider'),
        m('p', 'MPs who voted with their party: ', loyalCount),
        m('.header', 'MPs who voted against their party: ', rogues.length),
        m('.ui.list', rogues),
    ]);
}

grid.viewGrid = function(ctrl) {
    var y = 0;
    return m('.vgrid', {
        config: function(el) { ctrl.vm.offsetTop = el.offsetTop },
        key:'grid',
    }, [
        db().votes.map(function(vote, voteID) {
            if(!ctrl.shouldShowVote(vote)) return;
            y++;
            if((y + 5) * 8 + ctrl.vm.offsetTop < app.state.pageY ||
               (y - 5) * 8 + ctrl.vm.offsetTop > app.state.pageY + app.state.pageHeight)
                return m('.row');
            else
                return m.component(gridrow, vote, voteID, ctrl);
        }),
    ]);
};

document.defaultView.addEventListener("scroll resize", checkScroll);
document.defaultView.setInterval(checkScroll, 100);
function checkScroll() {
    if (app.state.pageY !== document.defaultView.scrollY ||
        app.state.pageHeight !== document.defaultView.innerHeight) {
        app.state.pageY = document.defaultView.scrollY;
        app.state.pageHeight = document.defaultView.innerHeight;
        m.redraw();
    }
}

m.module(document.body, grid);
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* eslint-disable no-console */
/* global console */

var allocCluster = require('../lib/test-cluster.js');
var collectParallel = require('collect-parallel/array');

var DUMP_LOGS = false;

allocCluster.test('dead exit peers get reaped', {
    size: 10,
    namedRemotes: ['alice', 'alice', 'alice', 'alice', 'alice', 'alice', 'alice'],
    whitelist: [
        // TODO: this is debt, this should not be an expected log; we should
        // understand and fix the cause of and need for this audit
        ['warn', 'partial affinity audit fail'],

        ['info', 'implementing affinity change'],
        ['info', 'pruning ex-affinity peers'],
        ['info', 'draining ex-affinity peer'],
        ['info', 'draining peer'],
        ['info', 'stopping peer drain'],
        ['info', 'Refreshing service peer affinity'],
        ['info', 'reaping dead peers'],
        ['info', 'reaping dead peer'],
        ['info', 'pruning peers'],
        ['info', 'draining pruned peer'],
        ['info', 'refreshed peer partially']
    ]
}, function t(cluster, assert) {
    var activeNum = 3;

    // for more determinism
    cluster.namedRemotes.sort(function byHostPort(a, b) {
        if (a.hostPort < b.hostPort) {
            return -1;
        } else if (a.hostPort > b.hostPort) {
            return 1;
        }
        return 0;
    });

    pruneClusterPears(cluster, assert, initialPruneDone);

    function initialPruneDone() {
        takeLogs();
        assert.comment('- initialPruneDone');

        // Verify that hyperban is connected to all the alices
        checkAllExitPeers(cluster, assert, null);

        // Reap peers that have not registered (nobody)
        reapClusterPears(cluster, assert, initialReapDone);
    }

    function initialReapDone() {
        takeLogs();
        assert.comment('- initialReapDone');

        // Verify that all alices are still connected
        checkAllExitPeers(cluster, assert, null);

        // Some of the peers re-register
        collectParallel(
            cluster.namedRemotes.slice(0, activeNum),
            function reregEach(alice, i, done) {
                cluster.sendRegister(alice.channel, {
                    serviceName: alice.serviceName
                }, done);
            },
            afterReRegister
        );
    }

    function afterReRegister(_, results) {
        takeLogs();
        assert.comment('- afterReRegister');

        var done = false;
        for (var i = 0; i < results.length; i++) {
            var res = results[i];
            done = done || !!res.err;
            assert.ifError(res.err, 'no unexpected error from rereg ' + i);
        }
        if (done) {
            assert.end();
            return;
        }

        reapClusterPears(cluster, assert, afterReapPeers);
    }

    function afterReapPeers() {
        takeLogs();
        assert.comment('- afterReapPeers');

        pruneClusterPears(cluster, assert, afterReapPrunePeers);
    }

    function afterReapPrunePeers() {
        takeLogs();
        assert.comment('- afterReapPrunePeers');

        checkAllExitPeers(cluster, assert, [
            // Some of the peers remain
            false,
            false,
            false,
            // Others not so much
            true,
            true,
            true,
            true
        ]);

        // But then everybody registers again!
        collectParallel(
            cluster.namedRemotes,
            function reregEach(alice, i, done) {
                cluster.sendRegister(alice.channel, {
                    serviceName: alice.serviceName
                }, done);
            },
            afterResurrection
        );
    }

    function afterResurrection(_, results) {
        takeLogs();
        assert.comment('- afterResurrection');

        var done = false;
        for (var i = 0; i < results.length; i++) {
            var res = results[i];
            done = done || !!res.err;
            assert.ifError(res.err, 'no unexpected error from resurrection ' + i);
        }
        if (done) {
            assert.end();
            return;
        }

        pruneClusterPears(cluster, assert, afterResPruneDone);
    }

    function afterResPruneDone() {
        takeLogs();
        assert.comment('- afterResPruneDone');

        // Verify that all the peers have rejoined the fray.
        checkAllExitPeers(cluster, assert, null);

        // And they all lived happily ever after.
        // The end.
        assert.end();

    }

    function takeLogs() {
        var logs = cluster.logger._backend.records.slice(0);
        cluster.logger._backend.records.length = 0;
        if (DUMP_LOGS) {
            logs2console(logs);
        }
        return logs;
    }
});

function logs2console(logs) {
    console.log(
        logs.map(function each(log) {
            var data = log._logData;
            return data.time + ' ' +
                data.level.toUpperCase() + ' ' +
                data.msg + ' ' +
                JSON.stringify(data.fields);
        }).join('\n')
    );
}

function reapClusterPears(cluster, assert, callback) {
    collectParallel(
        cluster.apps,
        function reapEach(app, i, done) {
            var serviceProxy = app.clients.serviceProxy;
            serviceProxy.peerReaper.run(done);
        },
        function finish(_, results) {
            for (var i = 0; i < results.length; i++) {
                var res = results[i];
                assert.ifError(res.err, 'no error from reaping app ' + i);
            }
            callback();
        }
    );
}

function pruneClusterPears(cluster, assert, callback) {
    collectParallel(
        cluster.apps,
        function pruneEach(app, i, done) {
            var serviceProxy = app.clients.serviceProxy;
            serviceProxy.peerPruner.run(done);
        },
        function finish(_, results) {
            for (var i = 0; i < results.length; i++) {
                var res = results[i];
                assert.ifError(res.err, 'no error from pruning app ' + i);
            }
            callback();
        }
    );
}

var getPeerInfo = require('../../peer-info.js');

function checkAllExitPeers(cluster, assert, isDead) {
    cluster.namedRemotes.forEach(function eachRemote(alice, i) {
        assert.comment('-- checkExitPeers for namedRemotes[' + i + ']');

        var app = cluster.apps[0];
        var exitShard = app.clients.egressNodes.exitsFor(alice.serviceName);
        var exitApps = cluster.apps.filter(function isExit(someApp) {
            return !!exitShard[someApp.tchannel.hostPort];
        });

        var peersInfo = {
            seenServiceName: {},
            numExistantPeers: 0,
            connected: {
                out: false,
                in: false
            }
        };

        exitApps.forEach(function anyAppPeerInfo(exitApp) {
            var peer = exitApp.tchannel.peers.get(alice.hostPort);
            if (!peer) {
                return;
            }
            peersInfo.numExistantPeers++;
            var peerInfo = getPeerInfo(peer);
            peerInfo.serviceNames.forEach(function eachServiceName(serviceName) {
                peersInfo.seenServiceName[serviceName] = true;
            });
            peersInfo.connected.out = peersInfo.connected.out || peerInfo.connected.out;
            peersInfo.connected.in = peersInfo.connected.in || peerInfo.connected.in;
        });
        peersInfo.serviceNames = Object.keys(peersInfo.seenServiceName);

        if (isDead && isDead[i]) {
            assert.equal(
                peersInfo.serviceNames.length, 0,
                'peer has no services');
        } else {
            assert.ok(peersInfo.numExistantPeers > 0,
                      'should have a peer on every exitApp');
            assert.ok(
                peersInfo.connected.out ||
                peersInfo.connected.in,
                'exitApp is connected to peer');
        }
    });
}
<commit_msg>test: remote-reaper, avoid race condition<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* eslint-disable no-console */
/* global console */

var allocCluster = require('../lib/test-cluster.js');
var collectParallel = require('collect-parallel/array');

var DUMP_LOGS = false;

allocCluster.test('dead exit peers get reaped', {
    size: 10,
    namedRemotes: ['alice', 'alice', 'alice', 'alice', 'alice', 'alice', 'alice'],
    whitelist: [
        // TODO: this is debt, this should not be an expected log; we should
        // understand and fix the cause of and need for this audit
        ['warn', 'partial affinity audit fail'],

        ['info', 'implementing affinity change'],
        ['info', 'pruning ex-affinity peers'],
        ['info', 'draining ex-affinity peer'],
        ['info', 'draining peer'],
        ['info', 'stopping peer drain'],
        ['info', 'Refreshing service peer affinity'],
        ['info', 'reaping dead peers'],
        ['info', 'reaping dead peer'],
        ['info', 'pruning peers'],
        ['info', 'draining pruned peer'],
        ['info', 'refreshed peer partially']
    ]
}, function t(cluster, assert) {
    var activeNum = 3;

    // for more determinism
    cluster.namedRemotes.sort(function byHostPort(a, b) {
        if (a.hostPort < b.hostPort) {
            return -1;
        } else if (a.hostPort > b.hostPort) {
            return 1;
        }
        return 0;
    });

    pruneClusterPears(cluster, assert, initialPruneDone);

    function initialPruneDone() {
        takeLogs();
        assert.comment('- initialPruneDone');

        // Verify that hyperban is connected to all the alices
        checkAllExitPeers(cluster, assert, null);

        // Reap peers that have not registered (nobody)
        reapClusterPears(cluster, assert, initialReapDone);
    }

    function initialReapDone() {
        takeLogs();
        assert.comment('- initialReapDone');

        // Verify that all alices are still connected
        checkAllExitPeers(cluster, assert, null);

        // Some of the peers re-register
        collectParallel(
            cluster.namedRemotes.slice(0, activeNum),
            function reregEach(alice, i, done) {
                cluster.sendRegister(alice.channel, {
                    serviceName: alice.serviceName
                }, done);
            },
            afterReRegister
        );
    }

    function afterReRegister(_, results) {
        takeLogs();
        assert.comment('- afterReRegister');

        var done = false;
        for (var i = 0; i < results.length; i++) {
            var res = results[i];
            done = done || !!res.err;
            assert.ifError(res.err, 'no unexpected error from rereg ' + i);
        }
        if (done) {
            assert.end();
            return;
        }

        reapClusterPears(cluster, assert, afterReapPeers);
    }

    function afterReapPeers() {
        takeLogs();
        assert.comment('- afterReapPeers');

        pruneClusterPears(cluster, assert, afterReapPrunePeers);
    }

    function afterReapPrunePeers() {
        takeLogs();
        assert.comment('- afterReapPrunePeers');

        checkAllExitPeers(cluster, assert, [
            // Some of the peers remain
            false,
            false,
            false,
            // Others not so much
            true,
            true,
            true,
            true
        ]);

        // But then everybody registers again!
        collectParallel(
            cluster.namedRemotes,
            function reregEach(alice, i, done) {
                cluster.sendRegister(alice.channel, {
                    serviceName: alice.serviceName
                }, done);
            },
            afterResurrection
        );
    }

    function afterResurrection(_, results) {
        takeLogs();
        assert.comment('- afterResurrection');

        var done = false;
        for (var i = 0; i < results.length; i++) {
            var res = results[i];
            done = done || !!res.err;

            // TODO: debug why this happens...
            if (res.err && res.err.type === 'tchannel.request.drained') {
                res.err = null;
            }

            assert.ifError(res.err, 'no unexpected error from resurrection ' + i);
        }
        if (done) {
            assert.end();
            return;
        }

        pruneClusterPears(cluster, assert, afterResPruneDone);
    }

    function afterResPruneDone() {
        takeLogs();
        assert.comment('- afterResPruneDone');

        // Verify that all the peers have rejoined the fray.
        checkAllExitPeers(cluster, assert, null);

        // And they all lived happily ever after.
        // The end.
        assert.end();

    }

    function takeLogs() {
        var logs = cluster.logger._backend.records.slice(0);
        cluster.logger._backend.records.length = 0;
        if (DUMP_LOGS) {
            logs2console(logs);
        }
        return logs;
    }
});

function logs2console(logs) {
    console.log(
        logs.map(function each(log) {
            var data = log._logData;
            return data.time + ' ' +
                data.level.toUpperCase() + ' ' +
                data.msg + ' ' +
                JSON.stringify(data.fields);
        }).join('\n')
    );
}

function reapClusterPears(cluster, assert, callback) {
    collectParallel(
        cluster.apps,
        function reapEach(app, i, done) {
            var serviceProxy = app.clients.serviceProxy;
            serviceProxy.peerReaper.run(done);
        },
        function finish(_, results) {
            for (var i = 0; i < results.length; i++) {
                var res = results[i];
                assert.ifError(res.err, 'no error from reaping app ' + i);
            }
            callback();
        }
    );
}

function pruneClusterPears(cluster, assert, callback) {
    collectParallel(
        cluster.apps,
        function pruneEach(app, i, done) {
            var serviceProxy = app.clients.serviceProxy;
            serviceProxy.peerPruner.run(done);
        },
        function finish(_, results) {
            for (var i = 0; i < results.length; i++) {
                var res = results[i];
                assert.ifError(res.err, 'no error from pruning app ' + i);
            }
            callback();
        }
    );
}

var getPeerInfo = require('../../peer-info.js');

function checkAllExitPeers(cluster, assert, isDead) {
    cluster.namedRemotes.forEach(function eachRemote(alice, i) {
        assert.comment('-- checkExitPeers for namedRemotes[' + i + ']');

        var app = cluster.apps[0];
        var exitShard = app.clients.egressNodes.exitsFor(alice.serviceName);
        var exitApps = cluster.apps.filter(function isExit(someApp) {
            return !!exitShard[someApp.tchannel.hostPort];
        });

        var peersInfo = {
            seenServiceName: {},
            numExistantPeers: 0,
            connected: {
                out: false,
                in: false
            }
        };

        exitApps.forEach(function anyAppPeerInfo(exitApp) {
            var peer = exitApp.tchannel.peers.get(alice.hostPort);
            if (!peer) {
                return;
            }
            peersInfo.numExistantPeers++;
            var peerInfo = getPeerInfo(peer);
            peerInfo.serviceNames.forEach(function eachServiceName(serviceName) {
                peersInfo.seenServiceName[serviceName] = true;
            });
            peersInfo.connected.out = peersInfo.connected.out || peerInfo.connected.out;
            peersInfo.connected.in = peersInfo.connected.in || peerInfo.connected.in;
        });
        peersInfo.serviceNames = Object.keys(peersInfo.seenServiceName);

        if (isDead && isDead[i]) {
            assert.equal(
                peersInfo.serviceNames.length, 0,
                'peer has no services');
        } else {
            assert.ok(peersInfo.numExistantPeers > 0,
                      'should have a peer on every exitApp');
            assert.ok(
                peersInfo.connected.out ||
                peersInfo.connected.in,
                'exitApp is connected to peer');
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>destrot keepAlive agent when finished<commit_after><|endoftext|>


<commit_before>
var AdminFilters = function(element, search_filters) {
    var $root = $(element);
    var $container = $('.filters', $root);
    var lastCount = 0;

    function addFilter(name, filter) {
        var $el = $('<tr />').appendTo($container);

        // Filter list
        $el.append(name);
    };

    $('a.filter').click(function() {
        var name = $(this).text().trim();
        alert(name);
        addFilter(name, search_filters[name]);

    });

};
<commit_msg>Update ab_filters.js<commit_after>var AdminFilters = function(element) {
    var $root = $(element);
    var $container = $('.filters', $root);
    var lastCount = 0;

    function addFilter(name, filter) {
        var $el = $('<tr />').appendTo($container);

        // Filter list
        $el.append(name);
    };

    $('a.filter').click(function() {
        var name = $(this).text().trim();
        alert(name);
        addFilter(name);

    });

};
<|endoftext|>


<commit_before>(function() {
    "use strict";

    angular.module('hippo.theme')

    /**
     * @ngdoc directive
     * @name hippo.theme.directive:selectBox
     * @restrict A
     *
     * @description
     * Converts a plain HTML select input field to a jQuery Chosen select box
     */
    .directive('hippo.theme.selectBox', [
        function() {
            return {
                restrict: 'A',
                link: function(scope, element) {
                    scope.$watch('options', function() {
                        element.trigger('chosen:updated');
                    });

                    element.chosen({
                        width: "100%"
                    });
                }
            };
        }
    ]);
}());<commit_msg>CMS7-7827 Add extra chosen event<commit_after>(function() {
    "use strict";

    angular.module('hippo.theme')

    /**
     * @ngdoc directive
     * @name hippo.theme.directive:selectBox
     * @restrict A
     *
     * @description
     * Converts a plain HTML select input field to a jQuery Chosen select box
     */
    .directive('hippo.theme.selectBox', [
        function() {
            return {
                restrict: 'A',
                link: function(scope, element) {
                    scope.$watch('options', function() {
                        element.trigger('chosen:updated');
                        element.trigger('chosen:updated.chosen');
                    });

                    element.chosen({
                        width: "100%"
                    });
                }
            };
        }
    ]);
}());<|endoftext|>


<commit_before>import React from 'react';

export const renderLetterHistory = diaryCode => {
  switch (diaryCode) {
    case '100':
    case '101':
    case '102':
    case '109':
      return (
        <>

            First demand letter

            A letter was sent to notify you of your debt and provide information
            on how to resolve it.

        </>
      );
    case '117':
      return (
        <>

            Second demand letter

            A letter was sent to inform you that failure to pay or contact the
            DMC within 60 days would result in the debt being reported to Credit
            Reporting Agencies.

        </>
      );
    case '123':
      return (
        <>

            Third demand letter

            A letter was sent to inform you that failure to pay or contact the
            DMC within 30 days would result in the debt being referred to the
            Department of Treasury for collection. This referral could result in
            your state or federal payments being withheld.

        </>
      );
    case '130':
      return (
        <>

            Debt increase letter

            A letter was sent to inform you that your debt’s balance has
            increased due to additional benefit over payments being made to you.

        </>
      );
    default:
      return null;
  }
};
<commit_msg>[CDP] 43979 - Fixing debt letter table formatting #21740<commit_after>import React from 'react';

export const renderLetterHistory = diaryCode => {
  switch (diaryCode) {
    case '100':
    case '101':
    case '102':
    case '109':
      return (
        <>

            First demand letter

            A letter was sent to notify you of your debt and provide information
            on how to resolve it.

        </>
      );
    case '117':
      return (
        <>

            Second demand letter

            A letter was sent to inform you that failure to pay or contact the
            DMC within 60 days would result in the debt being reported to Credit
            Reporting Agencies.

        </>
      );
    case '123':
      return (
        <>

            Third demand letter

            A letter was sent to inform you that failure to pay or contact the
            DMC within 30 days would result in the debt being referred to the
            Department of Treasury for collection. This referral could result in
            your state or federal payments being withheld.

        </>
      );
    case '130':
      return (
        <>

            Debt increase letter

            A letter was sent to inform you that your debt’s balance has
            increased due to additional benefit over payments being made to you.

        </>
      );
    default:
      return null;
  }
};
<|endoftext|>


<commit_before>/* global describe, it, beforeEach */

const Brave = require('../lib/brave')
const {urlInput, addFundsButton, paymentsStatus, paymentsWelcomePage, paymentsTab, walletSwitch} = require('../lib/selectors')
const assert = require('assert')

const prefsUrl = 'about:preferences'

describe('Payments Panel', function () {
  function * setup (client) {
    yield client
      .waitUntilWindowLoaded()
      .waitForUrl(Brave.newTabUrl)
      .waitForBrowserWindow()
      .waitForVisible('#window')
      .waitForVisible(urlInput)
  }

  describe('can setup payments', function () {
    Brave.beforeEach(this)
    beforeEach(function * () {
      yield setup(this.app.client)
    })

    it('shows welcome page', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
      let background = yield this.app.client.getCssProperty(walletSwitch, 'background-color')
      assert.equal(background.value, 'rgba(211,211,211,1)')
    })

    it('payments can be enabled', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === true &&
              val.value.settings['payments.notifications'] === true
          })
        })
    })

    it('payments can be disabled', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === true &&
              val.value.settings['payments.notifications'] === true
          })
        })
        .tabByUrl(prefsUrl)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === false &&
              val.value.settings['payments.notifications'] === false
          })
        })
    })

    it('can create wallet', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .waitUntil(function () {
          return this.getText(paymentsStatus).then((val) => val.includes('Creating'))
        })
        .waitUntil(function () {
          // Note: wallet creation may take a long time, so this test is likely
          // to time out.
          return this.getText(addFundsButton).then((val) => val.includes('Add funds'))
        })
    })
  })
})
<commit_msg>add ledger synopsis test<commit_after>/* global describe, it, beforeEach, before */

const Brave = require('../lib/brave')
const {urlInput, addFundsButton, paymentsStatus, paymentsWelcomePage, paymentsTab, walletSwitch, ledgerTable} = require('../lib/selectors')
const assert = require('assert')

const prefsUrl = 'about:preferences'

function * setup (client) {
  yield client
    .waitUntilWindowLoaded()
    .waitForUrl(Brave.newTabUrl)
    .waitForBrowserWindow()
    .waitForVisible('#window')
    .waitForVisible(urlInput)
}

describe('Payments Panel', function () {
  describe('can setup payments', function () {
    Brave.beforeEach(this)
    beforeEach(function * () {
      yield setup(this.app.client)
    })

    it('shows welcome page', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
      let background = yield this.app.client.getCssProperty(walletSwitch, 'background-color')
      assert.equal(background.value, 'rgba(211,211,211,1)')
    })

    it('payments can be enabled', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === true &&
              val.value.settings['payments.notifications'] === true
          })
        })
    })

    it('payments can be disabled', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === true &&
              val.value.settings['payments.notifications'] === true
          })
        })
        .tabByUrl(prefsUrl)
        .click(walletSwitch)
        .windowByUrl(Brave.browserWindowUrl)
        .waitUntil(function () {
          return this.getAppState().then((val) => {
            return val.value.settings['payments.enabled'] === false &&
              val.value.settings['payments.notifications'] === false
          })
        })
    })

    it('can create wallet', function * () {
      yield this.app.client
        .tabByIndex(0)
        .loadUrl(prefsUrl)
        .waitForVisible(paymentsTab)
        .click(paymentsTab)
        .waitForVisible(paymentsWelcomePage)
        .click(walletSwitch)
        .waitUntil(function () {
          return this.getText(paymentsStatus).then((val) => val.includes('Creating'))
        })
        .waitUntil(function () {
          // Note: wallet creation may take a long time, so this test is likely
          // to time out.
          return this.getText(addFundsButton).then((val) => val.includes('Add funds'))
        })
    })
  })
})

describe('synopsis', function () {
  function * newFrame (client, frameKey = 2) {
    yield client
      .ipcSend('shortcut-new-frame')
      // wait for correct urlInput based on frameKey
      .waitUntil(function () {
        return this.getTabCount().then((count) => {
          return count === frameKey
        })
      })
      .windowByUrl(Brave.browserWindowUrl)
      .waitForVisible('div[id="navigator"][data-frame-key="' + frameKey + '"] ' + urlInput)
      .waitForElementFocus(urlInput)
  }

  Brave.beforeAll(this)

  before(function * () {
    yield setup(this.app.client)
    yield this.app.client
      .tabByIndex(0)
      .loadUrl(prefsUrl)
      .waitForVisible(paymentsTab)
      .click(paymentsTab)
      .waitForVisible(paymentsWelcomePage)
      .click(walletSwitch)
      .waitUntil(function () {
        return this.getText(paymentsStatus).then((val) => val.includes('Creating'))
      })
      .waitUntil(function () {
        return this.getText(addFundsButton).then((val) => val.includes('Add funds'))
      })
  })

  it('no table if empty synopsis', function * () {
    yield this.app.client
      .isExisting(ledgerTable).then((isExisting) => isExisting === false)
  })

  it.skip('creates synopsis table after visiting a site', function * () {
    // TODO (mrose17): re-enable this test once ledger properly ignores the 8
    // second pageview limit during tests
    yield this.app.client
      .url('http://web.mit.edu/zyan/Public/wait.html')
      .waitUntil(function () {
        return this.getText('div').then((val) => val === 'done')
      })
      .windowByUrl(Brave.browserWindowUrl)
    yield newFrame(this.app.client)
    yield this.app.client
      .tabByUrl(Brave.newTabUrl)
      .loadUrl(prefsUrl)
      .waitForVisible(paymentsTab)
      .click(paymentsTab)
      .waitForExist(ledgerTable)
      .then((isExisting) => isExisting === true)
  })
})
<|endoftext|>


<commit_before>/*jshint node:true, maxlen:80, curly: true, eqeqeq: true, immed: true,
 latedef: true, newcap: true, noarg: true, sub: true, undef: true,
 eqnull: true, laxcomma: true, indent: 2, white:true */
 /*global describe:true, it:true, before:true, beforeEach:true */
"use strict";

// # Tests for concept-network-state module

// ## Required libraries
var assert = require('assert');

// Module to test
var ConceptNetwork = require('../lib/concept-network').ConceptNetwork;
var ConceptNetworkState = require('../lib/concept-network-state')
                          .ConceptNetworkState;

// ## ConceptNetwork
describe('ConceptNetworkState', function () {
  // ### Constructor
  describe('#Constructor', function () {

    it('should throw an exception if no ConceptNetwork is given', function () {
      assert.throws(function () {
        var cns = new ConceptNetworkState();
      },
      Error);
    });

    it('should not throw an exception', function () {
      assert.doesNotThrow(function () {
        var cn = new ConceptNetwork();
        var cns = new ConceptNetworkState(cn);
      }, null, "unexpected error");
    });

  });

  describe('#activate', function () {

    var cn, cns, node1;
    before(function () {
      cn = new ConceptNetwork();
      cns = new ConceptNetworkState(cn);
      node1 = cn.addNode("Node 1");
    });

    it('should put the node activation to 100', function () {
      cns.activate(node1.id);
      assert.equal(cns.nodeState[node1.id].activationValue, 100);
    });

  });

  describe('#getters', function () {

    var cn, cns, node1, node2;

    describe('##getActivationValue', function () {

      before(function () {
        cn = new ConceptNetwork();
        cns = new ConceptNetworkState(cn);
        node1 = cn.addNode("Node 1");
        node2 = cn.addNode("Node 2");
        cns.activate(node1.id);
      });

      it('should get a zero activation value', function () {
        assert.deepEqual(cns.getActivationValue(node2.id), 0);
      });

      it('should get a 100 activation value', function () {
        assert.deepEqual(cns.getActivationValue(node1.id), 100);
      });
    });

    describe('##getOldActivationValue', function () {

      before(function () {
        cn = new ConceptNetwork();
        cns = new ConceptNetworkState(cn);
        node1 = cn.addNode("Node 1");
        node2 = cn.addNode("Node 2");
        cns.activate(node1.id);
        cns.propagate();
      });

      it('should get a zero activation value', function () {
        assert.deepEqual(cns.getOldActivationValue(node2.id), 0);
      });

      it('should get a 100 activation value', function () {
        console.log(cns.nodeState);
        assert.deepEqual(cns.getOldActivationValue(node1.id), 100);
      });
    });

  });

  describe('#propagate', function () {

    var cn, cns, node1;
    before(function () {
      cn = new ConceptNetwork();
      cns = new ConceptNetworkState(cn);
      node1 = cn.addNode("Node 1");
    });

    it('should deactivate node without afferent links', function () {
      cns.activate(node1.id);
      assert.equal(cns.activationValue[node1.id], 100);
      cns.propagate();
      assert.equal(cns.activationValue[node1.id] < 100, true);
    });

  });

});
<commit_msg>Fix test of propagate.<commit_after>/*jshint node:true, maxlen:80, curly: true, eqeqeq: true, immed: true,
 latedef: true, newcap: true, noarg: true, sub: true, undef: true,
 eqnull: true, laxcomma: true, indent: 2, white:true */
 /*global describe:true, it:true, before:true, beforeEach:true */
"use strict";

// # Tests for concept-network-state module

// ## Required libraries
var assert = require('assert');

// Module to test
var ConceptNetwork = require('../lib/concept-network').ConceptNetwork;
var ConceptNetworkState = require('../lib/concept-network-state')
                          .ConceptNetworkState;

// ## ConceptNetwork
describe('ConceptNetworkState', function () {
  // ### Constructor
  describe('#Constructor', function () {

    it('should throw an exception if no ConceptNetwork is given', function () {
      assert.throws(function () {
        var cns = new ConceptNetworkState();
      },
      Error);
    });

    it('should not throw an exception', function () {
      assert.doesNotThrow(function () {
        var cn = new ConceptNetwork();
        var cns = new ConceptNetworkState(cn);
      }, null, "unexpected error");
    });

  });

  describe('#activate', function () {

    var cn, cns, node1;
    before(function () {
      cn = new ConceptNetwork();
      cns = new ConceptNetworkState(cn);
      node1 = cn.addNode("Node 1");
    });

    it('should put the node activation to 100', function () {
      cns.activate(node1.id);
      assert.equal(cns.nodeState[node1.id].activationValue, 100);
    });

  });

  describe('#getters', function () {

    var cn, cns, node1, node2;

    describe('##getActivationValue', function () {

      before(function () {
        cn = new ConceptNetwork();
        cns = new ConceptNetworkState(cn);
        node1 = cn.addNode("Node 1");
        node2 = cn.addNode("Node 2");
        cns.activate(node1.id);
      });

      it('should get a zero activation value', function () {
        assert.deepEqual(cns.getActivationValue(node2.id), 0);
      });

      it('should get a 100 activation value', function () {
        assert.deepEqual(cns.getActivationValue(node1.id), 100);
      });
    });

    describe('##getOldActivationValue', function () {

      before(function () {
        cn = new ConceptNetwork();
        cns = new ConceptNetworkState(cn);
        node1 = cn.addNode("Node 1");
        node2 = cn.addNode("Node 2");
        cns.activate(node1.id);
        cns.propagate();
      });

      it('should get a zero activation value', function () {
        assert.deepEqual(cns.getOldActivationValue(node2.id), 0);
      });

      it('should get a 100 activation value', function () {
        console.log(cns.nodeState);
        assert.deepEqual(cns.getOldActivationValue(node1.id), 100);
      });
    });

  });

  describe('#propagate', function () {

    var cn, cns, node1;
    before(function () {
      cn = new ConceptNetwork();
      cns = new ConceptNetworkState(cn);
      node1 = cn.addNode("Node 1");
    });

    it('should deactivate node without afferent links', function () {
      cns.activate(node1.id);
      assert.equal(cns.getActivationValue(node1.id), 100);
      cns.propagate();
      assert.equal(cns.getActivationValue(node1.id) < 100, true);
    });

  });

});
<|endoftext|>


<commit_before>$(document).ready(function(){
    $( document ).on( "click focused", "button.check_url_valid", function() {
        var btn = this;
        var url = $(this).parent().parent().find('input:first').val();
        var type = '';
        var attr = $(this).attr('url-type');
        var thisID = $(this).attr('id');
        var providerName = $(this).attr('providerName');
        var apiName = $(this).attr('apiName');
        var apiVersion = $(this).attr('apiVersion');
        if (attr) {
            type = $(btn).attr('url-type');
        } else {
            if (thisID == "prototype_test") {
                type = "http";
            }
            else {
            	if ($("#endpoint_config").val() && $("#endpoint_config").val() != "") {
            		type = $.parseJSON($("#endpoint_config").val())['endpoint_type'];
            	}
            }
        }
        if (!providerName && !apiName && !apiVersion) {
            providerName = "";
            apiName = "";
            apiVersion = "";
        }

        $(btn).parent().parent().parent().find('.url_validate_label').remove();
        $(btn).addClass("loadingButton-small");
        $(btn).val(i18n.t('Validating..'));

        if (url == '') {
        	$(btn).parent().parent().after('  '+ i18n.t('Please provide a URL to test.')+'');
            var toFade = $(btn).parent().parent().parent().find('.url_validate_label');
            $(btn).removeClass("loadingButton-small");
            $(btn).val(i18n.t('Test URI'));
            var foo = setTimeout(function(){$(toFade).hide()},3000);
            return;
        }
        if (!type) {
            type = "";
        }
        jagg.post("/site/blocks/item-add/ajax/add.jag", { action:"isURLValid", type:type, url:url, providerName:providerName, apiName:apiName, apiVersion:apiVersion },
                  function (result) {
                      if (!result.error) {
                          if (result.response.response == "success") {
                              $(btn).parent().parent().after('  ' + i18n.t('Valid') + '');

                          } else {
                              if (result.response.isConnectionError) {
                                if (result.response.response == null) {
                                    $(btn).parent().parent().after('  ' + i18n.t('Invalid') + i18n.t(' - Error connecting to backend') + '');
                                } else { //When an exception is thrown from jsFunction_isURLValid
                                    $(btn).parent().parent().after('  ' + i18n.t('Invalid') + '');
                                }
                              } else {
                                    if (result.response.statusCode == null) { //When an exception is thrown from sendHttpHEADRequest method
                                        $(btn).parent().parent().after('  ' + i18n.t('Invalid') + '. ' +  result.response.response + '');
                                    } else {
                                        if (result.response.isContainUriTemplatesOnly) {
                                            $(btn).parent().parent().after(' "> ' + i18n.t('Cannot test the endpoint provided. Please specify the full URL for testing.') + '');
                                        } else {
                                            $(btn).parent().parent().after('  ' + i18n.t('Warning') + '. ' + result.response.statusCode + ' - ' + result.response.reasonPhrase + '');
                                        }
                                    }
                              }

                          }
                          var toFade = $(btn).parent().parent().find('.url_validate_label');
                          var foo = setTimeout(function() {
                                $(toFade).hide();
                          }, 3000);
                      }else {
                          if (result.message == "timeout") {
                              jagg.showLogin();
                          }
                      }

                      $(btn).removeClass("loadingButton-small");
                      $(btn).val(i18n.t('Test URI'));
                  }, "json");

    });
});
<commit_msg>Removing dynamic text content from API endpoint URL validation response<commit_after>$(document).ready(function(){
    $( document ).on( "click focused", "button.check_url_valid", function() {
        var btn = this;
        var url = $(this).parent().parent().find('input:first').val();
        var type = '';
        var attr = $(this).attr('url-type');
        var thisID = $(this).attr('id');
        var providerName = $(this).attr('providerName');
        var apiName = $(this).attr('apiName');
        var apiVersion = $(this).attr('apiVersion');
        if (attr) {
            type = $(btn).attr('url-type');
        } else {
            if (thisID == "prototype_test") {
                type = "http";
            }
            else {
            	if ($("#endpoint_config").val() && $("#endpoint_config").val() != "") {
            		type = $.parseJSON($("#endpoint_config").val())['endpoint_type'];
            	}
            }
        }
        if (!providerName && !apiName && !apiVersion) {
            providerName = "";
            apiName = "";
            apiVersion = "";
        }

        $(btn).parent().parent().parent().find('.url_validate_label').remove();
        $(btn).addClass("loadingButton-small");
        $(btn).val(i18n.t('Validating..'));

        if (url == '') {
            $(btn).parent().parent().after(' ' +
                ' ' +
                ' ');
            jQuery( '.url_validate_message' ).text( i18n.t('Invalid') + '. ' +  result.response.response);
            var toFade = $(btn).parent().parent().parent().find('.url_validate_label');
            $(btn).removeClass("loadingButton-small");
            $(btn).val(i18n.t('Test URI'));
            var foo = setTimeout(function(){$(toFade).hide()},3000);
            return;
        }
        if (!type) {
            type = "";
        }
        jagg.post("/site/blocks/item-add/ajax/add.jag", { action:"isURLValid", type:type, url:url, providerName:providerName, apiName:apiName, apiVersion:apiVersion },
                  function (result) {
                      if (!result.error) {
                          if (result.response.response == "success") {
                              $(btn).parent().parent().after('  ' + i18n.t('Valid') + '');

                          } else {
                              if (result.response.isConnectionError) {
                                if (result.response.response == null) {
                                    $(btn).parent().parent().after('  ' + i18n.t('Invalid') + i18n.t(' - Error connecting to backend') + '');
                                } else { //When an exception is thrown from jsFunction_isURLValid
                                    $(btn).parent().parent().after('  ' + i18n.t('Invalid') + '');
                                }
                              } else {
                                    if (result.response.statusCode == null) { //When an exception is thrown from sendHttpHEADRequest method
                                        $(btn).parent().parent().after('  ' + i18n.t('Invalid') + '. ' +  result.response.response + '');
                                    } else {
                                        if (result.response.isContainUriTemplatesOnly) {
                                            $(btn).parent().parent().after(' "> ' + i18n.t('Cannot test the endpoint provided. Please specify the full URL for testing.') + '');
                                        } else {
                                            $(btn).parent().parent().after('  ' + i18n.t('Warning') + '. ' + result.response.statusCode + ' - ' + result.response.reasonPhrase + '');
                                        }
                                    }
                              }

                          }
                          var toFade = $(btn).parent().parent().find('.url_validate_label');
                          var foo = setTimeout(function() {
                                $(toFade).hide();
                          }, 3000);
                      }else {
                          if (result.message == "timeout") {
                              jagg.showLogin();
                          }
                      }

                      $(btn).removeClass("loadingButton-small");
                      $(btn).val(i18n.t('Test URI'));
                  }, "json");

    });
});
<|endoftext|>