<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const API_URL = process.env.API_URL = 'https://api-prj-1.bemoove.fr';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({
  env: ENV
}).metadata, {
  host: HOST,
  API_URL: API_URL,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = function (env) {
  return webpackMerge(commonConfig({
    env: ENV
  }), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },

    module: {

      rules: [

        /*
         * Extract CSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader'
          }),
          include: [helpers.root('src', 'styles')]
        },

        /*
         * Extract and compile SCSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader!sass-loader'
          }),
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      /**
       * Webpack plugin to optimize a JavaScript file for faster initial load
       * by wrapping eagerly-invoked functions.
       *
       * See: https://github.com/vigneshshanmugam/optimize-js-plugin
       */

      new OptimizeJsPlugin({
        sourceMap: false
      }),

      /**
       * Plugin: ExtractTextPlugin
       * Description: Extracts imported CSS files into external stylesheet
       *
       * See: https://github.com/webpack/extract-text-webpack-plugin
       */
      new ExtractTextPlugin('[name].[contenthash].css'),

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'API_URL' : JSON.stringify(METADATA.API_URL),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        output: {
          comments: false
        }, //prod
        mangle: {
          screw_ie8: true
        }, //prod
        compress: {
          screw_ie8: true,
          warnings: false,
          conditionals: true,
          unused: true,
          comparisons: true,
          sequences: true,
          dead_code: true,
          evaluate: true,
          if_return: true,
          join_vars: true,
          negate_iife: false // we need this for lazy v8
        },
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/empty.js')
      ),

      new NormalModuleReplacementPlugin(
        /zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
        helpers.root('config/empty.js')
      ),

      // AoT
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)upgrade/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)compiler/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)platform-browser-dynamic/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /dom(\\|\/)debug(\\|\/)ng_probe/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /dom(\\|\/)debug(\\|\/)by/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /src(\\|\/)debug(\\|\/)debug_node/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /src(\\|\/)debug(\\|\/)debug_renderer/,
      //   helpers.root('config/empty.js')
      // ),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        minimize: true,
        debug: false,
        options: {

          /**
           * Html loader advanced options
           *
           * See: https://github.com/webpack/html-loader#advanced-options
           */
          // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
          htmlLoader: {
            minimize: true,
            removeAttributeQuotes: false,
            caseSensitive: true,
            customAttrSurround: [
              [/#/, /(?:)/],
              [/\*/, /(?:)/],
              [/\[?\(?/, /(?:)/]
            ],
            customAttrAssign: [/\)?\]?=/]
          },

        }
      }),

      /**
       * Plugin: BundleAnalyzerPlugin
       * Description: Webpack plugin and CLI utility that represents
       * bundle content as convenient interactive zoomable treemap
       *
       * `npm run build:prod -- --env.analyze` to use
       *
       * See: https://github.com/th0r/webpack-bundle-analyzer
       */

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<commit_msg>Use beta API<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const API_URL = process.env.API_URL = 'https://api-beta.bemoove.fr';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({
  env: ENV
}).metadata, {
  host: HOST,
  API_URL: API_URL,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = function (env) {
  return webpackMerge(commonConfig({
    env: ENV
  }), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist-beta'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },

    module: {

      rules: [

        /*
         * Extract CSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader'
          }),
          include: [helpers.root('src', 'styles')]
        },

        /*
         * Extract and compile SCSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader!sass-loader'
          }),
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      /**
       * Webpack plugin to optimize a JavaScript file for faster initial load
       * by wrapping eagerly-invoked functions.
       *
       * See: https://github.com/vigneshshanmugam/optimize-js-plugin
       */

      new OptimizeJsPlugin({
        sourceMap: false
      }),

      /**
       * Plugin: ExtractTextPlugin
       * Description: Extracts imported CSS files into external stylesheet
       *
       * See: https://github.com/webpack/extract-text-webpack-plugin
       */
      new ExtractTextPlugin('[name].[contenthash].css'),

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'API_URL' : JSON.stringify(METADATA.API_URL),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        output: {
          comments: false
        }, //prod
        mangle: {
          screw_ie8: true
        }, //prod
        compress: {
          screw_ie8: true,
          warnings: false,
          conditionals: true,
          unused: true,
          comparisons: true,
          sequences: true,
          dead_code: true,
          evaluate: true,
          if_return: true,
          join_vars: true,
          negate_iife: false // we need this for lazy v8
        },
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/empty.js')
      ),

      new NormalModuleReplacementPlugin(
        /zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
        helpers.root('config/empty.js')
      ),

      // AoT
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)upgrade/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)compiler/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /@angular(\\|\/)platform-browser-dynamic/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /dom(\\|\/)debug(\\|\/)ng_probe/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /dom(\\|\/)debug(\\|\/)by/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /src(\\|\/)debug(\\|\/)debug_node/,
      //   helpers.root('config/empty.js')
      // ),
      // new NormalModuleReplacementPlugin(
      //   /src(\\|\/)debug(\\|\/)debug_renderer/,
      //   helpers.root('config/empty.js')
      // ),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        minimize: true,
        debug: false,
        options: {

          /**
           * Html loader advanced options
           *
           * See: https://github.com/webpack/html-loader#advanced-options
           */
          // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
          htmlLoader: {
            minimize: true,
            removeAttributeQuotes: false,
            caseSensitive: true,
            customAttrSurround: [
              [/#/, /(?:)/],
              [/\*/, /(?:)/],
              [/\[?\(?/, /(?:)/]
            ],
            customAttrAssign: [/\)?\]?=/]
          },

        }
      }),

      /**
       * Plugin: BundleAnalyzerPlugin
       * Description: Webpack plugin and CLI utility that represents
       * bundle content as convenient interactive zoomable treemap
       *
       * `npm run build:prod -- --env.analyze` to use
       *
       * See: https://github.com/th0r/webpack-bundle-analyzer
       */

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<|endoftext|>


<commit_before>jest.unmock('../lib/twilio-client')

var Bot = require('../lib/bot')
var TwilioClient = require('../lib/twilio-client')

var bot = new Bot()
var res = {
  send: jest.fn()
}

test('should use enviromental variables for sid, token and phone number', () => {

  process.env.TWILIO_ACCOUNT_SID = 'sid'
  process.env.TWILIO_AUTH_TOKEN = 'token'
  process.env.TWILIO_PHONE_NUMBER = 'number'

  var client = new TwilioClient(bot)

  expect(client.config.account_sid).toEqual('sid')
  expect(client.config.auth_token).toEqual('token')
  expect(client.config.phone_number).toEqual('number')

  process.env.TWILIO_ACCOUNT_SID = undefined
  process.env.TWILIO_AUTH_TOKEN = undefined
  process.env.TWILIO_PHONE_NUMBER = undefined
});

test('should use configuration object for key, secrets and tokens', () => {

  var config = {
    account_sid: 'sid',
    auth_token: 'token',
    phone_number: 'number'
  }

  var client = new TwilioClient(bot, config)

  expect(client.config.account_sid).toEqual('sid')
  expect(client.config.auth_token).toEqual('token')
  expect(client.config.phone_number).toEqual('number')
});

test('should listen for tweets mentioning the bot', () => {

  var handler = jest.fn()
  var originalImp = TwilioClient.prototype.createWebhookHandler
  TwilioClient.prototype.createWebhookHandler = function() {
    return handler
  }

  var client = new TwilioClient(bot)

  expect(bot.on).toBeCalledWith('webhook', handler)
  TwilioClient.prototype.createWebhookHandler = originalImp
});

test('should handle webhook with user agent TwilioProxy', () => {

  var next = jest.fn()
  var req = {
    headers: {
      'user-agent': 'TwilioProxy'
    }
  }
  var client = new TwilioClient(bot)

  client.createWebhookHandler()(req, res, next)

  expect(next).not.toBeCalled()
});

//       // If this isn't a twillio request then carry on with other handlers
//       if ( req.headers['user-agent'].indexOf('TwilioProxy') === -1 ) {
//         next()
//         return
//       }
//
//       var data = Object.assign({}, req.query, req.body)
//
//       var message = {
//         text: data.Body
//       }
//
//       var session = new Session(data.From, {}, this)
//
//       bot.trigger('message_received', message, session)
//       res.send({}) // We can't send a success code as twillio will send it

test('should send text when sending message', () => {

  var client = new TwilioClient(bot, {
    phone_number: '1'
  })

  client.send({
    user: '1'
  }, 'text')

  expect(client.twilio.sendMessage).toBeCalledWith({
      to: '1',
      from: '1',
      body: 'text'
  })
});
<commit_msg>Request simplify.<commit_after>jest.unmock('../lib/twilio-client')

var Bot = require('../lib/bot')
var TwilioClient = require('../lib/twilio-client')

var bot = new Bot()
var res = {
  send: jest.fn()
}
var req = {
  headers: {
    'user-agent': 'TwilioProxy'
  }
}

test('should use enviromental variables for sid, token and phone number', () => {

  process.env.TWILIO_ACCOUNT_SID = 'sid'
  process.env.TWILIO_AUTH_TOKEN = 'token'
  process.env.TWILIO_PHONE_NUMBER = 'number'

  var client = new TwilioClient(bot)

  expect(client.config.account_sid).toEqual('sid')
  expect(client.config.auth_token).toEqual('token')
  expect(client.config.phone_number).toEqual('number')

  process.env.TWILIO_ACCOUNT_SID = undefined
  process.env.TWILIO_AUTH_TOKEN = undefined
  process.env.TWILIO_PHONE_NUMBER = undefined
});

test('should use configuration object for key, secrets and tokens', () => {

  var config = {
    account_sid: 'sid',
    auth_token: 'token',
    phone_number: 'number'
  }

  var client = new TwilioClient(bot, config)

  expect(client.config.account_sid).toEqual('sid')
  expect(client.config.auth_token).toEqual('token')
  expect(client.config.phone_number).toEqual('number')
});

test('should listen for tweets mentioning the bot', () => {

  var handler = jest.fn()
  var originalImp = TwilioClient.prototype.createWebhookHandler
  TwilioClient.prototype.createWebhookHandler = function() {
    return handler
  }

  var client = new TwilioClient(bot)

  expect(bot.on).toBeCalledWith('webhook', handler)
  TwilioClient.prototype.createWebhookHandler = originalImp
});

test('should handle webhook with user agent TwilioProxy', () => {

  var next = jest.fn()
  var client = new TwilioClient(bot)

  client.createWebhookHandler()(req, res, next)

  expect(next).not.toBeCalled()
});

//
//       var data = Object.assign({}, req.query, req.body)
//
//       var message = {
//         text: data.Body
//       }
//
//       var session = new Session(data.From, {}, this)
//
//       bot.trigger('message_received', message, session)

test('should handle webhook with user agent TwilioProxy', () => {

  var next = jest.fn()
  var client = new TwilioClient(bot)

  client.createWebhookHandler()(req, res, next)

  expect(next).not.toBeCalled()
});

// return session

test('should handle webhook with user agent TwilioProxy', () => {

  var next = jest.fn()
  var client = new TwilioClient(bot)

  client.createWebhookHandler()(req, res, next)

  expect(next).not.toBeCalled()
});

test('should respond with empty json object for message', () => {

  var next = jest.fn()
  var client = new TwilioClient(bot)

  client.createWebhookHandler()(req, res, next)
  expect(res.send).toBeCalledWith({})
});

test('should send text when sending message', () => {

  var client = new TwilioClient(bot, {
    phone_number: '1'
  })

  client.send({
    user: '1'
  }, 'text')

  expect(client.twilio.sendMessage).toBeCalledWith({
      to: '1',
      from: '1',
      body: 'text'
  })
});
<|endoftext|>


<commit_before>/**
 * @file Accordion component
 */

import React, {Component, createRef, cloneElement} from 'react';
import PropTypes from 'prop-types';

// Components
import RaisedButton from '../RaisedButton';

// Statics
import Theme from '../Theme';

// Vendors
import classNames from 'classnames';
import ComponentUtil from '../_vendors/ComponentUtil';

class Accordion extends Component {

    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            collapsed: ComponentUtil.getDerivedState(props, state, 'collapsed')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.accordionContent = createRef();

        this.state = {
            collapsed: props.collapsed,
            contentHeight: null
        };

    }

    componentDidMount() {
        this.init();
    }

    /**
     * public
     */
    resetHeight = callback => {

        const el = this.accordionContent?.current;
        if (this.state.collapsed || !el) {
            return;
        }

        this.setState({
            contentHeight: 'auto'
        }, () => this.setState({
            contentHeight: el.offsetHeight
        }, () => {
            callback?.();
            this.props.onResetHeight?.(el.offsetHeight);
        }));

    };

    /**
     * public
     */
    collpase = () => {
        this.setState({
            collapsed: true
        }, () => {
            this.props.onCollpase?.();
            this.props.onChange?.(true);
        });
    };

    /**
     * public
     */
    expand = () => {
        this.setState({
            collapsed: false
        }, () => {
            this.props.onExpand?.();
            this.props.onChange?.(false);
        });
    };

    handleClick = () => {
        this.state.collapsed ?
            this.expand()
            :
            this.collpase();
    };

    init = () => {
        if (!this.props.collapsed) {
            this.resetHeight();
        } else {
            setTimeout(() => {
                this.setState({
                    collapsed: false
                }, () => {
                    this.resetHeight(() => {
                        this.setState({
                            collapsed: this.props.collapsed
                        });
                    });
                });
            }, 0);
        }
    };

    render() {

        const {children, className, style, title, collapseIcon, titleRenderer} = this.props,
            {collapsed, contentHeight} = this.state;

        return (

                {
                    titleRenderer ?
                        typeof titleRenderer === 'function' ?
                            titleRenderer(this.handleClick)
                            :
                            cloneElement(titleRenderer, {
                                onClick: this.handleClick
                            })
                        :
                        <RaisedButton className="accordion-title"
                                      theme={Theme.SECONDARY}
                                      value={title}
                                      rightIconCls={collapseIcon}
                                      onClick={this.handleClick}/>
                }

                    {children}

        );

    }
}

