<commit_before>'use strict';

    // Task related
var name        = 'manage-image',

    // Project & path related
    project     = require('../project'),
    image       = project.path.image,
    assets      = image+'/assets',
    style_assets = project.path.style+'/assets',

    // Gulp related
    Task        = require('./helpers/task.helper'),
    gulp        = require('gulp'),
    debug       = require('gulp-debug'),
    sprite      = require('gulp.spritesmith'),
    clean       = require('del'),

    log         = console.log;

module.exports = {
    compile: new Task(
        name+':compile',
        function() {
            gulp.src([assets+'/apple-touch-icon.png',
                      assets+'/favicon.ico',
                      assets+'/tile*.png'])
                .pipe(debug())
                .pipe(gulp.dest(image));

            var stream = gulp.src(['!'+assets+'/apple-touch-icon.png',
                                   '!'+assets+'/favicon.ico',
                                   '!'+assets+'/tile*.png',
                                       assets+'/*.png'])
                             .pipe(sprite({
                                imgName: 'sprites.png',
                                cssName: 'sprites.styl'
                             }));

            stream.img
                .pipe(debug())
                .pipe(gulp.dest(image)); // image assets

            stream.css
                .pipe(debug())
                .pipe(gulp.dest(style_assets));
        }
    ),
    cleanup: new Task(
        name+':cleanup',
        function() {
            clean([image+'/*.*'], {force: true}); // force: true allows deleting files outside of cwd
        }
    )
};
<commit_msg>Update manage-image task<commit_after>'use strict';

    // Task related
var name        = 'manage-image',

    // Project & path related
    project     = require('../project'),
    root        = project.path.root,
    image       = project.path.image,
    assets      = image+'/assets',
    style_assets = project.path.style+'/assets',

    // Gulp related
    Task        = require('./helpers/task.helper'),
    gulp        = require('gulp'),
    debug       = require('gulp-debug'),
    sprite      = require('gulp.spritesmith'),
    clean       = require('del'),
    rename      = require('gulp-rename'),

    log         = console.log;

module.exports = {
    cleanup: new Task(
        name+':cleanup',
        function() {
            clean([
                root+'/apple-touch-icon.png',
                root+'/favicon.ico',
                root+'/tile*.png',
                image+'/*.*',
                style_assets+'/sprites.styl'
                ], {force: true}); // force: true allows deleting files outside of cwd
        }
    ),
    compile: new Task(
        name+':compile',
        function() {
            gulp.src([assets+'/apple-touch-icon.png',
                      assets+'/favicon.ico',
                      assets+'/tile*.png'])
                .pipe(debug())
                .pipe(gulp.dest(root));

            var stream = gulp.src(['!'+assets+'/apple-touch-icon.png',
                                   '!'+assets+'/favicon.ico',
                                   '!'+assets+'/tile*.png',
                                       assets+'/*.png'])
                             .pipe(sprite({
                                imgName: 'sprites.png',
                                cssName: 'sprites.styl'
                             }));

            stream.img // save sprites image
                .pipe(debug())
                .pipe(rename({
                    basename: 'raw_sprites',
                    extname:  '.png'
                }))
                .pipe(gulp.dest(image)); // image assets dir

            stream.css // save sprites style
                .pipe(debug())
                .pipe(gulp.dest(style_assets));
        }
    ),
    assemble: new Task(
        name+':assemble',
        function() {
            var imagemin = require('imagemin');
            var pngquant = require('imagemin-pngquant');

            new imagemin()
                .src(image+'/raw_sprites.png')
                .use(rename({
                    basename: 'sprites',
                    extname:  '.png'
                }))
                .dest(image)
                .use(pngquant({quality: '65-80', speed: 1}))
                .run();
        }
    )
};
<|endoftext|>


<commit_before>import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import {Provider} from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { ReduxAsyncConnect } from 'redux-async-connect';
import useScroll from 'scroll-behavior/lib/useStandardScroll';

import getRoutes from './routes';

const client = new ApiClient();
const _browserHistory = useScroll(() => browserHistory)();
const dest = document.getElementById('content');
const store = createStore(_browserHistory, client, window.__data);
const history = syncHistoryWithStore(_browserHistory, store);

const component = (
  <Router render={(props) =>
    <ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} />
    } history={history}>
    {getRoutes(store)}
  </Router>
);

ReactDOM.render(
  <Provider store={store} key="provider">
    {component}
  </Provider>,
  dest
);

if (process.env.NODE_ENV !== 'production') {
  window.React = React; // enable debugger

  if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
    console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
  }
}

if (!window.devToolsExtension) {
  ReactDOM.render(
    <Provider store={store} key="provider">
      <div>
        {component}
      </div>
    </Provider>,
    dest
  );
}
<commit_msg>remove client file<commit_after><|endoftext|>


<commit_before>import express from 'express';
import SearchBlocks from '../../collections/search_blocks';
import { extend } from 'underscore';
import apolloMiddleware from 'react/apollo/middleware';
import setOnboardingComponentMiddleware from 'apps/onboarding/middleware/setOnboardingComponent';

const app = express();

app.set('views', `${__dirname}/templates`);
app.set('view engine', 'jade');

const renderOnboarding = (req, res, next) => {
  res.render('index');
};

const middlewareStack = [
  apolloMiddleware,
  setOnboardingComponentMiddleware
];

app.get('/welcome', ...middlewareStack, renderOnboarding);

module.exports = app;
<commit_msg>Add ensure_logged_in to onboarding middleware stack<commit_after>import express from 'express';
import SearchBlocks from '../../collections/search_blocks';
import { extend } from 'underscore';
import apolloMiddleware from 'react/apollo/middleware';
import ensureLoggedInMiddleware from 'lib/middleware/ensure_logged_in.coffee';
import setOnboardingComponentMiddleware from 'apps/onboarding/middleware/setOnboardingComponent';

const app = express();

app.set('views', `${__dirname}/templates`);
app.set('view engine', 'jade');

const renderOnboarding = (req, res, next) => {
  res.render('index');
};

const middlewareStack = [
  ensureLoggedInMiddleware,
  apolloMiddleware,
  setOnboardingComponentMiddleware
];

app.get('/welcome', ...middlewareStack, renderOnboarding);

module.exports = app;
<|endoftext|>


<commit_before>var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var colorLighten = require('less-color-lighten');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var replace = require('gulp-replace');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var webpack = require('webpack');

var config = require('../configuration');
var packageInfo = require('../package');
var webpackConfig = require('../webpack.config.js');

gulp.task('docs:browsersync', function () {
  browserSync.init({
    open: false,
    port: 4200,
    server: {
      baseDir: config.dirs.docs.dist
    },
    socket: {
      domain: 'localhost:4200'
    }
  });
});

gulp.task('docs:eslint', ['eslint'], function () {
  return gulp.src([config.dirs.docs.srcJS + '/**/*.?(js|jsx)'])
    .pipe(eslint())
    .pipe(eslint.formatEach('stylish', process.stderr));
});

gulp.task('docs:html', function () {
  return gulp.src(config.files.docs.srcHTML)
    .pipe(gulp.dest(config.dirs.docs.dist));
});

gulp.task('docs:less', function () {
  return gulp.src(config.files.docs.srcCSS, {read: true}, {ignorePath: 'src'})
    .pipe(sourcemaps.init())
    .pipe(less({
      paths: [config.dirs.docs.cssSrc], // @import paths
      plugins: [colorLighten]
    }))
    .pipe(autoprefixer())
    .pipe(concat(config.files.docs.distCSS))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('.'))
    .pipe(browserSync.stream());
});

gulp.task('docs:minify-css', ['docs:less'], function () {
  return gulp.src(config.files.docs.distCSS)
    .pipe(minifyCSS())
    .pipe(gulp.dest(config.dirs.docs.distCSS));
});

gulp.task('docs:minify-js', ['docs:replace-js-strings'], function () {
  return gulp.src(config.files.docs.distJS)
    .pipe(uglify({
      mangle: true,
      compress: true
    }))
    .pipe(gulp.dest(config.dirs.docs.distJS));
});

gulp.task('docs:replace-js-strings', ['docs:webpack'], function() {
  return gulp.src(config.files.docs.distJS)
    .pipe(replace('@@VERSION', packageInfo.version))
    .pipe(gulp.dest(config.dirs.docs.distJS));
});

gulp.task('docs:watch', function () {
  gulp.watch(config.files.docs.srcHTML, ['docs:html']);
  gulp.watch([
    config.dirs.docs.srcCSS + '/**/*.less',
    config.dirs.srcCSS + '/**/*.less'
  ], ['docs:less']);
  gulp.watch([
    config.dirs.docs.srcJS + '/**/*.?(js|jsx)',
    config.dirs.srcJS + '/**/*.?(js|jsx)'
  ], ['docs:webpack', 'docs:replace-js-strings', 'eslint']);
});

// Use webpack to compile jsx into js,
gulp.task('docs:webpack', ['docs:eslint'], function (callback) {
  // Extend options with source mapping
  webpackConfig.devtool = 'source-map';
  webpackConfig.module.preLoaders = [
    {
      test: /\.js$/,
      loader: 'source-map-loader',
      exclude: /node_modules/
    }
  ];
  // run webpack
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("webpack", err);
    }

    gutil.log("[webpack]", stats.toString({
      children: false,
      chunks: false,
      colors: true,
      modules: false,
      timing: true
    }));

    browserSync.reload();
    callback();
  });
});

gulp.task('docs:default', [
  'docs:eslint',
  'docs:webpack',
  'docs:replace-js-strings',
  'docs:less',
  'docs:html'
]);

gulp.task('docs:dist', [
  'docs:default',
  'docs:minify-css',
  'docs:minify-js'
]);

gulp.task('docs:livereload', [
  'docs:default',
  'docs:browsersync',
  'docs:watch'
]);
<commit_msg>Polish gulpfile<commit_after>var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var colorLighten = require('less-color-lighten');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var replace = require('gulp-replace');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var webpack = require('webpack');

var config = require('../configuration');
var packageInfo = require('../package');
var webpackConfig = require('../webpack.config.js');

gulp.task('docs:browsersync', function () {
  browserSync.init({
    open: false,
    port: 4200,
    server: {
      baseDir: config.dirs.docs.dist
    },
    socket: {
      domain: 'localhost:4200'
    }
  });
});

gulp.task('docs:eslint', ['eslint'], function () {
  return gulp.src([config.dirs.docs.srcJS + '/**/*.?(js|jsx)'])
    .pipe(eslint())
    .pipe(eslint.formatEach('stylish', process.stderr));
});

gulp.task('docs:html', function () {
  return gulp.src(config.files.docs.srcHTML)
    .pipe(gulp.dest(config.dirs.docs.dist));
});

gulp.task('docs:less', function () {
  return gulp.src(config.files.docs.srcCSS, {read: true}, {ignorePath: 'src'})
    .pipe(sourcemaps.init())
    .pipe(less({
      paths: [config.dirs.docs.cssSrc], // @import paths
      plugins: [colorLighten]
    }))
    .pipe(autoprefixer())
    .pipe(concat(config.files.docs.distCSS))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('.'))
    .pipe(browserSync.stream());
});

gulp.task('docs:minify-css', ['docs:less'], function () {
  return gulp.src(config.files.docs.distCSS)
    .pipe(minifyCSS())
    .pipe(gulp.dest(config.dirs.docs.distCSS));
});

gulp.task('docs:minify-js', ['docs:replace-js-strings'], function () {
  return gulp.src(config.files.docs.distJS)
    .pipe(uglify({
      mangle: true,
      compress: true
    }))
    .pipe(gulp.dest(config.dirs.docs.distJS));
});

gulp.task('docs:replace-js-strings', ['docs:webpack'], function () {
  return gulp.src(config.files.docs.distJS)
    .pipe(replace('@@VERSION', packageInfo.version))
    .pipe(gulp.dest(config.dirs.docs.distJS));
});

gulp.task('docs:watch', function () {
  gulp.watch(config.files.docs.srcHTML, ['docs:html']);
  gulp.watch([
    config.dirs.docs.srcCSS + '/**/*.less',
    config.dirs.srcCSS + '/**/*.less'
  ], ['docs:less']);
  gulp.watch([
    config.dirs.docs.srcJS + '/**/*.?(js|jsx)',
    config.dirs.srcJS + '/**/*.?(js|jsx)'
  ], ['docs:webpack', 'docs:replace-js-strings', 'eslint']);
});

// Use webpack to compile jsx into js,
gulp.task('docs:webpack', ['docs:eslint'], function (callback) {
  // Extend options with source mapping
  webpackConfig.devtool = 'source-map';
  webpackConfig.module.preLoaders = [
    {
      test: /\.js$/,
      loader: 'source-map-loader',
      exclude: /node_modules/
    }
  ];
  // run webpack
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack', err);
    }

    gutil.log('[webpack]', stats.toString({
      children: false,
      chunks: false,
      colors: true,
      modules: false,
      timing: true
    }));

    browserSync.reload();
    callback();
  });
});

gulp.task('docs:default', [
  'docs:eslint',
  'docs:webpack',
  'docs:replace-js-strings',
  'docs:less',
  'docs:html'
]);

gulp.task('docs:dist', [
  'docs:default',
  'docs:minify-css',
  'docs:minify-js'
]);

gulp.task('docs:livereload', [
  'docs:default',
  'docs:browsersync',
  'docs:watch'
]);
<|endoftext|>


<commit_before><commit_msg>Issue ekstep/Contributed-Plugins#139 feat: Gulp callback called many times error<commit_after><|endoftext|>


<commit_before>/*
 * grunt-ember-handlebars
 * https://github.com/yaymukund/grunt-ember-handlebars
 *
 * Copyright (c) 2012 Mukund Lakshman
 * Licensed under the MIT license.
 *
 * A grunt task that precompiles Ember.js Handlebars templates into
 * separate .js files of the same name. This script expects the
 * following setup:
 *
 * tasks/
 *   ember-templates.js
 *   lib/
 *     headless-ember.js
 *     ember.js
 *
 * headless-ember and ember.js can both be found in the main Ember repo:
 *   https://github.com/emberjs/ember.js/tree/master/lib
 */

var precompiler = require('./lib/precompiler'),
    path = require('path');

module.exports = function(grunt) {
  grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() {
    var files = grunt.file.expandFiles(this.file.src);
    grunt.utils._.each(files, function(file) {
      grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"');

      var compiled = precompiler.precompile(file);
          out = path.join(this.dest, compiled.filename);

      grunt.file.write(out, compiled.src, 'utf8');

    }, {dest: this.file.dest});
  });
};
<commit_msg>Fix newlines in grunt log output.<commit_after>/*
 * grunt-ember-handlebars
 * https://github.com/yaymukund/grunt-ember-handlebars
 *
 * Copyright (c) 2012 Mukund Lakshman
 * Licensed under the MIT license.
 *
 * A grunt task that precompiles Ember.js Handlebars templates into
 * separate .js files of the same name. This script expects the
 * following setup:
 *
 * tasks/
 *   ember-templates.js
 *   lib/
 *     headless-ember.js
 *     ember.js
 *
 * headless-ember and ember.js can both be found in the main Ember repo:
 *   https://github.com/emberjs/ember.js/tree/master/lib
 */

var precompiler = require('./lib/precompiler'),
    path = require('path');

module.exports = function(grunt) {
  grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() {
    var files = grunt.file.expandFiles(this.file.src);
    grunt.utils._.each(files, function(file) {
      grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"\n');

      var compiled = precompiler.precompile(file);
          out = path.join(this.dest, compiled.filename);

      grunt.file.write(out, compiled.src, 'utf8');

    }, {dest: this.file.dest});
  });
};
<|endoftext|>


<commit_before>const User = require('../../services/user')
const Github = require('../../services/github')

const lokaliseBaseConfig = {
  AWS_ACCESS_KEY: process.env.AWS_ACCESS_KEY,
  AWS_REGION: process.env.AWS_REGION,
  AWS_SECRET_KEY: process.env.AWS_SECRET_KEY,
  LOKALISE_API_TOKEN: process.env.LOKALISE_API_TOKEN,
  LOKALISE_BASE_PATH: process.env.LOKALISE_BASE_PATH,
  LOKALISE_PROJECT_ID: process.env.LOKALISE_PROJECT_ID,
}
const lokaliseDevConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_DEV_BUCKET}
const lokaliseStagingConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_STAGING_BUCKET}
const lokaliseProdConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_BUCKET}

const lokalise = {
  'prod': require('bots-lokalise')(lokaliseProdConfig),
  'staging': require('bots-lokalise')(lokaliseStagingConfig),
  'dev': require('bots-lokalise')(lokaliseDevConfig),
}

const release ([env, ...rest]) {
  switch (env) {
    case 'd':
    case 'dev':
      return lokalise['dev'].handler(rest).then(() => 'released to develop')
    case 's':
    case 'staging':
      return lokalise['staging'].handler(rest).then(() => 'released to staging')
    case 'p':
    case 'prod':
    case 'production':
      return lokalise['prod'].handler(rest).then(() => 'released to production')
    default:
      return Promise.resolve(`usage:
lokalise release dev
lokalise release staging
lokalise release production`)
  }
}

const handler = ([action, ...rest], actorId) => {
  const actor = User.get(actorId)
  if (!actor || !actor.isAdmin) {
    return Promise.resolve('No Permission')
  }

  switch (action) {
    case 'release':
      return release(rest);
    default:
      return Promise.resolve(`usage:
lokalise release [env]`)
  }
}

module.exports = handler

<commit_msg>Fix typo<commit_after>const User = require('../../services/user')
const Github = require('../../services/github')

const lokaliseBaseConfig = {
  AWS_ACCESS_KEY: process.env.AWS_ACCESS_KEY,
  AWS_REGION: process.env.AWS_REGION,
  AWS_SECRET_KEY: process.env.AWS_SECRET_KEY,
  LOKALISE_API_TOKEN: process.env.LOKALISE_API_TOKEN,
  LOKALISE_BASE_PATH: process.env.LOKALISE_BASE_PATH,
  LOKALISE_PROJECT_ID: process.env.LOKALISE_PROJECT_ID,
}
const lokaliseDevConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_DEV_BUCKET}
const lokaliseStagingConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_STAGING_BUCKET}
const lokaliseProdConfig = {...lokaliseBaseConfig, AWS_S3_BUCKET: process.env.AWS_S3_BUCKET}

const lokalise = {
  'prod': require('bots-lokalise')(lokaliseProdConfig),
  'staging': require('bots-lokalise')(lokaliseStagingConfig),
  'dev': require('bots-lokalise')(lokaliseDevConfig),
}

const release = ([env, ...rest]) => {
  switch (env) {
    case 'd':
    case 'dev':
      return lokalise['dev'].handler(rest).then(() => 'released to develop')
    case 's':
    case 'staging':
      return lokalise['staging'].handler(rest).then(() => 'released to staging')
    case 'p':
    case 'prod':
    case 'production':
      return lokalise['prod'].handler(rest).then(() => 'released to production')
    default:
      return Promise.resolve(`usage:
lokalise release dev
lokalise release staging
lokalise release production`)
  }
}

const handler = ([action, ...rest], actorId) => {
  const actor = User.get(actorId)
  if (!actor || !actor.isAdmin) {
    return Promise.resolve('No Permission')
  }

  switch (action) {
    case 'release':
      return release(rest);
    default:
      return Promise.resolve(`usage:
lokalise release [env]`)
  }
}

module.exports = handler

<|endoftext|>


<commit_before>// @flow

import {createStore, applyMiddleware, combineReducers} from 'redux'
import {createLogger} from 'redux-logger'
import reduxPromise from 'redux-promise'
import reduxThunk from 'redux-thunk'

import {homescreen, type State as HomescreenState} from './parts/homescreen'
import {settings, type State as SettingsState} from './parts/settings'
import {buildings, type State as BuildingsState} from './parts/buildings'
import {help, type State as HelpState} from './parts/help'
import {courses, type State as CoursesState} from './parts/courses'
import {stoprint, type State as StoPrintState} from './parts/stoprint'
import {
	notifications,
	type State as NotificationsState,
} from './parts/notifications'
import {login, type State as LoginState} from './parts/login'