Accordion.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The accordion's title.
     */
    title: PropTypes.any,

    collapsed: PropTypes.bool,

    titleRenderer: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),

    /**
     * Collapse icon.
     */
    collapseIcon: PropTypes.string,

    /**
     * Callback function fired when collpase the accordion.
     */
    onCollpase: PropTypes.func,

    /**
     * Callback function fired when expand the accordion.
     */
    onExpand: PropTypes.func,

    /**
     * Callback function fired when change the status of accordion.
     */
    onChange: PropTypes.func,

    onResetHeight: PropTypes.func

};

Accordion.defaultProps = {
    title: 'title',
    collapsed: false,
    collapseIcon: 'fas fa-angle-down'
};

export default Accordion;
<commit_msg>update Accordion<commit_after>/**
 * @file Accordion component
 */

import React, {Component, createRef, cloneElement} from 'react';
import PropTypes from 'prop-types';

// Components
import RaisedButton from '../RaisedButton';

// Statics
import Theme from '../Theme';

// Vendors
import classNames from 'classnames';
import ComponentUtil from '../_vendors/ComponentUtil';

class Accordion extends Component {

    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            collapsed: ComponentUtil.getDerivedState(props, state, 'collapsed')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.accordionContent = createRef();

        this.state = {
            collapsed: props.collapsed,
            contentHeight: null
        };

    }

    componentDidMount() {
        this.init();
    }

    /**
     * public
     */
    resetHeight = callback => {

        const el = this.accordionContent?.current;
        if (this.state.collapsed || !el) {
            return;
        }

        this.setState({
            contentHeight: 'auto'
        }, () => this.setState({
            contentHeight: el.offsetHeight
        }, () => {
            callback?.();
            this.props.onResetHeight?.(el.offsetHeight);
        }));

    };

    /**
     * public
     */
    collpase = () => {
        this.setState({
            collapsed: true
        }, () => {
            this.props.onCollpase?.();
            this.props.onChange?.(true);
        });
    };

    /**
     * public
     */
    expand = () => {
        this.setState({
            collapsed: false
        }, () => {
            this.props.onExpand?.();
            this.props.onChange?.(false);
        });
    };

    handleClick = () => {
        this.state.collapsed ?
            this.expand()
            :
            this.collpase();
    };

    init = () => {
        if (!this.props.collapsed) {
            this.resetHeight();
        } else {
            setTimeout(() => {
                this.setState({
                    collapsed: false
                }, () => {
                    this.resetHeight(() => {
                        this.setState({
                            collapsed: this.props.collapsed
                        });
                    });
                });
            }, 0);
        }
    };

    render() {

        const {children, className, style, title, collapseIcon, titleRenderer} = this.props;
        const {collapsed, contentHeight} = this.state;

        return (

                {
                    titleRenderer ?
                        typeof titleRenderer === 'function' ?
                            titleRenderer(this.handleClick)
                            :
                            cloneElement(titleRenderer, {
                                onClick: this.handleClick
                            })
                        :
                        <RaisedButton className="accordion-title"
                                      theme={Theme.SECONDARY}
                                      value={title}
                                      rightIconCls={collapseIcon}
                                      onClick={this.handleClick}/>
                }

                    {children}

        );

    }
}

Accordion.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The accordion's title.
     */
    title: PropTypes.any,

    collapsed: PropTypes.bool,

    titleRenderer: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),

    /**
     * Collapse icon.
     */
    collapseIcon: PropTypes.string,

    /**
     * Callback function fired when collpase the accordion.
     */
    onCollpase: PropTypes.func,

    /**
     * Callback function fired when expand the accordion.
     */
    onExpand: PropTypes.func,

    /**
     * Callback function fired when change the status of accordion.
     */
    onChange: PropTypes.func,

    onResetHeight: PropTypes.func

};

Accordion.defaultProps = {
    title: 'title',
    collapsed: false,
    collapseIcon: 'fas fa-angle-down'
};

export default Accordion;
<|endoftext|>


<commit_before>// lib/localio.js

'use strict';

var os = require('os');
var ifaces = os.networkInterfaces();

function getLocalIpAdresses() {
    var result = [];

    Object.keys(ifaces).forEach(function (ifname) {
        var alias = 0;

        ifaces[ifname].forEach(function (iface) {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
                return;
            }

            if (alias >= 1) {
                // this single interface has multiple ipv4 addresses
                result.push(ifname + ':' + iface.address)
            } else {
                // this interface has only one ipv4 adress
                result.push(ifname + ' : ' + iface.address)
            }
            ++alias;
        });
    });

    return result;
}

exports.getLocalIpAdresses = getLocalIpAdresses;<commit_msg>another minor plotting change<commit_after>// lib/localio.js

'use strict';

var os = require('os');
var ifaces = os.networkInterfaces();

function getLocalIpAdresses() {
    var result = [];

    Object.keys(ifaces).forEach(function (ifname) {
        var alias = 0;

        ifaces[ifname].forEach(function (iface) {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
                return;
            }

            if (alias >= 1) {
                // this single interface has multiple ipv4 addresses
                result.push(ifname + ' : ' + iface.address)
            } else {
                // this interface has only one ipv4 adress
                result.push(ifname + ' : ' + iface.address)
            }
            ++alias;
        });
    });

    return result;
}

exports.getLocalIpAdresses = getLocalIpAdresses;<|endoftext|>


<commit_before>import {ChangeEmitter} from "../utils/ChangeEmitter.js";
import AppDispatcher from "../dispatcher/AppDispatcher.js";

import ContainerConstants from "../constants/ContainerConstants.js";
import SearchConstants from "../constants/SearchConstants.js";

var _defaultMode = ContainerConstants.ALL;

function setMode(m) {
  if (m === null) {
    m = _defaultMode;
  }
  localStorage.setItem("mode", m);
}

function mode() {
  var m = localStorage.getItem("mode");
  if (m === null) {
    m = _defaultMode;
  }
  return m;
}

var _titles = {};
_titles[ContainerConstants.ALL] = "Library";
_titles[ContainerConstants.RECENT] = "Recently Added";
_titles[ContainerConstants.RETRO] = "";

class ContainerStore extends ChangeEmitter {
  getMode() {
    return mode();
  }

  getTitle() {
    var m = mode();
    if (_titles.hasOwnProperty(m)) {
      return _titles[m];
    }
    return m.toLowerCase();
  }
}

var _containerStore = new ContainerStore();

_containerStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;
  var source = payload.source;

  if (source === "VIEW_ACTION") {
    switch (action.actionType) {
      case ContainerConstants.MODE:
        setMode(action.mode);
        _containerStore.emitChange();
        break;

      case SearchConstants.SEARCH:
        setMode(ContainerConstants.SEARCH);
        _containerStore.emitChange();
        break;
    }
  }
  return true;
});

export default _containerStore;
<commit_msg>Fix search performance.<commit_after>import {ChangeEmitter} from "../utils/ChangeEmitter.js";
import AppDispatcher from "../dispatcher/AppDispatcher.js";

import ContainerConstants from "../constants/ContainerConstants.js";
import SearchConstants from "../constants/SearchConstants.js";

var _defaultMode = ContainerConstants.ALL;

function setMode(m) {
  if (m === null) {
    m = _defaultMode;
  }
  localStorage.setItem("mode", m);
}

function mode() {
  var m = localStorage.getItem("mode");
  if (m === null) {
    m = _defaultMode;
  }
  return m;
}

var _titles = {};
_titles[ContainerConstants.ALL] = "Library";
_titles[ContainerConstants.RECENT] = "Recently Added";
_titles[ContainerConstants.RETRO] = "";

class ContainerStore extends ChangeEmitter {
  getMode() {
    return mode();
  }

  getTitle() {
    var m = mode();
    if (_titles.hasOwnProperty(m)) {
      return _titles[m];
    }
    return m.toLowerCase();
  }
}

var _containerStore = new ContainerStore();

_containerStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;
  var source = payload.source;

  if (source === "VIEW_ACTION") {
    switch (action.actionType) {
      case ContainerConstants.MODE:
        setMode(action.mode);
        _containerStore.emitChange();
        break;

      case SearchConstants.SEARCH:
        if (_containerStore.getMode() !== ContainerConstants.SEARCH) {
          setMode(ContainerConstants.SEARCH);
          _containerStore.emitChange();
        }
        break;
    }
  }
  return true;
});

export default _containerStore;
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars*/
/* eslint-disable no-trailing-spaces*/
/**
 * Class for Inverted Index.
 *
 * @class
 */
class InvertedIndexClass {
  /**
   * Class Instantiation.
   */
  constructor() {
    this.index = {};
    this.books = {};
    this.parsedBooks = {};
  }

  /**
   * create Index
   *
   * creates an index of words
   *
   * @param{string}  filename accepts a string name for a file;
   * @param{object} books is a json object for which an index is to be created
   * @returns{object};
   */
  createIndex(filename, books) {
    this.index[filename] = {};
    this.books = (books);
    let bookIndex;
    books.forEach((singleBook, inex) => {
      // console.log(singleBook);
      singleBook = `${singleBook.title} ${singleBook.text}`;
      singleBook = singleBook.toLowerCase().match(/[\w]+/g);
      bookIndex = inex;
      singleBook.forEach((term) => {
        if (this.index[filename][term] === undefined) {
          this.index[filename][term] = {};
          this.index[filename][term][bookIndex] = true;
        } else {
          this.index[filename][term][bookIndex] = true;
        }
      });
    });
    return this.index;
  }

  /**
   * returns created index
   *
   * @returns{object};
   */
  getIndex() {
    return this.index;
  }