export {init as initRedux} from './init'

export type ReduxState = {
	courses?: CoursesState,
	homescreen?: HomescreenState,
	settings?: SettingsState,
	buildings?: BuildingsState,
	help?: HelpState,
	stoprint?: StoPrintState,
	notifications?: NotificationsState,
	login?: LoginState,
}

export const makeStore = () => {
	const aao = combineReducers({
		courses,
		homescreen,
		settings,
		buildings,
		help,
		stoprint,
		notifications,
		login,
	})

	const middleware = [reduxPromise, reduxThunk]

	if (__DEV__) {
		const logger = createLogger({
			collapsed: true,
			duration: true,
			// avoid logging the (large) course data state twice per action
			stateTransformer: state => ({
				...state,
				courses: {...state.courses, allCourses: '<omitted>'},
			}),
		})
		middleware.push(logger)
	}

	return createStore(aao, applyMiddleware(...middleware))
}
<commit_msg>add exported function return annotation to redux<commit_after>// @flow

import {createStore, applyMiddleware, combineReducers, type Store} from 'redux'
import {createLogger} from 'redux-logger'
import reduxPromise from 'redux-promise'
import reduxThunk from 'redux-thunk'

import {homescreen, type State as HomescreenState} from './parts/homescreen'
import {settings, type State as SettingsState} from './parts/settings'
import {buildings, type State as BuildingsState} from './parts/buildings'
import {help, type State as HelpState} from './parts/help'
import {courses, type State as CoursesState} from './parts/courses'
import {stoprint, type State as StoPrintState} from './parts/stoprint'
import {
	notifications,
	type State as NotificationsState,
} from './parts/notifications'
import {login, type State as LoginState} from './parts/login'

export {init as initRedux} from './init'

export type ReduxState = {
	courses?: CoursesState,
	homescreen?: HomescreenState,
	settings?: SettingsState,
	buildings?: BuildingsState,
	help?: HelpState,
	stoprint?: StoPrintState,
	notifications?: NotificationsState,
	login?: LoginState,
}

export function makeStore(): Store<*, *, *> {
	const aao = combineReducers({
		courses,
		homescreen,
		settings,
		buildings,
		help,
		stoprint,
		notifications,
		login,
	})

	const middleware = [reduxPromise, reduxThunk]

	if (__DEV__) {
		const logger = createLogger({
			collapsed: true,
			duration: true,
			// avoid logging the (large) course data state twice per action
			stateTransformer: state => ({
				...state,
				courses: {...state.courses, allCourses: '<omitted>'},
			}),
		})
		middleware.push(logger)
	}

	return createStore(aao, applyMiddleware(...middleware))
}
<|endoftext|>


<commit_before>
module.exports = function(grunt) {

    'use strict';

    var version;

    try {
        var git = require('git-rev-sync');
        version = git.short('..');
    } catch (err) {
        // pass
    }

    function data(url, forceUrl) {

        var server = grunt.option('server') || process.env.SUPERDESK_URL || url;
        var ws = grunt.option('ws') || process.env.SUPERDESK_WS_URL || 'ws://localhost:5100';
        var disableEditorToolbar = grunt.option('disableEditorToolbar');
        var defaultTimezone = grunt.option('defaultTimezone') || 'Europe/London';

        if (forceUrl) {
            server = url;
        }

        var config = {
            version: version || grunt.config.process('<%= pkg.version %>'),

            raven: {dsn: process.env.SUPERDESK_RAVEN_DSN || ''},
            server: {url: server, ws: ws},
            iframely: {key: process.env.IFRAMELY_KEY || ''},
            analytics: {
                piwik: {
                    url: process.env.PIWIK_URL || '',
                    id: process.env.PIWIK_SITE_ID || ''
                },
                ga: {
                    id: process.env.TRACKING_ID || ''
                }
            },
            editor: {disableEditorToolbar: disableEditorToolbar},
            defaultTimezone: defaultTimezone,
            //these are angular model formats, should be consistent throughout the application
            model: {
                dateformat: 'DD/MM/YYYY',
                timeformat: 'HH:mm:ss'
            },
            //view formats for datepickers/timepickers.
            //KEEP DEFAULTS DIFFERENT FROM MODEL (for testing purposes)
            view: {
                dateformat: process.env.VIEW_DATE_FORMAT || 'MM/DD/YYYY',
                timeformat: process.env.VIEW_TIME_FORMAT || 'HH:mm'
            }
        };

        return {data: {
            config: config,
            bower: 'bower_components',
            core: 'node_modules/superdesk-core/apps'
        }};
    }

    var files = {'<%= distDir %>/index.html': '<%= appDir %>/index.html'};

    return {
        mock: {
            options: data('http://localhost:5000/api', true),
            files: files
        },
        dev: {
            options: data('http://localhost:5000/api', true),
            files: {'index.html': '<%= appDir %>/index.html'}
        },
        travis: {
            options: data('http://localhost:5000/api'),
            files: files
        },
        test: {
            options: data('http://localhost:5000/api'),
            files: files
        },
        docs: {
            options: data('http://localhost:5000/api'),
            files: {'<%= distDir %>/docs.html': '<%= appDir %>/docs.html'}
        }
    };
};
<commit_msg>do not force localhost server<commit_after>
module.exports = function(grunt) {

    'use strict';

    var version;

    try {
        var git = require('git-rev-sync');
        version = git.short('..');
    } catch (err) {
        // pass
    }

    function data(url, forceUrl) {

        var server = grunt.option('server') || process.env.SUPERDESK_URL || url;
        var ws = grunt.option('ws') || process.env.SUPERDESK_WS_URL || 'ws://localhost:5100';
        var disableEditorToolbar = grunt.option('disableEditorToolbar');
        var defaultTimezone = grunt.option('defaultTimezone') || 'Europe/London';

        if (forceUrl) {
            server = url;
        }

        var config = {
            version: version || grunt.config.process('<%= pkg.version %>'),

            raven: {dsn: process.env.SUPERDESK_RAVEN_DSN || ''},
            server: {url: server, ws: ws},
            iframely: {key: process.env.IFRAMELY_KEY || ''},
            analytics: {
                piwik: {
                    url: process.env.PIWIK_URL || '',
                    id: process.env.PIWIK_SITE_ID || ''
                },
                ga: {
                    id: process.env.TRACKING_ID || ''
                }
            },
            editor: {disableEditorToolbar: disableEditorToolbar},
            defaultTimezone: defaultTimezone,
            //these are angular model formats, should be consistent throughout the application
            model: {
                dateformat: 'DD/MM/YYYY',
                timeformat: 'HH:mm:ss'
            },
            //view formats for datepickers/timepickers.
            //KEEP DEFAULTS DIFFERENT FROM MODEL (for testing purposes)
            view: {
                dateformat: process.env.VIEW_DATE_FORMAT || 'MM/DD/YYYY',
                timeformat: process.env.VIEW_TIME_FORMAT || 'HH:mm'
            }
        };

        return {data: {
            config: config,
            bower: 'bower_components',
            core: 'node_modules/superdesk-core/apps'
        }};
    }

    var files = {'<%= distDir %>/index.html': '<%= appDir %>/index.html'};

    return {
        mock: {
            options: data('http://localhost:5000/api', true),
            files: files
        },
        dev: {
            options: data('http://localhost:5000/api'),
            files: {'index.html': '<%= appDir %>/index.html'}
        },
        travis: {
            options: data('http://localhost:5000/api'),
            files: files
        },
        test: {
            options: data('http://localhost:5000/api'),
            files: files
        },
        docs: {
            options: data('http://localhost:5000/api'),
            files: {'<%= distDir %>/docs.html': '<%= appDir %>/docs.html'}
        }
    };
};
<|endoftext|>


<commit_before>(function() {
    // Use query param as search query
    var searchQuery = decodeURIComponent(window.location.href.split("?q=")[1]);

    // Initialize the search index
    var lunrIndex = lunr(function () {
        this.ref('url');
        this.field('title', {boost: 10});
        this.field('content');
    });

    // Add content from search blob to index
    function addContentToIndex() {
        for (var page in search_blob) {
            lunrIndex.add({
                url: page,
                title: search_blob[page].title,
                content: search_blob[page].content
            });
        }
    }

    function displaySearchHeading(query) {
        var heading = document.getElementById("searchHeading");
        heading.innerHTML = "Search results for: " + query;
    }

    // Get the raw search results
    function getRawSearchResults(query) {
        return lunrIndex.search(query);
    }

    // Try to find the end of a word on which to end the blurb
    function getResultBlurb(result_content) {
        var rangeForEndOfWord = result_content.substr(250, 275),
            endOfWordIndex = rangeForEndOfWord.indexOf(" ");

        return result_content.substr(0, 250 + endOfWordIndex);
    }

    function displaySearchResults(results) {
        var container = document.getElementById("searchResultsContainer"),
            ref, title;

        // Clear the loading text before inserting the results
        container.innerHTML = "";

        if (results.length) {
            for (var result in results) {
                ref = results[result].ref;

                if (ref !== "") {
                    // Some pages might not have a title set
                    title = search_blob[ref].title || '(No title)';
                    container.innerHTML += "" + title + "";
                    container.innerHTML += "
" + getResultBlurb(search_blob[ref].content) + "...

";
                }
            }
        } else {
            container.innerHTML += "
No results found.
";
        }
    }

    addContentToIndex();
    window.addEventListener("load", function () {
        displaySearchHeading(searchQuery);
        displaySearchResults(getRawSearchResults(searchQuery));
    });

})();
<commit_msg>[Security] Fix docs XSS vulnerability in search<commit_after>(function() {
    // Use query param as search query
    var searchQuery = decodeURIComponent(window.location.href.split("?q=")[1]);

    // Initialize the search index
    var lunrIndex = lunr(function () {
        this.ref('url');
        this.field('title', {boost: 10});
        this.field('content');
    });

    // Add content from search blob to index
    function addContentToIndex() {
        for (var page in search_blob) {
            lunrIndex.add({
                url: page,
                title: search_blob[page].title,
                content: search_blob[page].content
            });
        }
    }

    function displaySearchHeading(query) {
        var heading = document.getElementById("searchHeading");
        heading.textContent = "Search results for: " + query;
    }

    // Get the raw search results
    function getRawSearchResults(query) {
        return lunrIndex.search(query);
    }

    // Try to find the end of a word on which to end the blurb
    function getResultBlurb(result_content) {
        var rangeForEndOfWord = result_content.substr(250, 275),
            endOfWordIndex = rangeForEndOfWord.indexOf(" ");

        return result_content.substr(0, 250 + endOfWordIndex);
    }

    function displaySearchResults(results) {
        var container = document.getElementById("searchResultsContainer"),
            ref, title;

        // Clear the loading text before inserting the results
        container.innerHTML = "";

        if (results.length) {
            for (var result in results) {
                ref = results[result].ref;

                if (ref !== "") {
                    // Some pages might not have a title set
                    title = search_blob[ref].title || '(No title)';
                    container.innerHTML += "" + title + "";
                    container.innerHTML += "
" + getResultBlurb(search_blob[ref].content) + "...

";
                }
            }
        } else {
            container.innerHTML += "
No results found.
";
        }
    }

    addContentToIndex();
    window.addEventListener("load", function () {
        displaySearchHeading(searchQuery);
        displaySearchResults(getRawSearchResults(searchQuery));
    });

})();
<|endoftext|>


<commit_before>/**
	_enyo.Repeater_ is a simple control for making lists of items.

	Components of a repeater are copied for each item created, and are wrapped
	in a control that keeps the state of the item index.

	Example:

		{kind: "Repeater", count: 2, onSetupItem: "setImageSource", components: [
			{kind: "Image"}
		]}

		setImageSource: function(inSender, inEvent) {
			var index = inEvent.index;
			var item = inEvent.item;
			item.$.image.setSrc(this.imageSources[index]);
			return true;
		}

	Be sure to return true from your _onSetupItem_ handler to avoid having other
	event handlers further up the tree try to modify your item control.

	The repeater will always be rebuilt after a call to _setCount_, even if the
	count didn't change.  This differs from the behavior of most properties, in
	which no action happens when a set-value call doesn't modify the value.
	This is to accomodate potential changes to the data model for the repeater,
	which may happen to have the same item count as before.
*/
enyo.kind({
	name: "enyo.Repeater",
	published: {
		//* Number of items
		count: 0
	},
	events: {
		//* Sends the item index, and the item control, for decoration.
		onSetupItem: ""
	},
	create: function() {
		this.inherited(arguments);
		this.countChanged();
	},
	//* @protected
	initComponents: function() {
		this.itemComponents = this.components || this.kindComponents;
		this.components = this.kindComponents = null;
		this.inherited(arguments);
	},
	setCount: function(inCount) {
		this.setPropertyValue("count", inCount, "countChanged");
	},
	countChanged: function() {
		this.build();
	},
	itemAtIndex: function(inIndex) {
		return this.controlAtIndex(inIndex);
	},
	//* @public
	//* Render the list
	build: function() {
		this.destroyClientControls();
		for (var i=0, c; i<this.count; i++) {
			c = this.createComponent({kind: "enyo.OwnerProxy", index: i});
			// do this as a second step so 'c' is the owner of the created components
			c.createComponents(this.itemComponents);
			// invoke user's setup code
			this.doSetupItem({index: i, item: c});
		}
		this.render();
	}
});

// Sometimes client controls are intermediated with null-controls.
// These overrides reroute events from such controls to the nominal delegate,
// as would happen in the absence of intermediation.
enyo.kind({
	name: "enyo.OwnerProxy",
	tag: null,
	decorateEvent: function(inEventName, inEvent, inSender) {
		if (inEvent) {
			inEvent.index = this.index;
		}
		this.inherited(arguments);
	},
	delegateEvent: function(inDelegate, inName, inEventName, inEvent, inSender) {
		if (inDelegate == this) {
			inDelegate = this.owner.owner;
		}
		this.inherited(arguments, [inDelegate, inName, inEventName, inEvent, inSender]);
	}
});<commit_msg>Add enyo.Repeater.renderRow API, update comment for enyo.Repeater.build<commit_after>/**
	_enyo.Repeater_ is a simple control for making lists of items.

	Components of a repeater are copied for each item created, and are wrapped
	in a control that keeps the state of the item index.

	Example:

		{kind: "Repeater", count: 2, onSetupItem: "setImageSource", components: [
			{kind: "Image"}
		]}

		setImageSource: function(inSender, inEvent) {
			var index = inEvent.index;
			var item = inEvent.item;
			item.$.image.setSrc(this.imageSources[index]);
			return true;
		}

	Be sure to return true from your _onSetupItem_ handler to avoid having other
	event handlers further up the tree try to modify your item control.

	The repeater will always be rebuilt after a call to _setCount_, even if the
	count didn't change.  This differs from the behavior of most properties, in
	which no action happens when a set-value call doesn't modify the value.
	This is to accomodate potential changes to the data model for the repeater,
	which may happen to have the same item count as before.
*/
enyo.kind({
	name: "enyo.Repeater",
	published: {
		//* Number of items
		count: 0
	},
	events: {
		//* Sends the item index, and the item control, for decoration.
		onSetupItem: ""
	},
	create: function() {
		this.inherited(arguments);
		this.countChanged();
	},
	//* @protected
	initComponents: function() {
		this.itemComponents = this.components || this.kindComponents;
		this.components = this.kindComponents = null;
		this.inherited(arguments);
	},
	setCount: function(inCount) {
		this.setPropertyValue("count", inCount, "countChanged");
	},
	countChanged: function() {
		this.build();
	},
	itemAtIndex: function(inIndex) {
		return this.controlAtIndex(inIndex);
	},
	//* @public
	/** Render the collection of items. This will delete any existing items and recreate
		the repeater if called after the repeater has been rendered.  This is called for
		you automatically if _setCount_ is called, even if the count remains the same. */
	build: function() {
		this.destroyClientControls();
		for (var i=0, c; i<this.count; i++) {
			c = this.createComponent({kind: "enyo.OwnerProxy", index: i});
			// do this as a second step so 'c' is the owner of the created components
			c.createComponents(this.itemComponents);
			// invoke user's setup code
			this.doSetupItem({index: i, item: c});
		}
		this.render();
	},
	/** Render a specific item in the collection.  This does not destroy the item, but
		just calls the _onSetupItem_ event handler again for it, so any state stored in
		the item is preserved. */
	renderRow: function(inIndex) {
		var c = this.itemAtIndex(inIndex);
		this.doSetupItem({index: inIndex, item: c});
	}
});

// Sometimes client controls are intermediated with null-controls.
// These overrides reroute events from such controls to the nominal delegate,
// as would happen in the absence of intermediation.
enyo.kind({
	name: "enyo.OwnerProxy",
	tag: null,
	decorateEvent: function(inEventName, inEvent, inSender) {
		if (inEvent) {
			inEvent.index = this.index;
		}
		this.inherited(arguments);
	},
	delegateEvent: function(inDelegate, inName, inEventName, inEvent, inSender) {
		if (inDelegate == this) {
			inDelegate = this.owner.owner;
		}
		this.inherited(arguments, [inDelegate, inName, inEventName, inEvent, inSender]);
	}
});<|endoftext|>


<commit_before>// Based on Alex Arnell's inheritance implementation.
// --------------------------------------------------

var Class = (function() {
	function Subclass() {
	}
	function create() {
		var parent, properties, id;
		id = -1;
		parent = null;
		properties = toArray(arguments);
		if (typeOf(properties[0]) === 'function') {
			parent = properties.shift();
		}
		function Caste() {
			if (typeOf(this.initialize) === 'function') {
				this.initialize.apply(this, arguments);
			}
		}
		apply(Caste, Class.Methods);
		Caste.superclass = parent;
		Caste.subclasses = [];
		if (parent) {
			Subclass.prototype = parent.prototype;
			Caste.prototype = new Subclass();
			parent.subclasses.push(Caste);
		}
		while (++id < properties.length) {
			Caste.implement(properties[id]);
		}
		if (!typeOf(Caste.prototype.initialize)) {
			Caste.prototype.initialize = Ctor;
		}
		Caste.prototype.constructor = Caste;
		return Caste;
	}
	function implement(source) {
		var ancestor, properties, id, property, value, method;
		ancestor = this.superclass && this.superclass.prototype;
		properties = Object.keys(source);
		id = -1;
		if (IS_DONTENUM_BUGGY) {
			if (source.toString != Object.prototype.toString) {
				properties.push('toString');
			}
			if (source.valueOf != Object.prototype.valueOf) {
				properties.push('valueOf');
			}
		}
		while (++id < properties.length) {
			property = properties[id];
			value = source[property];
			if (ancestor && typeOf(value) === 'function' && (/\$super/g.test(value.argumentNames()[0]))) {
				method = value;
				value = function (fn) {
					return function () {
						return ancestor[fn].apply(this, arguments);
					};
				}(property).wrap(method);
				value.valueOf = function (method) {
					return function () {
						return method.valueOf.call(method);
					};
				}(method);
				value.toString = function (method) {
					return function () {
						return method.toString.call(method);
					};
				}(method);
			}
			this.prototype[property] = value;
		}
		return this;
	}
	return {
		create: create,
		Methods: {
			extend: apply,
			implement: implement
		}
	};
}());

// Static methods
Class.getDefinitionName = getDefinitionName;
Class.typeOf = typeOf;
Class.uniqueId = uniqueId;
Class.bind = bindFn;
Class.bindAll = bindAll;
Class.isObject = isObject;
Class.isString = isString;
Class.isNumber = isNumber;
Class.isUint = isUint;
Class.isInt = isInt;
Class.isDate = isDate;
Class.isArray = isArray;
Class.isArrayLike = isArrayLike;
Class.isFunction = isFunction;
Class.isRegExp = isRegExp;
Class.isBoolean = isBoolean;
Class.isElement = isElement;
Class.isFile = isFile;
Class.isWindow = isWindow;
Class.toFloat = toFloat;
Class.toUint = toUint;
Class.toArray = toArray;
Class.toInt = toInt;

// Expose Class identifier, even in AMD
// and CommonJS for browser emulators
if (typeof noGlobal === strundefined) {
	window.Class = Class;
}