  /**
   * Search Index
   *
   * Searches through the indexes for the specified search terms
   *
   * @param {string} filename
   * @param{string} terms
   * @return {Object} An Object Containing
   * the Various words and their Locations.
   */
  searchIndex(filename, ...terms) {
    let filesToSearch = [];
    const searchResult = {};
    if ((typeof (filename) === typeof []) &&
      (this.index[filename[0]])) {
      filesToSearch.push(filename[0]);
      terms.push(filename);
    } else if (this.index[filename] === undefined) {
      terms.push(filename);
      filesToSearch = filesToSearch.concat(Object.keys(this.index));
    } else {
      filesToSearch.push(filename);
    }
    filesToSearch.forEach((searchKey) => {
      searchResult[searchKey] = {};
      if (typeof (terms) === typeof []) {
        terms = terms.join();
      }
      terms = terms.toLowerCase().match(/[\w']+/g);
      for (let word = 0; word < terms.length; word += 1) {
        if (this.index[searchKey][terms[word]]) {
          searchResult[searchKey][terms[word]]
          = this.index[searchKey][terms[word]];
        }
      }
    });
    return searchResult;
  }

  /**
   * Valid Files
   *
   * Checks if the passed in JSON object is valid
   *
   * @param {object} jsonObj accepts a json file and checks if it is valid
   * @returns {array} returns an array, the first value being true or
   * false and the second value being an error message
   * test run
   */
  validFiles(jsonObj) {
    try {
      if (jsonObj.length === 0) {
        return [false, 'Error, empty file'];
      }
      this.parsedBooks = JSON.parse(jsonObj);
      const validityCheck = false;

      this.parsedBooks.forEach((entry) => {
        if (entry.title === undefined || entry.text === undefined) {
          throw new Error('Invalid Format');
        }
      });
      return [true, 'Success'];
    } catch (error) {
      if (error.message === 'Invalid Format') {
        return [false,
          'this Index takes books with Title and Text property only'
        ];
      } else if (error.name === 'SyntaxError') {
        return [false, 'Invalid JSON file'];
      }
    }
  }
}
<commit_msg>Defence notes<commit_after>/* eslint-disable no-unused-vars*/
/* eslint-disable no-trailing-spaces*/
/**
 * Class for Inverted Index.
 *
 * @class
 */
class InvertedIndexClass {
  /**
   * Class Instantiation.
   */
  constructor() {
    this.index = {};
    this.books = {};
    this.parsedBooks = {};
  }

  /**
   * create Index
   *
   * creates an index of words
   *
   * @param{string}  filename accepts a string name for a file;
   * @param{object} books is a json object for which an index is to be created
   * @returns{object};
   */
  createIndex(filename, books) {
    this.index[filename] = {};
    this.books = (books);
    let bookIndex;
    books.forEach((singleBook, inex) => {
      // console.log(singleBook);
      singleBook = `${singleBook.title} ${singleBook.text}`;
      singleBook = singleBook.toLowerCase().match(/[\w]+/g);
      bookIndex = inex;
      singleBook.forEach((term) => {
        if (this.index[filename][term] === undefined) {
          this.index[filename][term] = {};
          this.index[filename][term][bookIndex] = true;
        } else {
          this.index[filename][term][bookIndex] = true;
        }
      });
    });
    return this.index;
  }

  /**
   * returns created index
   *
   * @returns{object};
   */
  getIndex() {
    return this.index;
  }

  /**
   * Search Index
   *
   * Searches through the indexes for the specified search terms
   *
   * @param {string} filename
   * @param{string} terms
   * @return {Object} An Object Containing
   * the Various words and their Locations.
   */
  searchIndex(filename, ...terms) {
    let filesToSearch = [];
    const searchResult = {};
    if ((typeof (filename) === typeof []) &&
      (this.index[filename[0]])) {
      filesToSearch.push(filename[0]);
      terms.push(filename);
    } else if (this.index[filename] === undefined) {
      terms.push(filename);
      filesToSearch = filesToSearch.concat(Object.keys(this.index));
    } else {
      filesToSearch.push(filename);
    }
    filesToSearch.forEach((searchKey) => {
      searchResult[searchKey] = {};
      if (typeof (terms) === typeof []) {
        terms = terms.join();
      }
      terms = terms.toLowerCase().match(/[\w']+/g);
      for (let word = 0; word < terms.length; word += 1) {
        if (this.index[searchKey][terms[word]]) {
          searchResult[searchKey][terms[word]]
          = this.index[searchKey][terms[word]];
        }
      }
    });
    return searchResult;
  }

  /**
   * Valid Files
   *
   * Checks if the passed in JSON object is valid
   *
   * @param {object} jsonObj accepts a json file and checks if it is valid
   * @returns {array} returns an array, the first value being true or
   * false and the second value being an error message
   * test run
   */
  validFiles(jsonObj) {
    try {
      if (jsonObj.length === 0) {
        throw new Error('Error, empty file');
      }
      this.parsedBooks = JSON.parse(jsonObj);
      const validityCheck = false;
      this.parsedBooks.forEach((entry) => {
        if (entry.title === undefined || entry.text === undefined) {
          throw new Error('Invalid Format');
        }
      });
      return [true, 'Success'];
    } catch (error) {
      if (error.message === 'Invalid Format') {
        return [false,
          'this Index takes books with Title and Text property only'
        ];
      } else if (error.name === 'SyntaxError') {
        return [false, 'Invalid JSON file'];
      } else if (error.message === 'Error, empty file') {
        return [false, 'Error, empty file'];
      }
    }
  }
}
<|endoftext|>


<commit_before>// import {createCanvas, clearCanvas, square} from './graphics-handler.js';

export default class IsometricGrid {
  constructor () {
    const width = window.innerWidth
    const height = window.innerHeight

    const canvas = document.createElement('canvas')
    canvas.className = 'canvas'
    canvas.setAttribute('width', width)
    canvas.setAttribute('height', height)
    canvas.style.width = width + 'px'
    canvas.style.height = height + 'px'

    document.querySelector('.graphics-wrapper').appendChild(canvas)
    this.ctx = canvas.getContext('2d')
  }

  render () {
    this.renderUpwardDiagonals()
    this.renderDownwardDiagonals()
    this.renderVerticals()
  }

  renderUpwardDiagonals () {
    console.log('render upward diagonals')
  }

  renderDownwardDiagonals () {
    console.log('render downward diagonals')
  }

  renderVerticals () {
    console.log('render verticals')
  }
}
<commit_msg>Added first dimension of the isometric grid background<commit_after>// import {createCanvas, clearCanvas, square} from './graphics-handler.js';
const ALPHA = Math.tan(30 * Math.PI / 180)

export default class IsometricGrid {
  constructor () {
    const width = window.innerWidth
    const height = window.innerHeight

    const canvas = document.createElement('canvas')
    canvas.className = 'canvas'
    canvas.setAttribute('width', width)
    canvas.setAttribute('height', height)
    canvas.style.width = width + 'px'
    canvas.style.height = height + 'px'

    document.querySelector('.graphics-wrapper').appendChild(canvas)
    this.ctx = canvas.getContext('2d')
  }

  render () {
    this.renderUpwardDiagonals()
    this.renderDownwardDiagonals()
    this.renderVerticals()
  }

  renderUpwardDiagonals () {
    const screenWidth = window.innerWidth
    const screenHeight = window.innerHeight
    const zoom = 40
    var startX

    this.ctx.strokeStyle = '#ff0000'
    for (startX = -1 * screenWidth; startX < screenWidth; startX += zoom) {
      let width = screenWidth - startX
      this.ctx.beginPath()
      this.ctx.moveTo(startX, screenHeight)
      this.ctx.lineTo(screenWidth, screenHeight - (width * ALPHA))
      this.ctx.stroke()
    }
  }

  renderDownwardDiagonals () {
    console.log('render downward diagonals')
  }

  renderVerticals () {
    console.log('render verticals')
  }
}
<|endoftext|>


<commit_before>var five = require("johnny-five"),
    arDrone = require('ar-drone'),
    droneControl = arDrone.createUdpControl();

var ref = {fly: false}
var pcmd = {};

var speed = 0.2;

function takeoff() {
  console.log('taking off')
  ref.fly = true;
  ref.emergency = false;
}

function land() {
  console.log('landing')
  pcmd = {};
  ref.fly = false;
  ref.emergency = true;
}

function toggleFlying(){
  if(ref.fly){
    land()
  } else {
    takeoff()
  }
}

setInterval(function() {
  droneControl.ref(ref);
  droneControl.pcmd(pcmd);
  droneControl.flush();
}, 30);

var express = require('express');
var ejs = require ('ejs')
var app = express();

app.configure(function() {
  app.use(express.bodyParser());
  app.set('dirname', __dirname);
  app.use(app.router);
  app.use(express["static"](__dirname + "/public/"));
  app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
  return app.set('views', __dirname + "/views/");
});

app.get("/", function(req, res) {
  return res.render('index.ejs');
});

var port = process.env.PORT || 5200;
app.listen(port);
console.log("Listening on Port '" + port + "'");

var io = require('socket.io').listen(8001);

var leftY = rightY = leftZ = rightZ = 0;

var upperLimit = 30;
var lowerLimit = -30;

function move() {
  var left = leftY
  var right = rightY*-1

  // up
  if(left > upperLimit && right > upperLimit){
    command = 'up'
    pcmd.up = speed;
    pcmd.left = 0;
  }
  // down
  else if(left < lowerLimit && right < lowerLimit){
    command = 'down'
    pcmd.down = speed;
    pcmd.left = 0;
  }
  // left
  else if(left < lowerLimit && right > upperLimit){
    command = 'left'
    pcmd.up = 0;
    pcmd.left = speed;
  }
  // right
  else if(left > upperLimit && right < lowerLimit){
    command = 'right'
    pcmd.up = 0;
    pcmd.right = speed;
  }
  // hover
  else {
    command = 'hover'
    pcmd.down = 0;
    pcmd.left = 0;
  }
  io.sockets.emit('command', {command: command, left: left, right: right});
  moveZ()
}

var upperLimitZ = 35;
var lowerLimitZ = -15;

function moveZ(){
  var left = leftZ
  var right = rightZ

  // up
  if(left > upperLimitZ && right > upperLimitZ){
    command = 'forward'
    pcmd.front = speed;
    pcmd.clockwise = 0;
  }
  // down
  else if(left < lowerLimitZ && right < lowerLimitZ){
    command = 'back'
    pcmd.back = speed;
    pcmd.clockwise = 0;
  }
  // left
  else if(left < lowerLimitZ && right > upperLimitZ){
    command = 'clockwise'
    pcmd.front = 0;
    pcmd.clockwise = speed;
  }
  // right
  else if(left > upperLimitZ && right < lowerLimitZ){
    command = 'counterClockwise'
    pcmd.front = 0;
    pcmd.counterClockwise = speed;
  }
  // hover
  else {
    command = 'hover'
  }
  io.sockets.emit('commandZ', {command: command, left: left, right: right});
}

five.Board().on("ready", function(){
  var button = new five.Button(7);
  var leftYFlexSensor = new five.Sensor("A0");
  var rightYFlexSensor = new five.Sensor("A1");
  var leftZFlexSensor = new five.Sensor("A2");
  var rightZFlexSensor = new five.Sensor("A3");

  button.on("up", function() {
    // console.log("up");
    toggleFlying()
  });

  leftYFlexSensor.on("read", function(err, value){
    var a= five.Fn.map(value, 100, 500, -90, 90)
    leftY = five.Fn.constrain(a, -80, 80)
    io.sockets.emit('leftY', { angle: leftY, value: value });
    move()
  });
  rightYFlexSensor.on("read", function(err, value){
    var a = five.Fn.map(value, 400, 100, -90, 90)
    rightY = five.Fn.constrain(a, -80, 80)
    io.sockets.emit('rightY', { angle: rightY, value: value });
    move()
  });

  leftZFlexSensor.on("read", function(err, value){
    var a= five.Fn.map(value, 550, 330, -60, 60)
    leftZ = five.Fn.constrain(a, -60, 60)
    io.sockets.emit('leftZ', { angle: leftZ, value: value });
    move()
  });

  rightZFlexSensor.on("read", function(err, value){
    var a = five.Fn.map(value, 500, 200, -60, 60)
    rightZ = five.Fn.constrain(a, -60, 60)
    io.sockets.emit('rightZ', { angle: rightZ, value: value });
    move()
  });

});
<commit_msg>Have the node hoodie skip connecting to non arduino devices<commit_after>var five = require("johnny-five"),
    arDrone = require('ar-drone'),
    serialport = require('serialport'),
    droneControl = arDrone.createUdpControl();

var ref = {fly: false}
var pcmd = {};

var speed = 0.2;

function takeoff() {
  console.log('taking off')
  ref.fly = true;
  ref.emergency = false;
}

function land() {
  console.log('landing')
  pcmd = {};
  ref.fly = false;
  ref.emergency = true;
}

function toggleFlying(){
  if(ref.fly){
    land()
  } else {
    takeoff()
  }
}

setInterval(function() {
  droneControl.ref(ref);
  droneControl.pcmd(pcmd);
  droneControl.flush();
}, 30);

var express = require('express');
var ejs = require ('ejs')
var app = express();

app.configure(function() {
  app.use(express.bodyParser());
  app.set('dirname', __dirname);
  app.use(app.router);
  app.use(express["static"](__dirname + "/public/"));
  app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
  return app.set('views', __dirname + "/views/");
});

app.get("/", function(req, res) {
  return res.render('index.ejs');
});

var port = process.env.PORT || 5200;
app.listen(port);
console.log("Listening on Port '" + port + "'");

var io = require('socket.io').listen(8001);

var leftY = rightY = leftZ = rightZ = 0;

var upperLimit = 30;
var lowerLimit = -30;

function move() {
  var left = leftY
  var right = rightY*-1

  // up
  if(left > upperLimit && right > upperLimit){
    command = 'up'
    pcmd.up = speed;
    pcmd.left = 0;
  }
  // down
  else if(left < lowerLimit && right < lowerLimit){
    command = 'down'
    pcmd.down = speed;
    pcmd.left = 0;
  }
  // left
  else if(left < lowerLimit && right > upperLimit){
    command = 'left'
    pcmd.up = 0;
    pcmd.left = speed;
  }
  // right
  else if(left > upperLimit && right < lowerLimit){
    command = 'right'
    pcmd.up = 0;
    pcmd.right = speed;
  }
  // hover
  else {
    command = 'hover'
    pcmd.down = 0;
    pcmd.left = 0;
  }
  io.sockets.emit('command', {command: command, left: left, right: right});
  moveZ()
}

var upperLimitZ = 35;
var lowerLimitZ = -15;

function moveZ(){
  var left = leftZ
  var right = rightZ

  // up
  if(left > upperLimitZ && right > upperLimitZ){
    command = 'forward'
    pcmd.front = speed;
    pcmd.clockwise = 0;
  }
  // down
  else if(left < lowerLimitZ && right < lowerLimitZ){
    command = 'back'
    pcmd.back = speed;
    pcmd.clockwise = 0;
  }
  // left
  else if(left < lowerLimitZ && right > upperLimitZ){
    command = 'clockwise'
    pcmd.front = 0;
    pcmd.clockwise = speed;
  }
  // right
  else if(left > upperLimitZ && right < lowerLimitZ){
    command = 'counterClockwise'
    pcmd.front = 0;
    pcmd.counterClockwise = speed;
  }
  // hover
  else {
    command = 'hover'
  }
  io.sockets.emit('commandZ', {command: command, left: left, right: right});
}

var onReady = function(){
  console.log("ready to robot");
  var button = new five.Button(7);
  var leftYFlexSensor = new five.Sensor("A0");
  var rightYFlexSensor = new five.Sensor("A1");
  var leftZFlexSensor = new five.Sensor("A2");
  var rightZFlexSensor = new five.Sensor("A3");

  button.on("up", function() {
    // console.log("up");
    toggleFlying();
  });

  leftYFlexSensor.on("read", function(err, value){
    var a= five.Fn.map(value, 100, 500, -90, 90);
    leftY = five.Fn.constrain(a, -80, 80);
    io.sockets.emit('leftY', { angle: leftY, value: value });
    move();
  });
  rightYFlexSensor.on("read", function(err, value){
    var a = five.Fn.map(value, 400, 100, -90, 90);
    rightY = five.Fn.constrain(a, -80, 80);
    io.sockets.emit('rightY', { angle: rightY, value: value });
    move();
  });

  leftZFlexSensor.on("read", function(err, value){
    var a= five.Fn.map(value, 550, 330, -60, 60);
    leftZ = five.Fn.constrain(a, -60, 60);
    io.sockets.emit('leftZ', { angle: leftZ, value: value });
    move();
  });

  rightZFlexSensor.on("read", function(err, value){
    var a = five.Fn.map(value, 500, 200, -60, 60);
    rightZ = five.Fn.constrain(a, -60, 60);
    io.sockets.emit('rightZ', { angle: rightZ, value: value });
    move();
  });

};

var board;
serialport.list(function(err, ports){
  ports = ports.filter(function(port){
    return port.manufacturer.match(/arduino/i);
  });
  console.log(ports);

  var arduino = ports.shift().comName;
  console.log("connecting to " + arduino);
  board = new five.Board({
    port: arduino,
    repl: false,
    debug: true
  });
  board.on("ready", onReady);
});
<|endoftext|>


<commit_before>/*
 * jQuery Shorten plugin 1.1.0
 *
 * Copyright (c) 2014 Viral Patel
 * http://viralpatel.net
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

/*
** updated by Jeff Richardson
** Updated to use strict,
** IE 7 has a "bug" It is returning underfined when trying to reference string characters in this format
** content[i]. IE 7 allows content.charAt(i) This works fine in all modern browsers.
** I've also added brackets where they werent added just for readability (mostly for me).
*/

(function($) {
    $.fn.shorten = function(settings) {
        "use strict";

        var config = {
            showChars: 100,
            ellipsesText: "...",
            moreText: "more",
            lessText: "less",
            errMsg: null,
            force: false
        };

        if (settings) {
            $.extend(config, settings);
        }

        if ($(this).data('jquery.shorten') && !config.force) {
            return false;
        }
        $(this).data('jquery.shorten', true);

        $(document).off("click", '.morelink');

        $(document).on({
            click: function() {

                var $this = $(this);
                if ($this.hasClass('less')) {
                    $this.removeClass('less');
                    $this.html(config.moreText);
                    $this.parent().prev().prev().show(); // shortcontent
                    $this.parent().prev().hide(); // allcontent

                } else {
                    $this.addClass('less');
                    $this.html(config.lessText);
                    $this.parent().prev().prev().hide(); // shortcontent
                    $this.parent().prev().show(); // allcontent
                }
                return false;
            }
        }, '.morelink');

        return this.each(function() {
            var $this = $(this);

            var content = $this.html();
            var contentlen = $this.text().length;
            if (contentlen > config.showChars) {
                var c = content.substr(0, config.showChars);
                if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it
                {
                    var inTag = false; // I'm in a tag?
                    var bag = ''; // Put the characters to be shown here
                    var countChars = 0; // Current bag size
                    var openTags = []; // Stack for opened tags, so I can close them later
                    var tagName = null;

                    for (var i = 0, r = 0; r <= config.showChars; i++) {
                        if (content[i] == '<' && !inTag) {
                            inTag = true;

                            // This could be "tag" or "/tag"
                            tagName = content.substring(i + 1, content.indexOf('>', i));

                            // If its a closing tag
                            if (tagName[0] == '/') {

                                if (tagName != '/' + openTags[0]) {
                                    config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes';
                                } else {
                                    openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!)
                                }

                            } else {
                                // There are some nasty tags that don't have a close tag like

                                if (tagName.toLowerCase() != 'br') {
                                    openTags.unshift(tagName); // Add to start the name of the tag that opens
                                }
                            }
                        }
                        if (inTag && content[i] == '>') {
                            inTag = false;
                        }

                        if (inTag) { bag += content.charAt(i); } // Add tag name chars to the result
                        else {
                            r++;
                            if (countChars <= config.showChars) {
                                bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the []
                                countChars++;
                            } else // Now I have the characters needed
                            {
                                if (openTags.length > 0) // I have unclosed tags
                                {
                                    //console.log('They were open tags');
                                    //console.log(openTags);
                                    for (j = 0; j < openTags.length; j++) {
                                        //console.log('Cierro tag ' + openTags[j]);
                                        bag += '</' + openTags[j] + '>'; // Close all tags that were opened

                                        // You could shift the tag from the stack to check if you end with an empty stack, that means you have closed all open tags
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    c = $('
').html(bag + '' + config.ellipsesText + '').html();
                }

                var html = '
' + c +
                    '

' + content +
                    '
' + config.moreText + '';

                $this.html(html);
                $this.find(".allcontent").hide(); // Hide all text
                $('.shortcontent p:last', $this).css('margin-bottom', 0); //Remove bottom margin on last paragraph as it's likely shortened
            }
        });

    };

})(jQuery);
<commit_msg>Don't ignoring "ellipsesText" in text plain<commit_after>/*
 * jQuery Shorten plugin 1.1.0
 *
 * Copyright (c) 2014 Viral Patel
 * http://viralpatel.net
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

/*
** updated by Jeff Richardson
** Updated to use strict,
** IE 7 has a "bug" It is returning underfined when trying to reference string characters in this format
** content[i]. IE 7 allows content.charAt(i) This works fine in all modern browsers.
** I've also added brackets where they werent added just for readability (mostly for me).
*/

(function($) {
    $.fn.shorten = function(settings) {
        "use strict";

        var config = {
            showChars: 100,
            ellipsesText: "...",
            moreText: "more",
            lessText: "less",
            errMsg: null,
            force: false
        };

        if (settings) {
            $.extend(config, settings);
        }

        if ($(this).data('jquery.shorten') && !config.force) {
            return false;
        }
        $(this).data('jquery.shorten', true);

        $(document).off("click", '.morelink');

        $(document).on({
            click: function() {

                var $this = $(this);
                if ($this.hasClass('less')) {
                    $this.removeClass('less');
                    $this.html(config.moreText);
                    $this.parent().prev().prev().show(); // shortcontent
                    $this.parent().prev().hide(); // allcontent

                } else {
                    $this.addClass('less');
                    $this.html(config.lessText);
                    $this.parent().prev().prev().hide(); // shortcontent
                    $this.parent().prev().show(); // allcontent
                }
                return false;
            }
        }, '.morelink');

        return this.each(function() {
            var $this = $(this);

            var content = $this.html();
            var contentlen = $this.text().length;
            if (contentlen > config.showChars) {
                var c = content.substr(0, config.showChars);
                if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it
                {
                    var inTag = false; // I'm in a tag?
                    var bag = ''; // Put the characters to be shown here
                    var countChars = 0; // Current bag size
                    var openTags = []; // Stack for opened tags, so I can close them later
                    var tagName = null;

                    for (var i = 0, r = 0; r <= config.showChars; i++) {
                        if (content[i] == '<' && !inTag) {
                            inTag = true;

                            // This could be "tag" or "/tag"
                            tagName = content.substring(i + 1, content.indexOf('>', i));

                            // If its a closing tag
                            if (tagName[0] == '/') {

                                if (tagName != '/' + openTags[0]) {
                                    config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes';
                                } else {
                                    openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!)
                                }

                            } else {
                                // There are some nasty tags that don't have a close tag like

                                if (tagName.toLowerCase() != 'br') {
                                    openTags.unshift(tagName); // Add to start the name of the tag that opens
                                }
                            }
                        }
                        if (inTag && content[i] == '>') {
                            inTag = false;
                        }

                        if (inTag) { bag += content.charAt(i); } // Add tag name chars to the result
                        else {
                            r++;
                            if (countChars <= config.showChars) {
                                bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the []
                                countChars++;
                            } else // Now I have the characters needed
                            {
                                if (openTags.length > 0) // I have unclosed tags
                                {
                                    //console.log('They were open tags');
                                    //console.log(openTags);
                                    for (j = 0; j < openTags.length; j++) {
                                        //console.log('Cierro tag ' + openTags[j]);
                                        bag += '</' + openTags[j] + '>'; // Close all tags that were opened

                                        // You could shift the tag from the stack to check if you end with an empty stack, that means you have closed all open tags
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    c = $('
').html(bag + '' + config.ellipsesText + '').html();
                }else{
                    c+=config.ellipsesText;
                }

                var html = '
' + c +
                    '

' + content +
                    '
' + config.moreText + '';

                $this.html(html);
                $this.find(".allcontent").hide(); // Hide all text
                $('.shortcontent p:last', $this).css('margin-bottom', 0); //Remove bottom margin on last paragraph as it's likely shortened
            }
        });

    };

})(jQuery);
<|endoftext|>


<commit_before>/**
 * This class provides utility and helper functions when running a BlendJS
 * application in the Browser,Tablet, or a Smartphone
 */
Blend.defineClass('Blend.Environment', {
    requires: [
        'Blend.dom.Dom',
        'Blend.utils.String'
    ],
    singleton: true,
    /**
     * Default CSS prefix in BlendJS
     */
    CSS_PREFIX: 'b-',
    /**
     * The default uiType that is set by {Blend.web.Application} or {Blend.touch.Application}
     * This value is used internally for instantiating objects using their alias names.
     * @type {string} uiType
     */
    uiType: null,
    /**
     * Readonly property to indicating if the current browser is Internet Explorer
     * @type {Boolean}
     */
    isIE: null,
    /**
     * Readonly property providing the version, set only when the current browser
     * is Internet Explorer
     * @returns {Boolean}
     */
    IEVersion: null,
    /**
     * Adds an event listener to a DOM element
     * @param {Element} el
     * @param {String} eventName
     * @param {Function} eventHandler
     */
    addEventListener: function (el, eventName, eventHandler) {
        if (el.addEventListener) {
            el.addEventListener(eventName, eventHandler, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + eventName, eventHandler);
        }
    },
    /**
     * Removes an event listener from a DOM element
     * @param {Element} el
     * @param {String} eventName
     * @param {Function} eventHandler
     */
    removeEventListener: function (el, eventName, eventHandler) {
        if (el.removeEventListener) {
            el.removeEventListener(eventName, eventHandler, false);
        }
        if (el.detachEvent) {
            el.detachEvent('on' + eventName, eventHandler);
        }
    },
    /**
     * Registers a function as a callback that will be called when the document is ready
     * @param {Function} callback The callback function to run
     * @param {Object} scope The scope in which to run the callback. Defaults to Blend itself
     */
    ready: function (callback, scope) {
        var me = this;
        if (!me.readyCallbacks) {
            me.readyCallbacks = [];
        }
        me.readyCallbacks.push({
            fn: callback,
            sc: scope || me
        });
    },
    /*
     * Internal function for detecting the browser
     * The browser detection is only used to browser version checking.
     */
    detectBrowser: function () {
        var me = this,
                browser = navigator.userAgent.toLowerCase(),
                msie = ((/msie (\d+)/.exec(browser) || [])[1]);
        if (Blend.isNullOrUndef(msie)) {
            msie = ((/trident\/.*; rv:(\d+)/.exec(browser) || [])[1]);
        }

        me.isIE = !Blend.isNullOrUndef(msie);
        if (me.isIE) {
            me.IEVersion = parseInt(msie);
        } else {
            me.IEVersion = null;
        }
    },
    /**
     * An alternative to {Blend.Environment.kickStart} that can be used to kickstart an application.
     * @param {String} applicationClass A class that is derived from {Blend.web.Application}
     * or {Blend.touch.Appliction}
     */
    runApplication: function (applicationClass) {
        var me = this, appStart = function () {
            var app = Blend.create(applicationClass);
            if (Blend.isInstanceOf(app, 'Blend.core.Application')) {
                app.run();
            } else {
                throw new Error(applicationClass + " does not seem to be a Blend.core.Application instance");
            }
        };
        if (me.kickStarted) {
            appStart.apply(me, arguments);
        } else {
            me.ready(appStart);
        }
        me.kickStart();
    },
    /**
     * Checks if the probwer has certain capabilities to continue.
     * If the running browser is outdated to does not support certain
     * functions then Blend simply will not start!
     * @return {boolean}
     */
    isBrowserOK: function () {
        var me = this;
        if (me.isIE && me.IEVersion < 9) {
            document.write('Unable to tun this application! Please upgreade your outdated browser');
            return false;
        } else {
            return true;
        }
    },
    /**
     * Initiates Blend's application lifecycle by executing the callbacks
     * which are registered by {Environment.ready}
     */
    kickStart: function () {
        var me = this,
                didRun = false,
                doCallback = function () {
                    if (didRun === false) {
                        didRun = true;
                        if (me.isBrowserOK()) {
                            Blend.foreach(me.readyCallbacks, function (item) {
                                setTimeout(function () {
                                    item.fn.apply(item.sc, []);
                                }, 1);
                            });
                        }
                    }
                }

        if (!me.kickStarted) {
            me.kickStarted = true;
            me.detectBrowser();
            if (document.readyState === "complete") {
                setTimeout(doCallback, 5);
            } else {
                me.addEventListener(document, 'DOMContentLoaded', doCallback);
                me.addEventListener(window, 'load', doCallback);
            }
        }
    },
    cssPrefix: function (className) {
        var me = this, r = [];
        className = Blend.wrapInArray(className);
        Blend.foreach(className, function (itm) {
            r.push(me.CSS_PREFIX + itm);
        });
        return r;
    }
});<commit_msg>Refactored functions to be installed in Blend directly<commit_after>/**
 * This class provides utility and helper functions when running a BlendJS
 * application in the Browser,Tablet, or a Smartphone
 */
Blend.defineClass('Blend.Environment', {
    requires: [
        'Blend.dom.Dom',
        'Blend.utils.String'
    ],
    singleton: true,
    /**
     * Default CSS prefix in BlendJS
     */
    CSS_PREFIX: 'b-',
    /**
     * The default uiType that is set by {Blend.web.Application} or {Blend.touch.Application}
     * This value is used internally for instantiating objects using their alias names.
     * @type {string} uiType
     */
    uiType: null,
    /**
     * Readonly property to indicating if the current browser is Internet Explorer
     * @type {Boolean}
     */
    isIE: null,
    /**
     * Readonly property providing the version, set only when the current browser
     * is Internet Explorer
     * @returns {Boolean}
     */
    IEVersion: null,
    init: function () {
        var me = this;
        me.callParent.apply(me, arguments);
        me.cssPrefix();
    },
    /**
     * Adds an event listener to a DOM element
     * @param {Element} el
     * @param {String} eventName
     * @param {Function} eventHandler
     */
    addEventListener: function (el, eventName, eventHandler) {
        if (el.addEventListener) {
            el.addEventListener(eventName, eventHandler, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + eventName, eventHandler);
        }
    },
    /**
     * Removes an event listener from a DOM element
     * @param {Element} el
     * @param {String} eventName
     * @param {Function} eventHandler
     */
    removeEventListener: function (el, eventName, eventHandler) {
        if (el.removeEventListener) {
            el.removeEventListener(eventName, eventHandler, false);
        }
        if (el.detachEvent) {
            el.detachEvent('on' + eventName, eventHandler);
        }
    },
    /**
     * Registers a function as a callback that will be called when the document is ready
     * @param {Function} callback The callback function to run
     * @param {Object} scope The scope in which to run the callback. Defaults to Blend itself
     */
    ready: function (callback, scope) {
        var me = this;
        if (!me.readyCallbacks) {
            me.readyCallbacks = [];
        }
        me.readyCallbacks.push({
            fn: callback,
            sc: scope || me
        });
    },
    /*
     * Internal function for detecting the browser
     * The browser detection is only used to browser version checking.
     */
    detectBrowser: function () {
        var me = this,
                browser = navigator.userAgent.toLowerCase(),
                msie = ((/msie (\d+)/.exec(browser) || [])[1]);
        if (Blend.isNullOrUndef(msie)) {
            msie = ((/trident\/.*; rv:(\d+)/.exec(browser) || [])[1]);
        }

        me.isIE = !Blend.isNullOrUndef(msie);
        if (me.isIE) {
            me.IEVersion = parseInt(msie);
        } else {
            me.IEVersion = null;
        }
    },
    /**
     * An alternative to {Blend.Environment.kickStart} that can be used to kickstart an application.
     * @param {String} applicationClass A class that is derived from {Blend.web.Application}
     * or {Blend.touch.Appliction}
     */
    runApplication: function (applicationClass) {
        var me = this, appStart = function () {
            var app = Blend.create(applicationClass);
            if (Blend.isInstanceOf(app, 'Blend.core.Application')) {
                app.run();
            } else {
                throw new Error(applicationClass + " does not seem to be a Blend.core.Application instance");
            }
        };
        if (me.kickStarted) {
            appStart.apply(me, arguments);
        } else {
            me.ready(appStart);
        }
        me.kickStart();
    },
    /**
     * Checks if the probwer has certain capabilities to continue.
     * If the running browser is outdated to does not support certain
     * functions then Blend simply will not start!
     * @return {boolean}
     */
    isBrowserOK: function () {
        var me = this;
        if (me.isIE && me.IEVersion < 9) {
            document.write('Unable to tun this application! Please upgreade your outdated browser');
            return false;
        } else {
            return true;
        }
    },
    /**
     * Initiates Blend's application lifecycle by executing the callbacks
     * which are registered by {Environment.ready}
     */
    kickStart: function () {
        var me = this,
                didRun = false,
                doCallback = function () {
                    if (didRun === false) {
                        didRun = true;
                        if (me.isBrowserOK()) {
                            Blend.foreach(me.readyCallbacks, function (item) {
                                setTimeout(function () {
                                    item.fn.apply(item.sc, []);
                                }, 1);
                            });
                        }
                    }
                }

        if (!me.kickStarted) {
            me.kickStarted = true;
            me.detectBrowser();
            if (document.readyState === "complete") {
                setTimeout(doCallback, 5);
            } else {
                me.addEventListener(document, 'DOMContentLoaded', doCallback);
                me.addEventListener(window, 'load', doCallback);
            }
        }
    },
    cssPrefix: function () {
        var me = this;
        Blend.cssPrefix = function (className) {
            var r = [];
            className = Blend.wrapInArray(className);
            Blend.foreach(className, function (itm) {
                r.push(me.CSS_PREFIX + itm);
            });
            return r;
        }
    }
});<|endoftext|>


<commit_before>'use strict';

var wordScramble = wordScramble || {};
wordScramble.gameService = (function(configuration, pubsub)
{
	var gService = {};

	var CONST_ELEMENT_ID = "#gameContainer";
	var storageKey = 'wordScramble.gameData';
	var dictionary = [];
	var gameData = {};

	function getElement()
	{
		return document.querySelector(CONST_ELEMENT_ID);
	}

	function saveGameData()
	{
		window.localStorage.setItem(storageKey, JSON.stringify(gameData));
	}
	function loadGameData()
	{
		if (!window.localStorage) return;
		var storedData = window.localStorage.getItem(storageKey);
		if (storedData)
		{
			gameData = JSON.parse(storedData);
			return true;
		}
		return false;
	}

	function setWordSolved(wordObject)
	{
		var index = gameData.words.indexOf(wordObject);
		wordObject.solved = true;
		gameData.words.splice(index, 1, wordObject);
	}

	function subscribe()
	{
		pubsub.subscribe("wordScramble/endGame", function()
		{
			clearGameCache();
		});
		pubsub.subscribe("wordScramble/startGame", function()
		{
			startGame();
		});
		pubsub.subscribe("wordScramble/submitWord", function()
		{
			submitWordAttempt(wordScramble.wordAttemptService.getWordString());
			pubsub.publish("wordScramble/clearWordAttempt");
		});
		pubsub.subscribe("wordScramble/gameReady", function(topic, data)
		{
			console.log(data);
			var el = document.querySelector("body");
			if (el !== null)
			{
				el.classList.remove("status");
				var status = document.querySelector("#status");
				status.textContent = "";
			}
			gameData = data.gameData;

			pubsub.publish("wordScramble/lettersChanged", { "letters":gameData.letters });
-			pubsub.publish("wordScramble/wordsChanged", { "words":gameData.words });

			saveGameData();
		});
	}

	function clearGameCache()
	{
		var words = gameData.words;
		pubsub.publish("wordScramble/gameOver", {"words":words});
		window.localStorage.removeItem(storageKey);
	}

	function submitWordAttempt(word)
	{
		var words = gameData.words;
		var result = words.filter(function(o)
		{
			return o.word === word;
		});
		if (result && result[0] != null)
		{
			if (result[0].solved === true)
			{
				pubsub.publish("wordScramble/wordAttemptAlreadyExists", {"word":word});
			}
			else
			{
				setWordSolved(result[0]);

				// refetch to get updated value.
				words = gameData.words;

				pubsub.publish("wordScramble/wordsChanged", {"words":words});
				pubsub.publish("wordScramble/wordAttemptAccepted", {"word":word});
			}
		}
		else
		{
			pubsub.publish("wordScramble/wordAttemptRejected", {"word":word});
		}

		var victory = words.every(function(o, i)
		{
			return o.solved === true;
		});
		if (victory)
		{
			pubsub.publish("wordScramble/allWordsSolved", {"words":words});
		}

		saveGameData();
	}

	function startGame()
	{
		var el = document.querySelector("body");
		if (el !== null)
		{
			el.classList.add("status");
			var status = document.querySelector("#status");
			status.textContent = "Preparing game...";
		}

		var loaded = loadGameData();
		if (loaded)
		{
			pubsub.publish("wordScramble/gameReady", { gameData : gameData });
		}
		else
		{
			wordScramble.gameBuilder.build(wordScramble.dict);
		}
	}

	subscribe();
	startGame();

	return gService;

})(wordScramble.configuration, window.pubsubz);

<commit_msg>Clear the current word attempt when starting a game<commit_after>'use strict';

var wordScramble = wordScramble || {};
wordScramble.gameService = (function(configuration, pubsub)
{
	var gService = {};

	var CONST_ELEMENT_ID = "#gameContainer";
	var storageKey = 'wordScramble.gameData';
	var dictionary = [];
	var gameData = {};

	function getElement()
	{
		return document.querySelector(CONST_ELEMENT_ID);
	}

	function saveGameData()
	{
		window.localStorage.setItem(storageKey, JSON.stringify(gameData));
	}
	function loadGameData()
	{
		if (!window.localStorage) return;
		var storedData = window.localStorage.getItem(storageKey);
		if (storedData)
		{
			gameData = JSON.parse(storedData);
			return true;
		}
		return false;
	}

	function setWordSolved(wordObject)
	{
		var index = gameData.words.indexOf(wordObject);
		wordObject.solved = true;
		gameData.words.splice(index, 1, wordObject);
	}

	function subscribe()
	{
		pubsub.subscribe("wordScramble/endGame", function()
		{
			clearGameCache();
		});
		pubsub.subscribe("wordScramble/startGame", function()
		{
			startGame();
			pubsub.publish("wordScramble/clearWordAttempt");
		});
		pubsub.subscribe("wordScramble/submitWord", function()
		{
			submitWordAttempt(wordScramble.wordAttemptService.getWordString());
			pubsub.publish("wordScramble/clearWordAttempt");
		});
		pubsub.subscribe("wordScramble/gameReady", function(topic, data)
		{
			console.log(data);
			var el = document.querySelector("body");
			if (el !== null)
			{
				el.classList.remove("status");
				var status = document.querySelector("#status");
				status.textContent = "";
			}
			gameData = data.gameData;

			pubsub.publish("wordScramble/lettersChanged", { "letters":gameData.letters });
-			pubsub.publish("wordScramble/wordsChanged", { "words":gameData.words });

			saveGameData();
		});
	}

	function clearGameCache()
	{
		var words = gameData.words;
		pubsub.publish("wordScramble/gameOver", {"words":words});
		window.localStorage.removeItem(storageKey);
	}

	function submitWordAttempt(word)
	{
		var words = gameData.words;
		var result = words.filter(function(o)
		{
			return o.word === word;
		});
		if (result && result[0] != null)
		{
			if (result[0].solved === true)
			{
				pubsub.publish("wordScramble/wordAttemptAlreadyExists", {"word":word});
			}
			else
			{
				setWordSolved(result[0]);

				// refetch to get updated value.
				words = gameData.words;

				pubsub.publish("wordScramble/wordsChanged", {"words":words});
				pubsub.publish("wordScramble/wordAttemptAccepted", {"word":word});
			}
		}
		else
		{
			pubsub.publish("wordScramble/wordAttemptRejected", {"word":word});
		}

		var victory = words.every(function(o, i)
		{
			return o.solved === true;
		});
		if (victory)
		{
			pubsub.publish("wordScramble/allWordsSolved", {"words":words});
		}

		saveGameData();
	}

	function startGame()
	{
		var el = document.querySelector("body");
		if (el !== null)
		{
			el.classList.add("status");
			var status = document.querySelector("#status");
			status.textContent = "Preparing game...";
		}

		var loaded = loadGameData();
		if (loaded)
		{
			pubsub.publish("wordScramble/gameReady", { gameData : gameData });
		}
		else
		{
			wordScramble.gameBuilder.build(wordScramble.dict);
		}
	}

	subscribe();
	startGame();

	return gService;

})(wordScramble.configuration, window.pubsubz);

<|endoftext|>


<commit_before>var jsTrek.main = window.jstTrek.main || {};

var star = {
	chance: 08,
	types: ['active'],
	display: '*'
};

var starBase = {
	chance: 01,
	types: ['research','supply','friendly','enemy'],
	display: '@'

};

var planet = {
	chance: 01,
	types: ['O','M','K','Z'],
	display: '$'
};

var empty = {
	display: '.'
};

var choices = [star,starBase,planet];

var starField = [];
var createStarField = function() {
	for (var k = 1; k <= 64; k++) {
		var choice = determineObject(choices);
		if (choice !== undefined) {
			starField[k] = choice;
		}
		else {
			starField[k] = empty.display;
		}
	}
};
var determineObject = function(arr) {
	console.dir(arr);
	var chosenObject = undefined;
	for (var i = 0; i < arr.length; i++) {
		if (chosenObject !== undefined) { break; }
		if (getRandomArbitrary(1,64) <= arr[i].chance) {
			chosenObject = arr[i].display;
		}
	}
	return chosenObject;
};

var getRandomArbitrary = function(min,max) {
	return Math.floor(Math.random() * (max-min + 1)) + min;
};

var paintStarField = function(starField) {
	var field = "";
	console.dir(starField);
	for(var i = 1; i < starField.length; i++) {
		field += starField[i];
		if (i % 8 == 0) {
			field += "\n";
		}
	}
	return field;
}<commit_msg>call doItAll(); to generate a starfield.<commit_after>var jsTrek.main = window.jstTrek.main || {};

var star = {
	chance: 08,
	types: ['active'],
	display: '*'
};

var starBase = {
	chance: 01,
	types: ['research','supply','friendly','enemy'],
	display: '@'

};

var planet = {
	chance: 01,
	types: ['O','M','K','Z'],
	display: '$'
};

var empty = {
	display: '.'
};

var choices = [star,starBase,planet];

var starField = [];
var createStarField = function() {
	for (var k = 1; k <= 64; k++) {
		var choice = determineObject(choices);
		if (choice !== undefined) {
			starField[k] = choice;
		}
		else {
			starField[k] = empty.display;
		}
	}
};
var determineObject = function(arr) {
	console.dir(arr);
	var chosenObject = undefined;
	for (var i = 0; i < arr.length; i++) {
		if (chosenObject !== undefined) { break; }
		if (getRandomArbitrary(1,64) <= arr[i].chance) {
			chosenObject = arr[i].display;
		}
	}
	return chosenObject;
};

var getRandomArbitrary = function(min,max) {
	return Math.floor(Math.random() * (max-min + 1)) + min;
};

var paintStarField = function(starField) {
	var line1 = "  1 2 3 4 5 6 7 8\n1 ";
	var field = line1;
	console.dir(starField);
	var n = 2;
	for(var i = 1; i < starField.length; i++) {
		field += starField[i] + " ";
		if (i % 8 == 0) {
			field += "\n" + n + " ";
			n++;
		}
	}
	return field.substring(0, field.length - 3);
}

var doItAll = function() {
	createStarField();
	console.log(paintStarField(starField));
}<|endoftext|>


<commit_before>
var Store = require('../utils/Store.js'),
    D = require('../dispatcher'),
    Vms = require('./vms')
    HowlHelper = require('../utils/howl-helper')

var Howl = module.exports = new Store({resource: 'asdasd'})

Howl.dispatchToken = D.register(function(payload) {
    var action = payload.action

    switch (action.actionType) {

        case 'SESSION_LOGIN_OK':
            helper.connect(action.endpoint.replace('http', 'ws') + '/howl', action.token)
            Vms.subscribe(joinChannels)
            break;

        case 'SESSION_LOGOUT':
            leaveChannels()
            helper.disconnect()
            Vms.unsubscribe(joinChannels)
            break;
    }

    return false
})

//Set the default values
Howl.initStore = function() {
    Howl.clear()
    Howl.set('connected', false)
    Howl.set('channels', [])
}
Howl.initStore()

Howl.join = function(id) {

    var chans = Howl.get('channels')

    if (chans.indexOf(id) > -1)
        return false //Just ignore duplicate calls.
        // throw new Error('Channel already subscribed: ' + id)

    console.log('joining ' + id + ' ...')

    helper.send({join: id})
    chans.push(id)
}

Howl.leave = function(id) {

    var chans = Howl.get('channels'),
        idx = chans.indexOf(id)

    if (idx < 0)
        throw new Error('Cannot leave unknown channel: ' + id)

    console.log('leaving ' + id + ' ...')

    helper.send({leave: id})
    chans.splice(idx, 0)
}

var helper = new HowlHelper({
    onLogin: function() {
        Howl.set('connected', true)
        joinChannels()
        Howl.emit()
    },

    onDisconnect: function() {
        Howl.initStore()
        Howl.emit()
    },

    onMsg: function(msg) {
        console.log('#: onMsg', msg)
    }
})

//Join to the saved channels
function joinChannels() {

    if (!Howl.get('connected'))
        return

    var list = Vms.getAll().map(function(vm) {return vm.uuid})
    list.map(Howl.join)
}

//Leave the joined channels
function leaveChannels() {
    Howl.get('channels').map(Howl.leave)
}
<commit_msg>Handle incomming howl-messages for the VMs.<commit_after>
var Store = require('../utils/Store.js'),
    D = require('../dispatcher'),
    Vms = require('./vms'),
    Vm = require('./vm'),
    HowlHelper = require('../utils/howl-helper')

var Howl = module.exports = new Store({resource: 'asdasd'})

Howl.dispatchToken = D.register(function(payload) {
    var action = payload.action

    switch (action.actionType) {

        case 'SESSION_LOGIN_OK':
            helper.connect(action.endpoint.replace('http', 'ws') + '/howl', action.token)
            Vms.subscribe(joinChannels)
            break;

        case 'SESSION_LOGOUT':
            leaveChannels()
            helper.disconnect()
            Vms.unsubscribe(joinChannels)
            break;
    }

    return false
})

function emitVm() {
    Vms.emit()

    //If there is a currently selected VM, emit that store too.
    if (Vm.get('vm'))
        Vm.emit()
}

//Handle message from howl
function handleMessage(obj) {

    var chan = obj.channel,
        msg = obj.message,
        vm = Vms.get(chan)

    if (!chan || !vm) return

    switch (msg.event) {
        case 'log':
            vm.log.push(msg.data)
            emitVm()
            break;

        case 'state':
            vm.state = msg.data
            emitVm()
            break;

        case 'services':
            vm.services = msg.data
            emitVm()
            break;

        default:
            console.log('unhandled msg:', msg)
    }

}

//Set the default values
Howl.initStore = function() {
    Howl.clear()
    Howl.set('connected', false)
    Howl.set('channels', [])
}
Howl.initStore()

Howl.join = function(id) {

    var chans = Howl.get('channels')

    if (chans.indexOf(id) > -1)
        return false //Just ignore duplicate calls.
        // throw new Error('Channel already subscribed: ' + id)

    console.log('joining ' + id + ' ...')

    helper.send({join: id})
    chans.push(id)
}

Howl.leave = function(id) {

    var chans = Howl.get('channels'),
        idx = chans.indexOf(id)

    if (idx < 0)
        throw new Error('Cannot leave unknown channel: ' + id)

    console.log('leaving ' + id + ' ...')

    helper.send({leave: id})
    chans.splice(idx, 0)
}

var helper = new HowlHelper({
    onLogin: function() {
        Howl.set('connected', true)
        joinChannels()
        Howl.emit()
    },

    onDisconnect: function() {
        Howl.initStore()
        Howl.emit()
    },

    onMsg: function(msg) {
        handleMessage(msg)
    }
})

//Join to the saved channels
function joinChannels() {

    if (!Howl.get('connected'))
        return

    var list = Vms.getAll().map(function(vm) {return vm.uuid})
    list.map(Howl.join)
}

//Leave the joined channels
function leaveChannels() {
    Howl.get('channels').map(Howl.leave)
}
<|endoftext|>