return Class;
<commit_msg>Update Class.js<commit_after>// Based on Alex Arnell's inheritance implementation.
// --------------------------------------------------

var Class = (function() {
	function Subclass() {
	}
	function create() {
		var parent, properties, id;
		id = -1;
		parent = null;
		properties = toArray(arguments);
		if (typeOf(properties[0]) === 'function') {
			parent = properties.shift();
		}
		function Caste() {
			if (typeOf(this.initialize) === 'function') {
				this.initialize.apply(this, arguments);
			}
		}
		apply(Caste, Class.Methods);
		Caste.superclass = parent;
		Caste.subclasses = [];
		if (parent) {
			Subclass.prototype = parent.prototype;
			Caste.prototype = new Subclass();
			parent.subclasses.push(Caste);
		}
		while (++id < properties.length) {
			Caste.implement(properties[id]);
		}
		if (!typeOf(Caste.prototype.initialize)) {
			Caste.prototype.initialize = Ctor;
		}
		Caste.prototype.constructor = Caste;
		return Caste;
	}
	function implement(source) {
		var ancestor, properties, id, property, value, method;
		ancestor = this.superclass && this.superclass.prototype;
		properties = Object.keys(source);
		id = -1;
		if (IS_DONTENUM_BUGGY) {
			if (source.toString != Object.prototype.toString) {
				properties.push('toString');
			}
			if (source.valueOf != Object.prototype.valueOf) {
				properties.push('valueOf');
			}
		}
		while (++id < properties.length) {
			property = properties[id];
			value = source[property];
			if (ancestor && typeOf(value) === 'function' && (/\$super/g.test(value.argumentNames()[0]))) {
				method = value;
				value = function (fn) {
					return function () {
						return ancestor[fn].apply(this, arguments);
					};
				}(property).wrap(method);
				value.valueOf = function (method) {
					return function () {
						return method.valueOf.call(method);
					};
				}(method);
				value.toString = function (method) {
					return function () {
						return method.toString.call(method);
					};
				}(method);
			}
			this.prototype[property] = value;
		}
		return this;
	}
	return {
		create: create,
		Methods: {
			extend: apply,
			implement: implement
		}
	};
}());

// Static methods
Class.getDefinitionName = getDefinitionName;
Class.typeOf = typeOf;
Class.uniqueId = uniqueId;
Class.bind = bindFn;
Class.bindAll = bindAll;
Class.isObject = isObject;
Class.isEmptyObject = isEmptyObject;
Class.isString = isString;
Class.isNumber = isNumber;
Class.isUint = isUint;
Class.isInt = isInt;
Class.isDate = isDate;
Class.isArray = isArray;
Class.isArrayLike = isArrayLike;
Class.isFunction = isFunction;
Class.isRegExp = isRegExp;
Class.isBoolean = isBoolean;
Class.isElement = isElement;
Class.isFile = isFile;
Class.isWindow = isWindow;
Class.toFloat = toFloat;
Class.toUint = toUint;
Class.toArray = toArray;
Class.toInt = toInt;

// Expose Class identifier, even in AMD
// and CommonJS for browser emulators
if (typeof noGlobal === strundefined) {
	window.Class = Class;
}

return Class;
<|endoftext|>


<commit_before>'use strict';

/**
 * Parses a string-based equation into a tree of operands &
 * an array of numbers and/or Equation instances.
 *
 * For example, the equation 5*3-(2+1*0.5)-1%3 becomes
 *
 *               5*3-(2+1*0.5)-1%3
 *                     |
 *                     -
 *               /     |       \
 *            5*3   2+1*0.5    1%3
 *             |       |         \
 *             -       +          %
 *           /  \    /  \        / \
 *          5   3   2  1*0.5    1   3
 *                       |
 *                       *
 *                      / \
 *                     1  0.5
 *
 * where an operand node & its immediate children (sub-equations) form an Equation.
 *
 */

var Equation = require('./Equation');
var SO = Equation.SUPPORTED_OPERANDS;

function EquationParser() {}

/**
 * Checks if the parentheses of the given equation are balanced.
 * @param  {String}  equationStr
 * @return {Boolean}             False if inbalanced, otherwise true
 */
function hasBalancedParentheses (equationStr) {

  // Check for odd number of parentheses
  if(equationStr.replace(/[^\(\)]/g, '').split('').length % 2) {
    return false;
  }

  var parentheses = 0, i;
  for (i = equationStr.length; i--;) {
    if (equationStr[i] === ')') { parentheses--; }
    else if (equationStr[i] === '(') { parentheses++; }
    if (parentheses === 1) { return false; }
  }

  return true;
}

/**
 * Validates a given equation string by checking if it
 *   - is missing operands [ e.g. 1+1(2+2) ]
 *   - uses decimal point incorrectly [ e.g. +.- or ).( ]
 *   - has unbalanced parentheses [ e.g (1+1)+(2*5-1)) ]
 *   - has two or more consecutive operands [ e.g. 1++1 ]
 *   - contains characters that are not numbers, decimal points, parentheses or operands
 *
 * @param  {String} equationStr
 * @throws {Error}  Throws an Error if the input is invalid
 *
 * @todo  Check if parentheses are in balance
 */
function validateEquation(equationStr) {

  var invalidCharsRegexStr = '[^\\d\\.\\(\\)\\' + SO.ternary.join('\\') + SO.unary.join('') + ']';
  var consecutiveOperandsRegexStr = '[\\' + SO.ternary.join('\\') + ']{2,}';
  var invalidCharsRegex = new RegExp(invalidCharsRegexStr);
  var consecutiveOperandsRegex = new RegExp(consecutiveOperandsRegexStr);

  if (/\)\(/.test(equationStr)) {
    throw new Error('Missing an operand.');
  }

  if (/\D\.\D/.test(equationStr)) {
    throw new Error('Invalid use of the decimal point.');
  }

  if (!hasBalancedParentheses(equationStr)) {
    throw new Error('Parentheses are not in balance.');
  }

  if (consecutiveOperandsRegex.test(equationStr)) {
    throw new Error('Consecutive ternary operands detected.');
  }

  if (invalidCharsRegex.test(equationStr)) {
    throw new Error('The equation contains invalid characters. Supported operands: ' + SO);
  }

}

/**
 * Sanitizes/normalizes the equation string:
 *   - convert to lowercase
 *   - strip whitespace
 *   - strip repeating operands
 *   - pad decimal points with leading/trailing zeros
 *
 * @param  {String} equationStr The equation
 * @return {String}             A sanitized equation
 */
function sanitizeEquation(equationStr) {

  var repeatingCharsRegex = new RegExp('([\\.\\' + SO.ternary.join('\\') + SO.unary.join('') + '])(?=\\1+)', 'g');
  var trailingLeadingOperands = new RegExp('^[\\' + SO.ternary.join('\\') + ']+|[\\' + SO.ternary.join('\\') + SO.unary.join('') + ']+$', 'g');

  return equationStr
    .toLowerCase()
    // Strip whitespace
    .replace(/\s+/g, '')
    // Strip repeating operands and decimal points (e.g. 1+++2 => 1+2)
    .replace(repeatingCharsRegex, '')
    // Strip leading/trailing ternary and unary operands (+1+2+abs => 1+2)
    .replace(trailingLeadingOperands, '')
    // Pad decimal points with zeros (leading & trailing)
    .replace(/(\D)\.(\d)/g, function (m, p1, p2) { return p1 + '0.' + p2; })
    .replace(/(\d)\.(\D)/g, function (m, p1, p2) { return p1 + '.0' + p2; });

}

/**
 * Checks if a given equation string is surrounded by parentheses
 * @param  {String}  equationStr
 * @return {Boolean}             True if the equation string is surrounded by parentheses,
 *                               false otherwise
 */
function hasSurroundingParens (equationStr) {

  var length = equationStr.length;
  var parentheses = -1;
  var idx, char;

  if (equationStr[0] !== '(' || equationStr[length - 1] !== ')') { return false; }

  // Loop through the characters from right to left and return false
  // if we hit an opening parentheses that matches the surrounding closing parentheses
  // before we have reached the last character
  for (idx = length - 1; idx--;) {
    char = equationStr[idx];
    if (char === '(') { parentheses++; }
    else if (char === ')') { parentheses--; }
    if (!parentheses && idx) { return false; }
  }

  return true;
}

/**
 * Split the equation string by operand (parentheses aware).
 * Uses String.split() if the equation contains no parentheses.
 * @param  {String} equationStr  e.g. 1+1
 * @param  {String} operand      e.g. +
 * @return {Array}               An array of subequation strings
 */
function split(equationStr, operand) {

  // Return immediately if the given operand doesn't exist
  if (equationStr.indexOf(operand) === -1) { return [ equationStr ]; }

  // Use String.split() if the equation string contains no parentheses
  if (!/\(|\)/.test(equationStr)) {
    return equationStr.split(operand);
  }

  var parentheses = 0;
  var subEquationStrings = [];
  var cBegin, cEnd, char;

  // Loop through the characters from right to left and split the
  // equation string into subequation string if the given operand
  // is not located within parentheses
  for (cBegin = cEnd = equationStr.length; cBegin--;) {

    char = equationStr[cBegin];

    if (char === '(') { parentheses++; }
    else if (char === ')') { parentheses--; }
    else if (char === operand && !parentheses) {
      subEquationStrings.unshift(equationStr.substring(cBegin + 1, cEnd));
      cEnd = cBegin;
    }

  }

  subEquationStrings.unshift(equationStr.substring(0, cEnd));

  return subEquationStrings;
}

/**
 * Parses the string representation of an equation into an Equation instance
 * consisting of one or more Equation instances.
 *
 * @param  {String} equationStr A string representation of an equation
 * @param  {Array} operands     An array of operands to process (defaults to SO)
 * @return {Equation}           An Equation instance
 */
function parseEquation(equationStr, operands) {

  equationStr = equationStr || '0';

  if (!isNaN(equationStr)) {
    return new Equation(equationStr);
  }

  if (hasSurroundingParens(equationStr)) {

    // Strip surrounding parentheses and call parseEquation again
    return parseEquation(equationStr.replace(/^\(|\)$/g, ''));

  }

  /* jshint validthis:true */

  var subEquationStrings, subequations, operand;

  operands = operands ? operands.slice() : SO.slice();

  // Try splitting the equation into sub-equations using each of the supported operands
  while ((operand = operands.shift()) !== undefined) {
    subEquationStrings = split(equationStr, operand);
    if (subEquationStrings.length > 1) { break; }
  }

  // Unary operands are one-sided assignments so drop split's first entry (which is '')
  if (Equation.isUnaryOperand(operand)) { subEquationStrings.shift(); }

  // Iterate over the sub-equations and call parseEquation recursively
  subequations = subEquationStrings.map(function (subEquationStr) {
    return parseEquation(subEquationStr, operands);
  });

  return new Equation(subequations, operand);

}

/**
 * An overload of parseEquation().
 * Sanitizes & validates the input before passing it to parseEquation().
 *
 * @param  {String}  equationStr             A string representation of an equation
 * @param  {Object}  [options]
 * @param  {Boolean} [options.skipSanitize]  Boolean to control input sanitization (default: false)
 * @param  {Boolean} [options.skipValidate]  Boolean to control input validation (default: false)
 * @return {Equation}                        An Equation instance
 *
 * @see  parseEquation()
 */
EquationParser.prototype.parseEquation = function (equationStr, options) {

  options = options || {};

  // Alias unary operands for faster matching: sqrt => s, abs => a
  equationStr = equationStr.replace(/(s)qrt|(a)bs/gi, '$1$2');

  // Sanitize
  if (!options.skipSanitize) { equationStr = sanitizeEquation(equationStr); }

  // Validate
  if (!options.skipValidate) { validateEquation(equationStr); }

  // Parse
  return parseEquation(equationStr);

};

module.exports = EquationParser;
<commit_msg>Nitpicking: use bitwise AND instead of modulo<commit_after>'use strict';

/**
 * Parses a string-based equation into a tree of operands &
 * an array of numbers and/or Equation instances.
 *
 * For example, the equation 5*3-(2+1*0.5)-1%3 becomes
 *
 *               5*3-(2+1*0.5)-1%3
 *                     |
 *                     -
 *               /     |       \
 *            5*3   2+1*0.5    1%3
 *             |       |         \
 *             -       +          %
 *           /  \    /  \        / \
 *          5   3   2  1*0.5    1   3
 *                       |
 *                       *
 *                      / \
 *                     1  0.5
 *
 * where an operand node & its immediate children (sub-equations) form an Equation.
 *
 */

var Equation = require('./Equation');
var SO = Equation.SUPPORTED_OPERANDS;

function EquationParser() {}

/**
 * Checks if the parentheses of the given equation are balanced.
 * @param  {String}  equationStr
 * @return {Boolean}             False if inbalanced, otherwise true
 */
function hasBalancedParentheses (equationStr) {

  // Check for odd number of parentheses
  /* jslint bitwise: true */
  if(equationStr.replace(/[^\(\)]/g, '').split('').length & 1) {
    return false;
  }
  /* jslint bitwise: false */

  var parentheses = 0, i;
  for (i = equationStr.length; i--;) {
    if (equationStr[i] === ')') { parentheses--; }
    else if (equationStr[i] === '(') { parentheses++; }
    if (parentheses === 1) { return false; }
  }

  return true;
}

/**
 * Validates a given equation string by checking if it
 *   - is missing operands [ e.g. 1+1(2+2) ]
 *   - uses decimal point incorrectly [ e.g. +.- or ).( ]
 *   - has unbalanced parentheses [ e.g (1+1)+(2*5-1)) ]
 *   - has two or more consecutive operands [ e.g. 1++1 ]
 *   - contains characters that are not numbers, decimal points, parentheses or operands
 *
 * @param  {String} equationStr
 * @throws {Error}  Throws an Error if the input is invalid
 *
 * @todo  Check if parentheses are in balance
 */
function validateEquation(equationStr) {

  var invalidCharsRegexStr = '[^\\d\\.\\(\\)\\' + SO.ternary.join('\\') + SO.unary.join('') + ']';
  var consecutiveOperandsRegexStr = '[\\' + SO.ternary.join('\\') + ']{2,}';
  var invalidCharsRegex = new RegExp(invalidCharsRegexStr);
  var consecutiveOperandsRegex = new RegExp(consecutiveOperandsRegexStr);

  if (/\)\(/.test(equationStr)) {
    throw new Error('Missing an operand.');
  }

  if (/\D\.\D/.test(equationStr)) {
    throw new Error('Invalid use of the decimal point.');
  }

  if (!hasBalancedParentheses(equationStr)) {
    throw new Error('Parentheses are not in balance.');
  }

  if (consecutiveOperandsRegex.test(equationStr)) {
    throw new Error('Consecutive ternary operands detected.');
  }

  if (invalidCharsRegex.test(equationStr)) {
    throw new Error('The equation contains invalid characters. Supported operands: ' + SO);
  }

}

/**
 * Sanitizes/normalizes the equation string:
 *   - convert to lowercase
 *   - strip whitespace
 *   - strip repeating operands
 *   - pad decimal points with leading/trailing zeros
 *
 * @param  {String} equationStr The equation
 * @return {String}             A sanitized equation
 */
function sanitizeEquation(equationStr) {

  var repeatingCharsRegex = new RegExp('([\\.\\' + SO.ternary.join('\\') + SO.unary.join('') + '])(?=\\1+)', 'g');
  var trailingLeadingOperands = new RegExp('^[\\' + SO.ternary.join('\\') + ']+|[\\' + SO.ternary.join('\\') + SO.unary.join('') + ']+$', 'g');

  return equationStr
    .toLowerCase()
    // Strip whitespace
    .replace(/\s+/g, '')
    // Strip repeating operands and decimal points (e.g. 1+++2 => 1+2)
    .replace(repeatingCharsRegex, '')
    // Strip leading/trailing ternary and unary operands (+1+2+abs => 1+2)
    .replace(trailingLeadingOperands, '')
    // Pad decimal points with zeros (leading & trailing)
    .replace(/(\D)\.(\d)/g, function (m, p1, p2) { return p1 + '0.' + p2; })
    .replace(/(\d)\.(\D)/g, function (m, p1, p2) { return p1 + '.0' + p2; });

}

/**
 * Checks if a given equation string is surrounded by parentheses
 * @param  {String}  equationStr
 * @return {Boolean}             True if the equation string is surrounded by parentheses,
 *                               false otherwise
 */
function hasSurroundingParens (equationStr) {

  var length = equationStr.length;
  var parentheses = -1;
  var idx, char;

  if (equationStr[0] !== '(' || equationStr[length - 1] !== ')') { return false; }

  // Loop through the characters from right to left and return false
  // if we hit an opening parentheses that matches the surrounding closing parentheses
  // before we have reached the last character
  for (idx = length - 1; idx--;) {
    char = equationStr[idx];
    if (char === '(') { parentheses++; }
    else if (char === ')') { parentheses--; }
    if (!parentheses && idx) { return false; }
  }

  return true;
}

/**
 * Split the equation string by operand (parentheses aware).
 * Uses String.split() if the equation contains no parentheses.
 * @param  {String} equationStr  e.g. 1+1
 * @param  {String} operand      e.g. +
 * @return {Array}               An array of subequation strings
 */
function split(equationStr, operand) {

  // Return immediately if the given operand doesn't exist
  if (equationStr.indexOf(operand) === -1) { return [ equationStr ]; }

  // Use String.split() if the equation string contains no parentheses
  if (!/\(|\)/.test(equationStr)) {
    return equationStr.split(operand);
  }

  var parentheses = 0;
  var subEquationStrings = [];
  var cBegin, cEnd, char;

  // Loop through the characters from right to left and split the
  // equation string into subequation string if the given operand
  // is not located within parentheses
  for (cBegin = cEnd = equationStr.length; cBegin--;) {

    char = equationStr[cBegin];

    if (char === '(') { parentheses++; }
    else if (char === ')') { parentheses--; }
    else if (char === operand && !parentheses) {
      subEquationStrings.unshift(equationStr.substring(cBegin + 1, cEnd));
      cEnd = cBegin;
    }

  }

  subEquationStrings.unshift(equationStr.substring(0, cEnd));

  return subEquationStrings;
}

/**
 * Parses the string representation of an equation into an Equation instance
 * consisting of one or more Equation instances.
 *
 * @param  {String} equationStr A string representation of an equation
 * @param  {Array} operands     An array of operands to process (defaults to SO)
 * @return {Equation}           An Equation instance
 */
function parseEquation(equationStr, operands) {

  equationStr = equationStr || '0';

  if (!isNaN(equationStr)) {
    return new Equation(equationStr);
  }

  if (hasSurroundingParens(equationStr)) {

    // Strip surrounding parentheses and call parseEquation again
    return parseEquation(equationStr.replace(/^\(|\)$/g, ''));

  }

  /* jshint validthis:true */

  var subEquationStrings, subequations, operand;

  operands = operands ? operands.slice() : SO.slice();

  // Try splitting the equation into sub-equations using each of the supported operands
  while ((operand = operands.shift()) !== undefined) {
    subEquationStrings = split(equationStr, operand);
    if (subEquationStrings.length > 1) { break; }
  }

  // Unary operands are one-sided assignments so drop split's first entry (which is '')
  if (Equation.isUnaryOperand(operand)) { subEquationStrings.shift(); }

  // Iterate over the sub-equations and call parseEquation recursively
  subequations = subEquationStrings.map(function (subEquationStr) {
    return parseEquation(subEquationStr, operands);
  });

  return new Equation(subequations, operand);

}

/**
 * An overload of parseEquation().
 * Sanitizes & validates the input before passing it to parseEquation().
 *
 * @param  {String}  equationStr             A string representation of an equation
 * @param  {Object}  [options]
 * @param  {Boolean} [options.skipSanitize]  Boolean to control input sanitization (default: false)
 * @param  {Boolean} [options.skipValidate]  Boolean to control input validation (default: false)
 * @return {Equation}                        An Equation instance
 *
 * @see  parseEquation()
 */
EquationParser.prototype.parseEquation = function (equationStr, options) {

  options = options || {};

  // Alias unary operands for faster matching: sqrt => s, abs => a
  equationStr = equationStr.replace(/(s)qrt|(a)bs/gi, '$1$2');

  // Sanitize
  if (!options.skipSanitize) { equationStr = sanitizeEquation(equationStr); }

  // Validate
  if (!options.skipValidate) { validateEquation(equationStr); }

  // Parse
  return parseEquation(equationStr);

};

module.exports = EquationParser;
<|endoftext|>


<commit_before>/*

    Copyright (c) Charlie Tiehm

    Filename: twitch   | Created at: 30. Aug

*/

const twitchClass = require('../classes/twitch.js');
const twitch = new twitchClass(config.CLIENTID);

let check = async (bot) => {

    let rows = await r.table('livestreams').run();
    /*
    rows returns an array
    */
    for (let row of rows) {
        /*
        get one server
         */
        if (row.streams) {
            for (let a of row.livestreams) {
                /*
                get every stream from one server
                 */
                twitch.check(a.name).then(data => {
                    console.log(data);
                    let p =  row.livestreams;
                    function findInd(element) {
                        return element.name === data.name;
                    }
                    let toInsert = data.online ? {
                        game: data.game,
                        views: data.views,
                        image: data.image,
                        mature: data.mature,
                        lang: data.lang,
                        name: data.name,
                        url: data.url,
                        msgID: null,
                        online: true
                    } : {online: false, name: data.name};

                    let appendToArray = (table, uArray, doc) => r.table(table)
                        .filter({guildID : msg.guild.id})
                        .update(object => ({ [uArray]: object(uArray)
                            .default([]).changeAt(p.findIndex(findInd), toInsert) }))
                        .run();
                    appendToArray('livestreams', 'livestreams')
                })
            }
        }
    }

};

module.exports = check;<commit_msg>Removed stupid copyright tag<commit_after>
const twitchClass = require('../classes/twitch.js');
const twitch = new twitchClass(config.CLIENTID);

let check = async (bot) => {

    let rows = await r.table('livestreams').run();
    /*
    rows returns an array
    */
    for (let row of rows) {
        /*
        get one server
         */
        if (row.streams) {
            for (let a of row.livestreams) {
                /*
                get every stream from one server
                 */
                twitch.check(a.name).then(data => {
                    console.log(data);
                    let p =  row.livestreams;
                    function findInd(element) {
                        return element.name === data.name;
                    }
                    let toInsert = data.online ? {
                        game: data.game,
                        views: data.views,
                        image: data.image,
                        mature: data.mature,
                        lang: data.lang,
                        name: data.name,
                        url: data.url,
                        msgID: null,
                        online: true
                    } : {online: false, name: data.name};

                    let appendToArray = (table, uArray, doc) => r.table(table)
                        .filter({guildID : msg.guild.id})
                        .update(object => ({ [uArray]: object(uArray)
                            .default([]).changeAt(p.findIndex(findInd), toInsert) }))
                        .run();
                    appendToArray('livestreams', 'livestreams')
                })
            }
        }
    }

};

module.exports = check;
<|endoftext|>


<commit_before>var app;
var specialApps = {
    "allApps" : "allApps",
    "publish" : "publish",
    "viewAll" : "viewAll",
    "exploreApps" : "exploreApps",
    "registryApp" : "registryApp"
};

var iframeLoaded = function() {};

$(document).ready(function() {
  app = window.location.hash.substring(1) || $('.installed-apps a').data('id') || 'contactsviewer';
  loadApp();

  $('.iframeLink').click(function() {
    app = $(this).data('id');
    loadApp();
    return false;
  });

  $('.oauthLink').click(function() {
    var popup = window.open($(this).attr('href'), "account", "width=" + $(this).data('width') + ",height=" + $(this).data('height') + ",status=no,scrollbars=no,resizable=no");
    popup.focus();
    return false;
  });

  $('.your-apps').click(function() {
    $('.blue').removeClass('blue');
    $(this).addClass('blue');
    if (document.getElementById('appFrame').contentWindow.filterItems) {
      document.getElementById('appFrame').contentWindow.filterItems($(this).attr('id'));
    }
    $('.sidenav-items input').attr('checked', false)
  });

  $('.sidenav-items input').click(function() {
    var checked = $('.sidenav-items input:checked');
    if (checked.length == 0) {
      $('.your-apps').click();
    } else {
      $('.your-apps').removeClass('blue');
      app = "exploreApps&filter";
      var types = [];
      var services = [];
      $('#types').find(checked).each(function(i, elem) {
        app += "&types[]=" + $(elem).attr('id');
      });
      $('#services').find(checked).each(function(i, elem) {
        app += "&services[]=" + $(elem).attr('id');
      });
      loadApp();
    }
  });
});

var loadApp = function(callback) {
  var appUrl = app;
  var params = '';
  if (app.indexOf('&') != -1) {
    appUrl = app.substring(0, app.indexOf('&'));
    params = app.substring(app.indexOf('&') + 1);
  }
  if (callback) {
    iframeLoaded = callback;
  } else {
    iframeLoaded = function() {};
  }
  $('.app-details').hide();
  $('.iframeLink,.your-apps').removeClass('blue');
  window.location.hash = app;
  if (specialApps[appUrl]) {
    $("#appFrame")[0].contentWindow.location.replace(specialApps[appUrl] + '?params=' + params);
  } else {
    $.get('clickapp/' + appUrl, function(e) {});
    $("#appFrame")[0].contentWindow.location.replace('/Me/' + appUrl);
  }
  $('.iframeLink[data-id="' + app + '"]').addClass('blue').parent('p').siblings().show();
  if (params.indexOf('filter') === 0) {
    var boxes = params.split('&');
    for (var i = 0; i < boxes.length; i++) {
      var item = boxes[i].split('=');
      if (item.length > 1) {
        $('#' + item[1]).attr('checked', true);
      }
    }
  }
};

var syncletInstalled = function(provider) {
  if (provider === 'github') {
    $('.your-apps').show();
  }
  var link = $('.oauthLink[data-provider="' + provider + '"]');
  link.children('img').addClass('installed').appendTo('.sidenav-items.synclets');
  link.remove();
};
<commit_msg>ensure all the checkboxes are unchecked when on the featured page<commit_after>var app;
var specialApps = {
    "allApps" : "allApps",
    "publish" : "publish",
    "viewAll" : "viewAll",
    "exploreApps" : "exploreApps",
    "registryApp" : "registryApp"
};

var iframeLoaded = function() {};

$(document).ready(function() {
  app = window.location.hash.substring(1) || $('.installed-apps a').data('id') || 'contactsviewer';
  loadApp();

  $('.iframeLink').click(function() {
    app = $(this).data('id');
    loadApp();
    return false;
  });

  $('.oauthLink').click(function() {
    var popup = window.open($(this).attr('href'), "account", "width=" + $(this).data('width') + ",height=" + $(this).data('height') + ",status=no,scrollbars=no,resizable=no");
    popup.focus();
    return false;
  });

  $('.your-apps').click(function() {
    $('.blue').removeClass('blue');
    $(this).addClass('blue');
    if (document.getElementById('appFrame').contentWindow.filterItems) {
      document.getElementById('appFrame').contentWindow.filterItems($(this).attr('id'));
    }
  });

  $('.sidenav-items input').click(function() {
    var checked = $('.sidenav-items input:checked');
    if (checked.length == 0) {
      $('.your-apps').click();
    } else {
      $('.your-apps').removeClass('blue');
      app = "exploreApps&filter";
      var types = [];
      var services = [];
      $('#types').find(checked).each(function(i, elem) {
        app += "&types[]=" + $(elem).attr('id');
      });
      $('#services').find(checked).each(function(i, elem) {
        app += "&services[]=" + $(elem).attr('id');
      });
      loadApp();
    }
  });
});

var loadApp = function(callback) {
  var appUrl = app;
  var params = '';
  if (app.indexOf('&') != -1) {
    appUrl = app.substring(0, app.indexOf('&'));
    params = app.substring(app.indexOf('&') + 1);
  }
  if (callback) {
    iframeLoaded = callback;
  } else {
    iframeLoaded = function() {};
  }
  $('.app-details').hide();
  $('.iframeLink,.your-apps').removeClass('blue');
  window.location.hash = app;
  if (specialApps[appUrl]) {
    $("#appFrame")[0].contentWindow.location.replace(specialApps[appUrl] + '?params=' + params);
  } else {
    $.get('clickapp/' + appUrl, function(e) {});
    $("#appFrame")[0].contentWindow.location.replace('/Me/' + appUrl);
  }
  $('.iframeLink[data-id="' + app + '"]').addClass('blue').parent('p').siblings().show();
  $('.sidenav-items input').attr('checked', false)
  if (params.indexOf('filter') === 0) {
    var boxes = params.split('&');
    for (var i = 0; i < boxes.length; i++) {
      var item = boxes[i].split('=');
      if (item.length > 1) {
        $('#' + item[1]).attr('checked', true);
      }
    }
  }
};

var syncletInstalled = function(provider) {
  if (provider === 'github') {
    $('.your-apps').show();
  }
  var link = $('.oauthLink[data-provider="' + provider + '"]');
  link.children('img').addClass('installed').appendTo('.sidenav-items.synclets');
  link.remove();
};
<|endoftext|>


<commit_before>//
// var in_a = require("in-a-nutshell");
// YOUR_TEXT = "At the Twins, Arya fatally poisons the remaining lords of House Frey. The White Walkers march toward the Wall, where Tollett allows Bran and Meera inside. At Winterfell, despite Sansa's disapproval, Jon secures the loyalties of Houses Umber and Karstark, who fought alongside Ramsay in the Battle of the Bastards. At the Citadel, Samwell steals books that reveal a large reservoir of dragonglass in Dragonstone, and sends word to Jon. He later finds Jorah in a cell. In the Riverlands, Arya meets a group of friendly Lannister soldiers, who take her intention to kill Cersei as a joke. Thoros shows Sandor a vision in the fire. The revelation leads him to believe in the Lord of Light. In King's Landing, Jaime tells Cersei of the crucial need for allies. She welcomes Euron, who proposes marriage to her in exchange for his Iron Fleet and a chance to kill Theon and Yara. Cersei declines citing trust as a concern, so Euron promises to return with a 'gift' to prove his loyalty. Daenerys arrives at Dragonstone, the home of House Targaryen once occupied by Stannis, with her army and dragons. Daenerys sends the Dornishmen on Yara's fleet to Sunspear, the Unsullied to Casterly Rock and decides to not move on to King's Landing yet, intending to install a complete siege instead. She demands that Varys criticize her future mistakes instead of betraying her, which he did to previous monarchs. Melisandre arrives and encourages her to invite Jon Snow to Dragonstone. Grey Worm and Missandei consummate their relationship. Cersei gathers several lords, asking for their fealties and promising Randyll the title of Warden of the South. Qyburn shows Cersei an invented ballista for killing dragons. Arya meets with Hot Pie, who tells her of Jon's ascension to King in the North; she then decides to return to Winterfell. After receiving Samwell's letter, Jon leaves for Dragonstone in hopes of getting Daenerys's support against the White Walkers, leaving Sansa in charge and warning Littlefinger not to get close to her. Samwell begins a forbidden treatment for Jorah. Euron's fleet attacks Yara's. Obara and Nymeria are killed, while Ellaria, Tyene, and Yara are captured. Theon flees the carnage in horror by jumping into the sea. Jon arrives at Dragonstone, where Daenerys demands his fealty. Instead, he asks for help against the Army of the Dead; after advice from Tyrion, Daenerys grants them access to the dragonglass on the island. Melisandre leaves for Volantis. Bran arrives at Winterfell and explains some of his powers to Sansa. In King's Landing, Euron returns with Ellaria and Tyene as a gift for Cersei, who promises to marry him after the war. She then gives him co-control of her military along with Jaime. Cersei gives Tyene the same poison Ellaria used to kill Myrcella, forcing Ellaria to watch her daughter's oncoming death. In Oldtown, a healed Jorah leaves to find Daenerys. Ebrose decides to forgive Samwell. Grey Worm and the Unsullied attack Casterly Rock. However, it is revealed that Jaime took most of the Lannister forces to attack Highgarden, while Euron's fleet arrives destroying the Unsullied's ships. Jaime and the rest of the Lannister forces easily invade Highgarden. He gives Olenna poison as a quick and painless death. After drinking, she confesses to Joffrey's poisoning and demands he tell Cersei. Arya returns to Winterfell where she is reunited with Sansa and spars with Brienne, both of whom are unnerved by her exceptional fighting skills. Bran unemotionally bids farewell to Meera, divulging that he is no longer the boy she accompanied north. Littlefinger presents Bran with the dagger that was nearly used to assassinate him. Cersei promises the Iron Bank a full return on their investment, as a loot train from Highgarden is soon to arrive. Jon brings Daenerys to the dragonglass mine where he shows her ancient cave paintings depicting that the First Men and the Children of the Forest joined forces against the undead. Later, Daenerys learns that the Casterly Rock attack was a Lannister decoy, with Highgarden falling to the Lannisters. Despite Tyrion's protests, she decides to take action. Led by Daenerys riding Drogon and the Dothraki cavalry, Jaime and Bronn are caught by surprise while supervising the gold shipment, and the Dothrakis and Drogon's fire decimate the Lannister army. Drogon is wounded by a bolt from Bronn manning the scorpion weapon, and Jaime tries to attack Daenerys. Drogon launches his fire breath at Jaime, but Bronn tackles him into a river, where both are weighted down by their armor."
//
// var summary = in_a.nutshell(YOUR_TEXT, 15,'plaintext');
// console.log(summary);
//

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
    console.log(req.body.name);
    res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
    console.log('Server running at http://127.0.0.1:8080/');
});<commit_msg>Delete backup_smmry.js<commit_after><|endoftext|>


<commit_before>"use strict";

function FlutterManager() {
	let mgr = FlutterManager;
	mgr.connectedDevices = {};
	mgr.connectionStatus = 2;
	// 0 - At least 1 disconnected
	// 1 - Every device is OK
	// 2 - Nothing connected
	mgr.UpdateConnectionStatus();
}

FlutterManager.ShowDiscoverDialog = function() {
	DiscoverDialog.show(FlutterManager);
}

FlutterManager.GetDeviceName = function(shorten) {
	if (shorten) {
		return "F";
	} else {
		return "Flutter";
	}
}

FlutterManager.GetConnectionStatus = function() {
	return FlutterManager.connectionStatus;
}

FlutterManager.UpdateConnectionStatus = function() {
	HtmlServer.sendRequestWithCallback("flutter/totalStatus", function(result) {
		FlutterManager.connectionStatus = parseInt(result);
		if (isNaN(FlutterManager.connectionStatus)) {
			FlutterManager.connectionStatus = 0;
		}
	},function(){
		FlutterManager.connectionStatus = 0;
	});
}

FlutterManager.GetDeviceCount = function() {
	return Object.keys(FlutterManager.connectedDevices).length;
}

// TODO: Choose either GetDeviceByIndex or GetDeviceByName
FlutterManager.GetDeviceByIndex = function(index) {
	// This is a hack because a FIFO list of devices is not kept
	let devices = Object.keys(FlutterManager.connectedDevices).map(function(key) {
		return FlutterManager.connectedDevices[key];
	})
	return devices[index];
}

FlutterManager.GetConnectedDevices = function() {
	let devices = Object.keys(FlutterManager.connectedDevices).map(function(key) {
		return FlutterManager.connectedDevices[key];
	})
	return devices;
}

/**
 * Static function to discover flutter devices
 *
 * @param      {function}  successFn  Callback function called on successful
 *                                    discovery of devices
 * @param      {function}  errorFn    Callback function called on an error in
 *                                    device discovery
 */
FlutterManager.DiscoverDevices = function(successFn, errorFn) {
	HtmlServer.sendRequestWithCallback("flutter/discover", successFn, errorFn);
}

/**
 * Connects a device and adds it to a list of connected devices
 *
 * @param      {string}  deviceName  Name of the device to connect
 */
FlutterManager.ConnectDevice = function(deviceName) {
	FlutterManager.connectedDevices[deviceName] = new Flutter(deviceName);
	FlutterManager.connectedDevices[deviceName].connect();
	BlockPalette.getCategory("robots").refreshGroup();
	FlutterManager.UpdateConnectionStatus();
}

/**
 * Disconnects a device and removes it from a list of connected devices
 *
 * @param      {String}  deviceName  Name of the device to disconnect
 */
FlutterManager.DisconnectDevice = function(deviceName) {
	FlutterManager.connectedDevices[deviceName].disconnect();
	delete FlutterManager.connectedDevices[deviceName];
	BlockPalette.getCategory("robots").refreshGroup();
	FlutterManager.UpdateConnectionStatus();
}

/**
 * Gets a device by name
 *
 * @param      {string}  deviceName  The device name
 * @return     {Flutter}  The device by name.
 */
FlutterManager.GetDeviceByName = function(deviceName) {
	return FlutterManager.connectedDevices[deviceName];
}<commit_msg>Fixed status light updating for connect/disconnect of flutter<commit_after>"use strict";

function FlutterManager() {
	let mgr = FlutterManager;
	mgr.connectedDevices = {};
	mgr.connectionStatus = 2;
	// 0 - At least 1 disconnected
	// 1 - Every device is OK
	// 2 - Nothing connected
	mgr.UpdateConnectionStatus();
}

FlutterManager.ShowDiscoverDialog = function() {
	DiscoverDialog.show(FlutterManager);
}

FlutterManager.GetDeviceName = function(shorten) {
	if (shorten) {
		return "F";
	} else {
		return "Flutter";
	}
}

FlutterManager.GetConnectionStatus = function() {
	return FlutterManager.connectionStatus;
}

FlutterManager.UpdateConnectionStatus = function() {
	HtmlServer.sendRequestWithCallback("flutter/totalStatus", function(result) {
		FlutterManager.connectionStatus = parseInt(result);
		if (isNaN(FlutterManager.connectionStatus)) {
			FlutterManager.connectionStatus = 0;
		}
	},function(){
		FlutterManager.connectionStatus = 0;
	});
}

FlutterManager.GetDeviceCount = function() {
	return Object.keys(FlutterManager.connectedDevices).length;
}

// TODO: Choose either GetDeviceByIndex or GetDeviceByName
FlutterManager.GetDeviceByIndex = function(index) {
	// This is a hack because a FIFO list of devices is not kept
	let devices = Object.keys(FlutterManager.connectedDevices).map(function(key) {
		return FlutterManager.connectedDevices[key];
	})
	return devices[index];
}

FlutterManager.GetConnectedDevices = function() {
	let devices = Object.keys(FlutterManager.connectedDevices).map(function(key) {
		return FlutterManager.connectedDevices[key];
	})
	return devices;
}

/**
 * Static function to discover flutter devices
 *
 * @param      {function}  successFn  Callback function called on successful
 *                                    discovery of devices
 * @param      {function}  errorFn    Callback function called on an error in
 *                                    device discovery
 */
FlutterManager.DiscoverDevices = function(successFn, errorFn) {
	HtmlServer.sendRequestWithCallback("flutter/discover", successFn, errorFn);
}

/**
 * Connects a device and adds it to a list of connected devices
 *
 * @param      {string}  deviceName  Name of the device to connect
 */
FlutterManager.ConnectDevice = function(deviceName) {
	FlutterManager.connectedDevices[deviceName] = new Flutter(deviceName);
	FlutterManager.connectedDevices[deviceName].connect(function() {
		BlockPalette.getCategory("robots").refreshGroup();
		FlutterManager.UpdateConnectionStatus();
	});
}

/**
 * Disconnects a device and removes it from a list of connected devices
 *
 * @param      {String}  deviceName  Name of the device to disconnect
 */
FlutterManager.DisconnectDevice = function(deviceName) {
	FlutterManager.connectedDevices[deviceName].disconnect(function() {
		delete FlutterManager.connectedDevices[deviceName];
		BlockPalette.getCategory("robots").refreshGroup();
		FlutterManager.UpdateConnectionStatus();
	});
}

/**
 * Gets a device by name
 *
 * @param      {string}  deviceName  The device name
 * @return     {Flutter}  The device by name.
 */
FlutterManager.GetDeviceByName = function(deviceName) {
	return FlutterManager.connectedDevices[deviceName];
}<|endoftext|>