// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * This view displays information related to HTTP throttling.
 * @constructor
 */
function HttpThrottlingView() {
  const mainBoxId = 'http-throttling-view-tab-content';
  const enableCheckboxId = 'http-throttling-view-enable-checkbox';

  DivView.call(this, mainBoxId);

  this.enableCheckbox_ = $(enableCheckboxId);
  this.enableCheckbox_.onclick = this.onEnableCheckboxClicked_.bind(this);

  g_browser.addHttpThrottlingObserver(this);
}

inherits(HttpThrottlingView, DivView);

/**
 * Gets informed that HTTP throttling has been enabled/disabled.
 * @param {boolean} enabled HTTP throttling has been enabled.
 */
HttpThrottlingView.prototype.onHttpThrottlingEnabledPrefChanged = function(
    enabled) {
  this.enableCheckbox_.checked = enabled;
};

/**
 * Handler for the onclick event of the checkbox.
 */
HttpThrottlingView.prototype.onEnableCheckboxClicked_ = function() {
  g_browser.enableHttpThrottling(this.enableCheckbox_.checked);
};

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * This view displays information related to HTTP throttling.
 */

var HttpThrottlingView = (function() {
  // IDs for special HTML elements in http_throttling_view.html
  const MAIN_BOX_ID = 'http-throttling-view-tab-content';
  const ENABLE_CHECKBOX_ID = 'http-throttling-view-enable-checkbox';

  // We inherit from DivView.
  var superClass = DivView;

  function HttpThrottlingView() {
    // Call superclass's constructor.
    superClass.call(this, MAIN_BOX_ID);

    this.enableCheckbox_ = $(ENABLE_CHECKBOX_ID);
    this.enableCheckbox_.onclick = this.onEnableCheckboxClicked_.bind(this);

    g_browser.addHttpThrottlingObserver(this);
  }

  cr.addSingletonGetter(HttpThrottlingView);

  HttpThrottlingView.prototype = {
    // Inherit the superclass's methods.
    __proto__: superClass.prototype,

    /**
     * Gets informed that HTTP throttling has been enabled/disabled.
     * @param {boolean} enabled HTTP throttling has been enabled.
     */
    onHttpThrottlingEnabledPrefChanged: function(enabled) {
      this.enableCheckbox_.checked = enabled;
    },

    /**
     * Handler for the onclick event of the checkbox.
     */
    onEnableCheckboxClicked_: function() {
      g_browser.enableHttpThrottling(this.enableCheckbox_.checked);
    }
  };

  return HttpThrottlingView;
})();

Refactor HttpThrottlingView to be defined inside an anonymous namespace.


var path = require("path"),
    Files = require("../modules"),
    config = require("../config"),
    root_dir = config.get("root_dir") + '/';

// Parse the request path and figure out how to respond
exports.file = function fileRoute (req, res){
    var uri = path.normalize(req.path);

    if (uri !== req.path)
        return res.redirect(uri);

    // Figure out what's going on and render accordingly
    Files.FileCollector.init(path.normalize(root_dir + req.path))
    	.on("ready", function (directory) {
            return res.render("directory", {
                "title": directory.path,
                "files": directory.files,
                "breadcrumbs": directory.getBreadCrumbs()
            });
    	}).on("single", function (file) {
    	    // Render single file
    	}).on("notFound", function (directory_or_file) {
    	    var path = directory_or_file.path;

    	    return res.status(404).render("404", {
    		"title": path,
    		"path": path
    	    });
    	});
};

var path = require("path"),
    Files = require("../modules"),
    config = require("../config"),
    root_dir = config.root_dir;

// Parse the request path and figure out how to respond
exports.file = function fileRoute (req, res){
    var uri = path.normalize(req.path);

    if (uri !== req.path)
        return res.redirect(uri);

    // Figure out what's going on and render accordingly
    Files.FileCollector.init(path.normalize(root_dir + req.path))
    	.on("ready", function (directory) {
            return res.render("directory", {
                "title": directory.getPath(),
                "files": directory.files,
                "breadcrumbs": directory.getBreadCrumbs()
            });
    	}).on("single", function (file) {
    	    // Render single file
    	}).on("notFound", function (directory_or_file) {
    	    var path = directory_or_file.getPath();

    	    return res.status(404).render("404", {
    		"title": path,
    		"path": path
    	    });
    	});
};

Send proper path to views


export { default as ComputeHelper } from './helpers/compute';
export { default as PipeHelper } from './helpers/pipe';
export { default as MapByHelper } from './helpers/map-by';
export { default as SortByHelper } from './helpers/sort-by';
export { default as FilterByHelper } from './helpers/filter-by';
export { default as GroupByHelper } from './helpers/group-by';
export { default as DropHelper } from './helpers/drop';
export { default as TakeHelper } from './helpers/take';
export { default as RepeatHelper } from './helpers/repeat';
export { default as RangeHelper } from './helpers/range';
export { default as IncHelper } from './helpers/inc';
export { default as DecHelper } from './helpers/dec';
export { default as ToggleHelper } from './helpers/toggle';
export { default as WHelper } from './helpers/w';

export { default as ComputeHelper } from './helpers/compute';
export { default as PipeHelper } from './helpers/pipe';
export { default as MapByHelper } from './helpers/map-by';
export { default as SortByHelper } from './helpers/sort-by';
export { default as FilterByHelper } from './helpers/filter-by';
export { default as GroupByHelper } from './helpers/group-by';
export { default as DropHelper } from './helpers/drop';
export { default as TakeHelper } from './helpers/take';
export { default as RepeatHelper } from './helpers/repeat';
export { default as RangeHelper } from './helpers/range';
export { default as IncHelper } from './helpers/inc';
export { default as DecHelper } from './helpers/dec';
export { default as ToggleHelper } from './helpers/toggle';
export { default as JoinHelper } from './helpers/join';
export { default as WHelper } from './helpers/w';

Add missing export for {{join}} helper


/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const config = require('../webpack.config.dev');
const webpackDev = require('webpack-dev-middleware');
const webpackHot = require('webpack-hot-middleware');

const app = express();
const compiler = webpack(config);

const PORT = process.env.PORT || 3000;

app.use('/', express.static(path.join(__dirname, '..', 'examples')));

app.use(webpackDev(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath,
}));

app.use(webpackHot(compiler));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'examples/index.html'));
});

app.listen(PORT, 'localhost', () => {
    process.stdout.write(`Listening at http://localhost:${PORT}\n`);
});

/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const config = require('../webpack.config.dev');
const webpackDev = require('webpack-dev-middleware');
const webpackHot = require('webpack-hot-middleware');

const app = express();
const compiler = webpack(config);

const PORT = process.env.PORT || 4000;

app.use('/', express.static(path.join(__dirname, '..', 'examples')));

app.use(webpackDev(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath,
}));

app.use(webpackHot(compiler));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'examples/index.html'));
});

app.listen(PORT, 'localhost', () => {
    process.stdout.write(`Listening at http://localhost:${PORT}\n`);
});

Change server port to be node convention


var State = require('./state')
var Story = require('./model/story')

module.exports = function (router) {
  router.get('/stories/list', function (req, res, next) {
    Story.find((err, stories) => {
      res.status(200).send(stories)
    })
  })
}

var State = require('./state')
var Story = require('./model/story')

module.exports = function (router) {
  router.get('/stories/list', function (req, res, next) {
    Story.find((err, stories) => {
      res.status(200).send(stories)
    })
  })

  router.get('/stories/get', function (req, res, next) {
    let storyId = req.query.storyId
    Story.findOne({ _id: storyId }, (err, story) => {
      res.status(200).send(story)
    })
  })
}

Add API to get one story


'use strict';
var stew = require('broccoli-stew');

module.exports = function shimAmd(tree, nameMapping) {
  return stew.map(tree, function(content, relativePath) {
    var name = nameMapping[relativePath];
    if (name) {
      return [
        '(function(define){\n',
        content,
        '\n})((function(){ function newDefine(){ var args = Array.prototype.slice.call(arguments); args.unshift("',
        name,
        '"); return define.apply(null, args); }; newDefine.amd = true; return newDefine; })());'
      ].join('');
    } else {
      return content;
    }
  });
};

'use strict';
var stew = require('broccoli-stew');

module.exports = function shimAmd(tree, nameMapping) {
  return stew.map(tree, function(content, relativePath) {
    var name = nameMapping[relativePath];
    if (name) {
      return [
        '(function(define){',
        content,
        '})((function(){ function newDefine(){ var args = Array.prototype.slice.call(arguments); args.unshift("',
        name,
        '"); return define.apply(null, args); }; newDefine.amd = true; return newDefine; })());'
      ].join('');
    } else {
      return content;
    }
  });
};

Revert "Add newlines to amd shim"


document.body.prepend(dynamicButton);

function createClassroom() {
    var auth2 = gapi.auth2.getAuthInstance();
    var name = "";
    var email = "";
    if (auth2.isSignedIn.get()) {
        var name = auth2.currentUser.get().getBasicProfile().getName();
        var email = auth2.currentUser.get().getBasicProfile().getEmail();
    }

    var subject = document.querySelector('#subject').value;
    var classroomData = JSON.stringify({ "nickname": name, "userId": email, "subject": subject });
    fetch("/dashboard-handler", {method: "POST", body: classroomData}).then((resp) => {
        if (resp.ok){
            console.log("Classroom Created!");
        } else {
            console.log("Error has occured");
        }
    });
}

Prepend sign in button to dashboard.html


#!/usr/bin/env node

var fs = require('fs');
var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version

var opt = require('optimist')
    .usage('jQuery Builder '+ version +'\nUsage: $0')
    .options('e', {
      alias: 'exclude',
      describe: 'Modules to exclude [module,module]',
      type: 'string'
    })
    .option('m', {
      alias: 'minify',
      describe: 'Minify output',
      type: 'boolean'
    })
    .options('l', {
      alias: 'ls',
      describe: 'List available modules',
      type: 'boolean'
    })
    .options('v', {
      alias: 'version',
      describe: 'Version of jQuery to use (1.8.0, 1.8.1, 1.8.2)',
      type: 'string',
      default: '1.8.2'
    })
    .options('h', {
      alias: 'help',
      descripe: 'Show help info'
    });

var argv = opt.argv;

if (argv.help) {
  return opt.showHelp();
}

if (argv.ls) {
  var comp = require('../modules');
  console.log('Modules:');
  comp.forEach(function(c) {
    console.log(c);
  });
  return;
}

var exclude = (argv.exclude) ? argv.exclude.split(',') : undefined;

var builder = require('../lib/builder');

builder(exclude, argv.version, argv.minify, function(err, source) {
  process.stdout.write(source);
});

#!/usr/bin/env node

var fs = require('fs');
var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version

var opt = require('optimist')
    .usage('jQuery Builder '+ version +'\nUsage: $0')
    .options('e', {
      alias: 'exclude',
      describe: 'Modules to exclude [module,module]',
      type: 'string'
    })
    .option('m', {
      alias: 'minify',
      describe: 'Minify output',
      type: 'boolean'
    })
    .options('l', {
      alias: 'ls',
      describe: 'List available modules',
      type: 'boolean'
    })
    .options('v', {
      alias: 'version',
      describe: 'Version of jQuery to use (1.8.0, 1.8.1, 1.8.2)',
      type: 'string',
      default: '1.8.2'
    })
    .options('h', {
      alias: 'help',
      descripe: 'Show help info'
    });

var argv = opt.argv;

if (argv.help) {
  return opt.showHelp();
}

if (argv.ls) {
  var comp = require('../data').modules;
  console.log('Modules:');
  comp.forEach(function(c) {
    console.log(c);
  });
  return;
}

var exclude = (argv.exclude) ? argv.exclude.split(',') : undefined;

var builder = require('../lib/builder');

builder(exclude, argv.version, argv.minify, function(err, source) {
  process.stdout.write(source);
});

Fix for error: Cannot find module '../modules' when --ls specified.


var media = document.querySelectorAll('video, audio');
var rate = prompt('Speed? Currently playing back at ' + media[0].playbackRate + 'x.','');
Array.prototype.forEach.call(media, function(player) {
   if (rate != 0) {
      player.playbackRate = rate;
   } else {
      player.playbackRate = 1;
   }
});

var media = document.querySelectorAll('video, audio');
var rate = prompt('Speed? Currently playing back at ' + media[0].playbackRate + 'x.','');
Array.prototype.forEach.call(media, function(player) {
   if (rate == null) {
      return;
   } else if (rate != 0) {
      player.playbackRate = rate;
   } else {
      player.playbackRate = 1;
   }
});

Maintain current speed if user cancels out.


import React from 'react';
import { expect } from 'chai';
import TestUtils from 'react-addons-test-utils';
import * as components from 'components';

describe('themability', () => {
  Object.keys(components).forEach((key) => {
    let componentClass = components[key];

    describe(key, () => {
      describe('_mixTheme', () => {
        it('returns an object with combined themes', () => {
          componentClass.defaultTheme = {
            one: 'one',
            three: {
              test: 'three'
            }
          };

          let component = TestUtils.renderIntoDocument(React.createElement(componentClass, {theme: {two: 'two'}}));
          expect(component._mixTheme()).to.deep.equal({
            one: 'one',
            two: 'two',
            three: {
              test: 'three'
            }
          });
        });
      });
    });
  });
});

import React from 'react';
import { expect } from 'chai';
import TestUtils from 'react-addons-test-utils';
import * as components from 'components';

describe('themability', () => {
  Object.keys(components).forEach((key) => {
    let componentClass = components[key];

    describe(key, () => {
      describe('_mixTheme', () => {
        before(() => {
          global.oldTheme = componentClass.defaultTheme;
          componentClass.defaultTheme = {
            one: 'one',
            three: {
              test: 'three'
            }
          };
        });

        after(() => {
          componentClass.defaultTheme = global.oldTheme;
        });

        it('returns an object with combined themes', () => {
          let component = TestUtils.renderIntoDocument(React.createElement(componentClass, {theme: {two: 'two'}}));
          expect(component._mixTheme()).to.deep.equal({
            one: 'one',
            two: 'two',
            three: {
              test: 'three'
            }
          });
        });
      });
    });
  });
});

Clean global themes after themability test


import protagonist from 'protagonist';

export default function parseMson(mson, cb) {
  protagonist.parse(mson.trim(), (err, parseResult) => {
    let dataStructureElements;

    if (err) {
      return cb(err);
    }

    dataStructureElements = parseResult.content[0].content[0].content;

    dataStructureElements = dataStructureElements.map((element) =>
      element.content[0]
    );

    return cb(null, dataStructureElements);
  });
}

import protagonist from 'protagonist';

export default function parseMson(mson, cb) {
  protagonist.parse(mson.trim(), (err, parseResult) => {
    let dataStructureElements = [];

    if (err) {
      return cb(err);
    }

    if (
      parseResult.content &&
      parseResult.content[0] &&
      parseResult.content[0].content &&
      parseResult.content[0].content[0] &&
      parseResult.content[0].content[0].content
    ) {
      dataStructureElements = parseResult.content[0].content[0].content;
    }

    dataStructureElements = dataStructureElements.map((element) =>
      element.content[0]
    );

    return cb(null, dataStructureElements);
  });
}

Fix the ‘Cannot read property 'content' of undefined’ error.


/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Main entry-point for the Networking API.
 */

var napi = require('./lib/napi');

var restify = require('restify');
var bunyan = require('bunyan');

var log = bunyan.createLogger({
    name: 'napi',
    level: 'debug',
    serializers: restify.bunyan.serializers
});

var server;

try {
  server = napi.createServer({
    log: log,
    configFile: __dirname + '/config.json'
  });
} catch (err) {
  var errs = err.hasOwnProperty('ase_errors') ? err.ase_errors : [err];
  for (var e in errs) {
    log.error(errs[e]);
  }
  process.exit(1);
}

server.start();

/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Main entry-point for the Networking API.
 */

var napi = require('./lib/napi');

var restify = require('restify');
var bunyan = require('bunyan');

var log = bunyan.createLogger({
    name: 'napi',
    level: 'debug',
    serializers: {
        err: bunyan.stdSerializers.err,
        req: bunyan.stdSerializers.req,
        res: restify.bunyan.serializers.response
    }
});

var server;

try {
  server = napi.createServer({
    log: log,
    configFile: __dirname + '/config.json'
  });
} catch (err) {
  var errs = err.hasOwnProperty('ase_errors') ? err.ase_errors : [err];
  for (var e in errs) {
    log.error(errs[e]);
  }
  process.exit(1);
}

server.start();

Revert the last change, as that removes the req and err serializers


var config = module.exports = require('./config_defaults.js');

config.fundraising_file = '/home/ec2-user/tcbr/fundraising-total.txt'

// config.logger.scraper = {
// 	name: "pixo-scraper",
//     streams: [
// 	    {
// 	        type: 'rotating-file',
// 	        path: 'scraper.log',
// 	        period: '1d'
// 	    }
//     ]
// };

var config = module.exports = require('./config_defaults.js');

config.fundraising_file = '/home/ec2-user/tcbr/fundraising-total.txt'

config.logger.scraper = {
	name: "pixo-scraper",
    streams: [
	    {
	        type: 'rotating-file',
	        path: '/home/ec2-user/tcbr/scraper.log',
	        period: '1d'
	    }
    ]
};

Add prod config for scraper


/* global __dirname */
require('es6-promise').polyfill();

const path = require('path');
const webpack = require('webpack');

const publicPath = '/static';

module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './demo/index.js',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath,
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: 'pre',
        loader: 'eslint-loader',
        include: [path.join(__dirname, 'lib'), path.join(__dirname, 'demo')],
      },
      {
        test: /\.js$/,
        loaders: ['react-hot-loader/webpack', 'babel-loader'],
        include: [path.join(__dirname, 'lib'), path.join(__dirname, 'demo')],
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader?importLoaders=1',
      },
    ],
  },
  devServer: {
    historyApiFallback: true,
    hot: true,
    open: true,
    openPage: 'demo/index.html',
    port: 3040,
    publicPath,
  },
};

/* global __dirname */
require('es6-promise').polyfill();

const path = require('path');
const webpack = require('webpack');

const publicPath = '/static';

module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './demo/index.js',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath,
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: 'pre',
        loader: 'eslint-loader',
        include: [path.join(__dirname, 'lib'), path.join(__dirname, 'demo')],
      },
      {
        test: /\.js$/,
        loaders: ['react-hot-loader/webpack', 'babel-loader'],
        include: [path.join(__dirname, 'lib'), path.join(__dirname, 'demo')],
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader?importLoaders=1',
      },
    ],
  },
  devServer: {
    historyApiFallback: true,
    hot: true,
    open: true,
    openPage: 'demo/index.html',
    publicPath,
  },
};

Remove port to automatically scan for a port


/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Constant declarations for common key values.
 */

goog.provide('goog.events.Keys');

/**
 * Key values for common characters.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
 * @enum {string}
 */
goog.events.Keys = {
  ALT: 'Meta',
  ALTGRAPH: 'AltGraph',
  CTRL: 'Control',
  DOWN: 'ArrowDown',
  END: 'End',
  ENTER: 'Enter',
  ESCAPE: 'Escape',
  HOME: 'Home',
  LEFT: 'ArrowLeft',
  PAGE_DOWN: 'PageDown',
  PAGE_UP: 'PageUp',
  RIGHT: 'ArrowRight',
  SHIFT: 'Shift',
  SPACE: ' ',
  TAB: 'Tab',
  UP: 'ArrowUp',
};

/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Constant declarations for common key values.
 */

goog.provide('goog.events.Keys');

/**
 * Key values for common characters.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
 * @enum {string}
 */
goog.events.Keys = {
  ALT: 'Meta',
  ALTGRAPH: 'AltGraph',
  BACKSPACE: 'Backspace',
  CTRL: 'Control',
  DELETE: 'Delete',
  DOWN: 'ArrowDown',
  END: 'End',
  ENTER: 'Enter',
  ESCAPE: 'Escape',
  HOME: 'Home',
  INSERT: 'Insert',
  LEFT: 'ArrowLeft',
  PAGE_DOWN: 'PageDown',
  PAGE_UP: 'PageUp',
  RIGHT: 'ArrowRight',
  SHIFT: 'Shift',
  SPACE: ' ',
  TAB: 'Tab',
  UP: 'ArrowUp',
};

Expand Keys enum to include: backspace, delete, and insert. RELNOTES: n/a


if (typeof define !== 'function') { var define = require('amdefine')(module); }
if (typeof expect !== 'function') { var expect = require('expect.js'); }

define([
  'app/flowControl'
], function(answers) {
  describe("flow control", function() {
    it("you should be able to conditionally branch your code", function() {
      var num = Math.floor(Math.random() * 10) + 1;

      expect(answers.fizzBuzz()).not.to.be.ok();
      expect(answers.fizzBuzz(2)).to.be(2);
      expect(answers.fizzBuzz(3)).to.be('fizz');
      expect(answers.fizzBuzz(5)).to.be('buzz');
      expect(num * 3 * 5).to.be('fizzbuzz');
    });

    it("you should be able to work with logical operators", function() {
      expect(answers.and(false, false)).not.to.be.ok();
      expect(answers.and(true, false)).not.to.be.ok();
      expect(answers.and(true, true)).to.be.ok();

      expect(answers.or(true, false)).to.be.ok();
      expect(answers.or(true, true)).to.be.ok();
      expect(answers.or(false, false)).not.to.be.ok();
    });
  });

});

if (typeof define !== 'function') { var define = require('amdefine')(module); }
if (typeof expect !== 'function') { var expect = require('expect.js'); }

define([
  'app/flowControl'
], function(answers) {
  describe("flow control", function() {
    it("you should be able to conditionally branch your code", function() {
      var num = Math.floor(Math.random() * 10) + 1;

      expect(answers.fizzBuzz()).not.to.be.ok();
      expect(answers.fizzBuzz(2)).to.be(2);
      expect(answers.fizzBuzz(3)).to.be('fizz');
      expect(answers.fizzBuzz(5)).to.be('buzz');
      expect(answers.fizzBuzz(num * 3 * 5)).to.be('fizzbuzz');
    });

    it("you should be able to work with logical operators", function() {
      expect(answers.and(false, false)).not.to.be.ok();
      expect(answers.and(true, false)).not.to.be.ok();
      expect(answers.and(true, true)).to.be.ok();

      expect(answers.or(true, false)).to.be.ok();
      expect(answers.or(true, true)).to.be.ok();
      expect(answers.or(false, false)).not.to.be.ok();
    });
  });

});

Correct call to answer method


const { clipboard, ipcRenderer } = require('electron');
const beautify_js = require('js-beautify');
const lang = require('language-classifier');

ipcRenderer.on('shortcut-hit', (event, arg) => {
  console.log(arg);
})

function formatClipboard() {
  let clipboard_contents = clipboard.readText(),
      language = lang(clipboard_contents),
      output = '';

  switch(language) {
    case 'css':
      output = beautify_js.css(clipboard_contents);
      break;
    case 'html':
      output = beautify_js.html(clipboard_contents);
      break;
    case 'javascript':
    default:
      output = beautify_js.js_beautify(clipboard_contents);
      break;
  }

  console.log(output);
}

const { clipboard, ipcRenderer } = require('electron');
const beautify_js = require('js-beautify');
const lang = require('language-classifier');

ipcRenderer.on('shortcut-hit', (event, arg) => {
  console.log(arg);
})

function formatClipboard() {
  let clipboard_contents = clipboard.readText(),
      language = lang(clipboard_contents),
      output = '';

  if (clipboard_contents.length === 0) return;

  switch(language) {
    case 'css':
      output = beautify_js.css(clipboard_contents);
      break;
    case 'html':
      output = beautify_js.html(clipboard_contents);
      break;
    case 'javascript':
    default:
      output = beautify_js.js_beautify(clipboard_contents);
      break;
  }

  clipboard.writeText(output);
}

Copy formatted text to clipboard


const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    './app/index.js'
  ],

  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: 'index_bundle.js'
  },

  module: {
    rules: [
      {test: /\.(js|jsx)$/, exclude: /node_modules/,
         use: {
           loader: 'babel-loader',
           options: {
              presets: ['env', 'react']
            }
          }
        },
      {test: /\.css$/, use: ['style-loader', 'css-loader']}
    ]
  },

  devServer: {
    hot: true,
    contentBase: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './app/index.html'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    './app/index.js'
  ],

  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].bundle.js'
  },

  module: {
    rules: [
      {test: /\.(js|jsx)$/, exclude: /node_modules/,
         use: {
           loader: 'babel-loader',
           options: {
              presets: ['env', 'react']
            }
          }
        },
      {test: /\.css$/, use: ['style-loader', 'css-loader']}
    ]
  },

  devServer: {
    hot: true,
    contentBase: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './app/index.html'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
}

Use subsitution for bundle names


const elements = document.querySelectorAll('bracket-less');

// when paused will collapse text to (...)
// when playing doesn't cause trouble

function toggleCollapse(state) {
  if (state.collapse) { // play -> text collapsed
    elements.forEach(el => el.classList.add('bracket-less'));
  } else { // pause -> text displayed
    elements.forEach(el => el.classList.remove('bracket-less'));
  }
}

chrome.runtime.onMessage.addListener((state, sender, sendResponse) => {
  sendResponse(toggleCollapse(state));
});

const elements = document.querySelectorAll('bracket-less');

function expandBrackets() {
  this.innerHTML = this.dataset.bracketless;
  this.classList.remove('bracket-less');
}
function collapseBrackets() {
  this.innerHTML = '...';
  this.classList.add('bracket-less');
}
elements.forEach(el => el.addEventListener('click', expandBrackets.bind(el)));
elements.forEach(el => el.addEventListener('dblclick', collapseBrackets.bind(el)));

function toggleCollapse(state) {
  if (state.collapse) { // play -> text collapsed
    elements.forEach(el => el.classList.add('bracket-less'));
  } else { // pause -> text displayed
    elements.forEach(el => el.classList.remove('bracket-less'));
  }
}

chrome.runtime.onMessage.addListener((state, sender, sendResponse) => {
  sendResponse(toggleCollapse(state));
});

Add onclick and ondblclick event listeners


import { auth0 } from '../../config/secrets';
import { homeLocation } from '../../config/env';

const { clientID, clientSecret, domain } = auth0;

const successRedirect = `${homeLocation}/welcome`;
const failureRedirect = '/signin';

export default {
  devlogin: {
    authScheme: 'mock',
    provider: 'dev',
    module: 'passport-mock-strategy'
  },
  local: {
    provider: 'local',
    module: 'passport-local',
    usernameField: 'email',
    passwordField: 'password',
    authPath: '/auth/local',
    successRedirect: successRedirect,
    failureRedirect: failureRedirect,
    session: true,
    failureFlash: true
  },
  'auth0-login': {
    provider: 'auth0',
    module: 'passport-auth0',
    clientID,
    clientSecret,
    domain,
    cookieDomain: 'freeCodeCamp.org',
    callbackURL: '/auth/auth0/callback',
    authPath: '/auth/auth0',
    callbackPath: '/auth/auth0/callback',
    useCustomCallback: true,
    successRedirect: successRedirect,
    failureRedirect: failureRedirect,
    scope: ['openid profile email'],
    failureFlash: true
  }
};

import { auth0 } from '../../config/secrets';
import { homeLocation, apiLocation } from '../../config/env';

const { clientID, clientSecret, domain } = auth0;

const successRedirect = `${homeLocation}/welcome`;
const failureRedirect = `${homeLocation}/signin`;

export default {
  devlogin: {
    authScheme: 'mock',
    provider: 'dev',
    module: 'passport-mock-strategy'
  },
  local: {
    provider: 'local',
    module: 'passport-local',
    usernameField: 'email',
    passwordField: 'password',
    authPath: '/auth/local',
    successRedirect: successRedirect,
    failureRedirect: failureRedirect,
    session: true,
    failureFlash: true
  },
  'auth0-login': {
    provider: 'auth0',
    module: 'passport-auth0',
    clientID,
    clientSecret,
    domain,
    cookieDomain: process.env.COOKIE_DOMAIN || 'localhost',
    callbackURL: `${apiLocation}/auth/auth0/callback`,
    authPath: '/auth/auth0',
    callbackPath: '/auth/auth0/callback',
    useCustomCallback: true,
    successRedirect: successRedirect,
    failureRedirect: failureRedirect,
    scope: ['openid profile email'],
    failureFlash: true
  }
};

Use absolute path for auth0 callback


const OBEX_utils = require('./obex_utils'),
	  sleep = require('./sleep');

(function pollForNewData(){
	const device = OBEX_utils.mount(process.argv[2], "~/FRC-SCOUT/dev");

	// READ DATA

	setTimeout(() => {
		sleep(1);

		OBEX_utils.unmount(device);

		// Recursively Polls
		pollForNewData();
	}, 1500);
})();

const OBEX_utils = require('./obex_utils'),
	  sleep = require('./sleep'),

	  config = require('./config'),

	  expandHomeDir = require('expand-home-dir');

(function pollForNewData(){
	const device = OBEX_utils.mount(process.argv[2], expandHomeDir(config.device_directory)),

		  files = fs.readdirSync(
			  expandHomeDir(config.receive_directory)
		  );

	files.forEach((file) => {
		const newFile = fs.readFileSync(expandHomeDir(config.receive_directory) + file, { encoding: "utf8" }));

		// Log File to MongoDB
		// Send File via Web Socket to Web UI
	});

	setTimeout(() => {
		sleep(1);

		OBEX_utils.unmount(device);

		// Recursively Polls
		pollForNewData();
	}, 5000);
})();

Adjust Polling Interval and Implement Data Read


import path from 'path';
import webpack from 'webpack';

const buildPath = path.resolve(__dirname, 'dist');
const clientPath = path.resolve(__dirname, 'src', 'client.js');

const devPlugins = [
  new webpack.NoErrorsPlugin(),
  new webpack.HotModuleReplacementPlugin()
]

const prodPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({compressor: { warnings: false }})
];

const plugins = (process.env.NODE_ENV === 'production') ? prodPlugins : devPlugins

var config = {

  devtool: '#inline-source-map',

  entry: [
    clientPath,
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client'
  ],

  output: {
    path: buildPath,
    filename: 'bundle.js',
    publicPath: '/static/'
  },

  resolve: {
    alias: {},
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel',
      exclude: /node_modules/,
      include: __dirname,
      query: { presets: ["es2015", "stage-0", "react"] }
    },
    {
      test: /\.css$/,
      loader: "style!css"
    }]
  },
  plugins: plugins
};

module.exports = config;

import path from 'path';
import webpack from 'webpack';

const buildPath = path.resolve(__dirname, 'dist');
const clientPath = path.resolve(__dirname, 'src', 'client.js');

const devPlugins = [
  new webpack.NoErrorsPlugin(),
  new webpack.HotModuleReplacementPlugin()
]

const prodPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({compressor: { warnings: false }})
];

const plugins = (process.env.NODE_ENV === 'production') ? prodPlugins : devPlugins

var config = {

  devtool: 'eval',

  entry: [
    clientPath,
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client'
  ],

  output: {
    path: buildPath,
    filename: 'bundle.js',
    publicPath: '/static/'
  },

  resolve: {
    alias: {},
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel',
      exclude: /node_modules/,
      include: __dirname,
      query: { presets: ["es2015", "stage-0", "react"] }
    },
    {
      test: /\.css$/,
      loader: "style!css"
    }]
  },
  plugins: plugins
};

module.exports = config;

Change to eval mode source map


function StorageManager(storageMethod) {
    this.storageMethod = storageMethod;
}

StorageManager.prototype.setCurrentLevel = function(level) {
    this.storageMethod.setItem('currentLevel', level);
};

StorageManager.prototype.incrementCurrentLevel = function() {
   this.setCurrentLevel(this.getCurrentLevel() + 1);
};

StorageManager.prototype.getCurrentLevel = function() {
    return parseInt(this.storageMethod.getItem('currentLevel')) || 1;
};

StorageManager.prototype.setCurrentLevelHistory = function(history) {
    this.history = history;
};

StorageManager.prototype.updateCurrentLevelHistory = function() {
    if(typeof this.history === 'undefined' ) {
        throw "Cannot update history without history object";
    }
    this.storageMethod.setItem('currentLevelHistory', JSON.stringify(this.history));
};

StorageManager.prototype.getCurrentLevelHistory = function(history) {
    var history = this.storageMethod.getItem('currentLevelHistory');
    return history ? JSON.parse(history) : [];
};

StorageManager.prototype.getLevelResults = function() {
    var results = this.storageMethod.getItem('levelResults');
    return results ? JSON.parse(results) : [];
};

StorageManager.prototype.setLevelResult = function(level, result) {
    var results = this.getLevelResults();
    results[level - 1] = result;
    this.storageMethod.setItem('levelResults', JSON.stringify(results));
};

StorageManager.prototype.getLevelResult = function(level) {
    return this.getLevelResults()[level];
};

function StorageManager(storageMethod) {
    this.storageMethod = storageMethod;
}

StorageManager.prototype.setCurrentLevel = function(level) {
    this.storageMethod.setItem('currentLevel', level);
};

StorageManager.prototype.incrementCurrentLevel = function() {
   this.setCurrentLevel(this.getCurrentLevel() + 1);
};

StorageManager.prototype.getCurrentLevel = function() {
    return parseInt(this.storageMethod.getItem('currentLevel')) || 1;
};

StorageManager.prototype.setCurrentLevelHistory = function(history) {
    this.history = history;
};

StorageManager.prototype.updateCurrentLevelHistory = function() {
    if(typeof this.history === 'undefined' ) {
        throw "Cannot update history without history object";
    }
    this.storageMethod.setItem('currentLevelHistory', JSON.stringify(this.history));
};

StorageManager.prototype.getCurrentLevelHistory = function(history) {
    var history = this.storageMethod.getItem('currentLevelHistory');
    return history ? JSON.parse(history) : [];
};

StorageManager.prototype.getLevelResults = function() {
    var results = this.storageMethod.getItem('levelResults');
    return results ? JSON.parse(results) : [];
};

StorageManager.prototype.setLevelResult = function(level, result) {
    var results = this.getLevelResults();
    results[level - 1] = result;
    this.storageMethod.setItem('levelResults', JSON.stringify(results));
};

StorageManager.prototype.getLevelResult = function(level) {
    return this.getLevelResults()[level - 1];
};

Fix storage manager returning wrong level result


/*
 * I am working on this
 */
(function() {
    var test = "test",
        test2 = "test2";

    function log() {
        console.log(test + " - " + test2);
    }
})()

/*
 * I am working on this
 */
(function() {
    var test = "test",
        test2 = "test2";

    function log() {
        console.log(test + " - " + test2);
    }

    log();
})()

Call log() function - testing functionallity.


genotower.geneticAlgorithm = {

    evolve : function () {
      genotower.generation.mutateGenome(genotower.towers);
      genotower.generation.mutateGenome(genotower.walls);
      genotower.map.draw();
      console.log(genotower.generation.scoreFitness());
    }
};

genotower.geneticAlgorithm = {

    evolve : function () {
      genotower.generation.mutateGenome(genotower.towers);
      genotower.generation.mutateGenome(genotower.walls);
      genotower.map.draw();
      genotower.path.placePath();
      console.log(genotower.generation.scoreFitness());
    }
};

Call placePath() on each iteration of evolve.


angular.module('mqWebApp').provider('mqWebQueue', {
	qmgr : '',

	$get : ['$http', function($http) {
		return {
			getQueueManager : function() {
				return qmgr;
			},
			inquire : function(args) {
				if ( typeof args == 'object' ) {
					return $http.get('/queue/inquire/' + qmgr, {
							cache : false,
							params : args
						});
				}
				else {
					return $http.get('/queue/inquire/' + qmgr + '/' + args, { cache : false } );
				}
			}
		}
	}],

	setQueueManager : function(value) {
		qmgr = value;
	}

});

angular.module('mqWebApp').provider('mqWebQueue', {
	qmgr : '',

	$get : ['$http', function($http) {
		return {
			getQueueManager : function() {
				return qmgr;
			},
			// Pass an object for using the query parameters of inquire
			// or a name of a queue to set the URI path.
			inquire : function() {
				if ( typeof arguments[0] == 'object' ) {
					return $http.get('/queue/inquire/' + qmgr, {
							cache : false,
							params : arguments[0]
						});
				}
				else {
					return $http.get('/queue/inquire/' + qmgr + '/' + arguments[0], { cache : false } );
				}
			}
		}
	}],

	setQueueManager : function(value) {
		qmgr = value;
	}

});

Use 'arguments' to check for variable arguments


import $ from "jquery";

import * as compose_state from "./compose_state";
import * as overlays from "./overlays";
import * as popovers from "./popovers";

export function is_visible() {
    return $("#recent_topics_view").is(":visible");
}

export function is_in_focus() {
    // Check if user is focused on
    // recent topics.
    return (
        is_visible() &&
        !compose_state.composing() &&
        !popovers.any_active() &&
        !overlays.is_active() &&
        !$(".home-page-input").is(":focus")
    );
}

export function get_topic_key(stream_id, topic) {
    return stream_id + ":" + topic.toLowerCase();
}

import $ from "jquery";

import * as compose_state from "./compose_state";
import * as overlays from "./overlays";
import * as popovers from "./popovers";

export function is_visible() {
    return $("#recent_topics_view").is(":visible");
}

export function is_in_focus() {
    // Check if user is focused on
    // recent topics.
    return (
        is_visible() &&
        !compose_state.composing() &&
        !popovers.any_active() &&
        !overlays.is_active() &&
        !overlays.is_modal_open() &&
        !$(".home-page-input").is(":focus")
    );
}

export function get_topic_key(stream_id, topic) {
    return stream_id + ":" + topic.toLowerCase();
}

Return false in `is_in_focus` if a modal is present.


const fmiRequest = require('../lib/fmiRequest');

const queryId = 'fmi::forecast::hirlam::surface::point::simple';
exports.queryId = queryId;
exports.params = ['place'];

exports.run = function runQuery(place) {
  return fmiRequest.get({ queryId, params: { place } })
    .then(results => Promise.resolve(results))
    .catch(err => console.log(err));
};

const fmiRequest = require('../lib/fmiRequest');

const queryId = 'fmi::forecast::hirlam::surface::point::simple';
exports.queryId = queryId;
exports.params = ['place', 'latlng'];

exports.run = function runQuery(place) {
  return fmiRequest.get({ queryId, params: { place } })
    .then(results => Promise.resolve(results))
    .catch(err => console.log(err));
};

/**
 * Fetches forecasts by LatLng, eg. 61.23,23.31
 */
exports.runLatLng = function runQuery(latlon) {
  return fmiRequest.get({ queryId, params: { latlon } })
    .then(results => Promise.resolve(results))
    .catch(err => console.log(err));
};

Add function to get forecasts by latitude and longitude.


app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
    return {
        restrict: 'E',
        templateUrl: config.partialsDir + '/broadcast_block.html',
        link: function(scope, element, attrs) {
            var notifications = Restangular.all('notifications');
            var updateNotifications = function() {
                notifications.getList().then(function(response) {
                    if (response.length) {
                        scope.selectedNotification = response[0];
                    } else {
                        scope.selectedNotification = undefined;
                    }
                });
            };
            updateNotifications();

            scope.markAsSeen = function(notification) {
                notification.patch().then(updateNotifications);
            };
        }
    };
}]);

app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
    return {
        restrict: 'E',
        templateUrl: config.partialsDir + '/broadcast_block.html',
        link: function(scope, element, attrs) {
            var notifications = Restangular.all('notifications');
            var updateNotifications = function() {
                notifications.getList().then(function(response) {
                    if (response.length) {
                        scope.selectedNotification = response[0];
                    } else {
                        scope.selectedNotification = undefined;
                    }
                });
            };
            scope.markAsSeen = function(notification) {
                notification.patch().then(updateNotifications);
            };

            if (AuthService.isAuthenticated()) {
               updateNotifications();
            }
        }
    };
}]);

Check auth status before retrieving notifications


'use strict'

var fs = fs || require('fs');

var getDirRecursiveSync = function(dir, filelist) {

    var files = fs.readdirSync(dir);
    filelist = filelist || [];
    var fileLength = files.length;
    for (var i=0; i<fileLength; i++)
    {
        var file = files[i];
        var path = dir + file;
        if (fs.statSync(path).isDirectory()) {
            filelist = getDirRecursiveSync(path + '/', filelist);
        } else {
            filelist.push(path);
        }
    }
    return filelist;
};

module.exports = getDirRecursiveSync;

Add strict option to recursive directory browser


const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

/**
* Checks if the password provided by the user matches the password
* in the database
*/
function comparePasswords (reqPass, dbPass) {
  return bcrypt.compareSync(reqPass, dbPass)
}

/**
 * Generate token for use when login in
 */
function generateToken (payload) {
  return jwt.sign(payload, process.env.JWT_SECRET)
}

/**
 * Hash the password for secure storage in the database
 */
function hashedPassword (password) {
  return bcrypt.hashSync(password, 10)
}

module.exports = {
  comparePasswords,
  generateToken,
  hashedPassword
}

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

/**
* Checks if the password provided by the user matches the password
* in the database
*/
function comparePasswords (reqPass, dbPass) {
  return bcrypt.compareSync(reqPass, dbPass)
}

/**
 * Generate token for use when login in
 */
function generateToken (payload) {
  return jwt.sign(payload, process.env.JWT_SECRET)
}

/**
 * Verify the token. Verifies validity (tamper and expiry)
 */
function verifyToken (token, secretOrKey, options, callback) {
  return jwt.verify(token, secretOrKey, options, callback)
}

/**
 * Hash the password for secure storage in the database
 */
function hashedPassword (password) {
  return bcrypt.hashSync(password, 10)
}

module.exports = {
  comparePasswords,
  generateToken,
  verifyToken,
  hashedPassword
}

Add logic to verify the token without doing a database lookup


//  Chance.js 0.1
//  http://chancejs.com
//  (c) 2013 Victor Quinn
//  Chance may be freely distributed or modified under the MIT license.

(function () {

    var Chance = {
        VERSION: 0.1,

        // Building Blocks/Basics
        bool: function () {
            return Math.random() * 100 < 50;
        },

        str: function (length) {
            var text = "";
            var possible = "abcdefghijklmnopqrstuvwxyz";

            for (var i = 0; i < length; i++) {
                text += possible.charAt(Math.floor(Math.random() * possible.length));
            }

            return text;
        }
    };

    // CommonJS module
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = Chance;
        }
        exports.Chance = Chance;
    }

    // Register as a named AMD module
    if (typeof define === 'function' && define.amd) {
        define('Chance', [], function () {
            return Chance;
        });
    }

})();

//  Chance.js 0.1
//  http://chancejs.com
//  (c) 2013 Victor Quinn
//  Chance may be freely distributed or modified under the MIT license.

(function () {

    var Chance = {
        VERSION: 0.1,

        // Building Blocks/Basics
        bool: function () {
            return Math.random() * 100 < 50;
        },
        natural: function() {
            // 9007199254740992 is the max integer number.
            return Math.floor(Math.random() * 9007199254740992);
        },
        integer: function() {
            // 9007199254740992 is the max integer number.
            var num = Math.floor(Math.random() * 9007199254740992);
            return this.bool() ? num : num * -1;
        },

        str: function (length) {
            var text = "";
            var possible = "abcdefghijklmnopqrstuvwxyz";

            for (var i = 0; i < length; i++) {
                text += possible.charAt(Math.floor(Math.random() * possible.length));
            }

            return text;
        }
    };

    // CommonJS module
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = Chance;
        }
        exports.Chance = Chance;
    }

    // Register as a named AMD module
    if (typeof define === 'function' && define.amd) {
        define('Chance', [], function () {
            return Chance;
        });
    }

})();

Add functions for natural, integer


import { ErrorPage } from './ErrorPage';
import { LoginPage } from './LoginPage';
import { App } from './actions';
import { Root } from './router';

(function () {

if (!history.pushState) {
  return;   // see old.js
}

var query = Votr.settings.destination;
if (query !== undefined && (query == '' || query.substring(0, 1) == '?')) {
  try {
    history.replaceState(null, '', Votr.settings.url_root + query);
  } catch (e) {
    console.error(e);
  }
}

Votr.setDebug = function (enabled) {
  document.cookie = enabled ? 'votr_debug=true' : 'votr_debug=';
  location.reload();
}

var root =
    Votr.settings.servers ? <LoginPage /> :
    Votr.settings.error ? <ErrorPage /> :
    <Root app={App} />;

Votr.appRoot = React.render(root, document.getElementById('votr'));

})();

import { ErrorPage } from './ErrorPage';
import { LoginPage } from './LoginPage';
import { App } from './actions';
import { Root } from './router';

(function () {

if (!history.pushState) {
  return;   // see old.js
}

if (typeof __webpack_require__ !== 'undefined') {
  Votr.webpackRequire = __webpack_require__;
}

var query = Votr.settings.destination;
if (query !== undefined && (query == '' || query.substring(0, 1) == '?')) {
  try {
    history.replaceState(null, '', Votr.settings.url_root + query);
  } catch (e) {
    console.error(e);
  }
}

Votr.setDebug = function (enabled) {
  document.cookie = enabled ? 'votr_debug=true' : 'votr_debug=';
  location.reload();
}

var root =
    Votr.settings.servers ? <LoginPage /> :
    Votr.settings.error ? <ErrorPage /> :
    <Root app={App} />;

Votr.appRoot = React.render(root, document.getElementById('votr'));

})();

Add debug access to webpack modules.


define(['backbone.marionette', 'app', 'hbs!../templates/exam'],
  function (Marionette, App, template) {
    'use strict';

    return Marionette.ItemView.extend({
      tagName: 'tr',
      template: template,

      events: {
        'click .remove': function () {
          App.request('removeModule', this.model.id);
        },
        'click .show-hide': function () {
          var display = !this.model.get('display');
          this.model.set('display', display);
          App.request('displayLessons', this.model.id, display);
        }
      },

      modelEvents: {
        change: 'render'
      },

      onRender: function () {
        this.$el.addClass('color' + this.model.get('color'))
          .toggleClass('clash', this.model.get('clash'));
      }
    });
  });

define(['backbone.marionette', 'app', 'hbs!../templates/exam'],
  function (Marionette, App, template) {
    'use strict';

    return Marionette.ItemView.extend({
      tagName: 'tr',
      template: template,

      events: {
        'click .remove': function (event) {
          event.preventDefault();
          App.request('removeModule', this.model.id);
        },
        'click .show-hide': function (event) {
          event.preventDefault();
          var display = !this.model.get('display');
          this.model.set('display', display);
          App.request('displayLessons', this.model.id, display);
        }
      },

      modelEvents: {
        change: 'render'
      },

      onRender: function () {
        this.$el.addClass('color' + this.model.get('color'))
          .toggleClass('clash', this.model.get('clash'));
      }
    });
  });

Fix missing preventDefault on links in exam timetable


import jwt from 'jsonwebtoken';
/**
  * verifyToken: This verifies all routes that starts with /api
  *  It checks if there is token and checks if the token is valid
  *  if the token is valid then it decodes it and send to the next routes
  * @function verifyToken
  * @param {object} req
  * @param {object} res
  * @param {object} next
  * @return {object} - returns response status and json data
  */
const verifyToken = (req, res, next) => {
  // checking for token
  if (req.url.startsWith('/users/auth')) return next();
  if (!req.headers.authorization) {
    return res.status(400).json({
      message: 'Please set token in the header!'
    });
  }
  const token = req.headers.authorization;
  // decoding the token
  if (token) {
    // verifies secret and checks
    jwt.verify(token, process.env.JWT_SECRET, (error, decoded) => {
      if (error) {
        return res.status(400).json({
          message: 'Invalid token. Please login :)'
        });
      }
      // request user detail for other routes
      req.decoded = decoded;
      next();
    });
  } else {
    return res.status(400).json({
      message: 'Please provide a token!'
    });
  }
};

export default verifyToken;

import jwt from 'jsonwebtoken';
/**
  * verifyToken: This verifies all routes that starts with /api
  *  It checks if there is token and checks if the token is valid
  *  if the token is valid then it decodes it and send to the next routes
  * @function verifyToken
  * @param {object} req
  * @param {object} res
  * @param {object} next
  * @return {object} - returns response status and json data
  */
const verifyToken = (req, res, next) => {
  if (req.url.startsWith('/users/auth') || req.url === '/') return next();
  if (!req.headers.authorization) {
    return res.status(400).json({
      message: 'Please set token in the header!'
    });
  }
  const token = req.headers.authorization;
  if (token) {
    jwt.verify(token, process.env.JWT_SECRET, (error, decoded) => {
      if (error) {
        return res.status(400).json({
          message: 'Invalid token. Please login :)'
        });
      }
      req.decoded = decoded;
      next();
    });
  } else {
    return res.status(400).json({
      message: 'Please provide a token!'
    });
  }
};

export default verifyToken;

Make the index route open


module.exports = {
  description: '',

  afterInstall: function () {
    return this.addAddonsToProject({
      packages: [
        {name: 'ember-array-helper', target: '^1.0.0'},
        {name: 'ember-cli-d3-shape', target: '0.9.4-4.1.1.0'},
        {name: 'ember-frost-core', target: '>=0.25.6 <1.0.0'},
        {name: 'ember-prop-types', target: '^3.0.0'}
      ]
    })
  }
}

module.exports = {
  description: '',

  normalizeEntityName: function () {},

  afterInstall: function () {
    return this.addAddonsToProject({
      packages: [
        {name: 'ember-array-helper', target: '^1.0.0'},
        {name: 'ember-cli-d3-shape', target: '0.9.4-4.1.1.0'},
        {name: 'ember-frost-core', target: '>=0.25.6 <1.0.0'},
        {name: 'ember-prop-types', target: '^3.0.0'}
      ]
    })
  }
}

Fix "The `ember generate <entity-name>` command requires an entity name to be specified." error during installation


/* eslint-env mocha */
const mockBot = require('../mockBot')
const assert = require('assert')
const mockery = require('mockery')

describe('urban module', function () {
  before(function () {
    // mockery mocks the entire require()
    mockery.enable()
    mockery.registerMock('urban', (headword) => {
      return {
        first: () => {
          switch (headword) {
            case 'one':
              return { definition: 'one two three four', link: 'http://example.com' }
            default:
              return undefined
          }
        }
      }
    })

    mockBot.loadModule('urban')
  })

  it('should return a definition', async function () {
    let response = await mockBot.runCommand('!ud one')
    assert.strictEqual(response, 'one two three four')
  })

  it('should show an error on 404', async function () {
    let response = await mockBot.runCommand('!ud two')
    assert.strictEqual(response, 'unable to find a definition for two')
  })

  after(function (done) {
    mockery.disable()
    mockery.deregisterAll()
    done()
  })
})

/* eslint-env mocha */
const mockBot = require('../mockBot')
const assert = require('assert')
const mockery = require('mockery')

describe('urban module', function () {
  before(function () {
    // mockery mocks the entire require()
    mockery.enable()
    mockery.registerMock('urban', (headword) => {
      return {
        first: (cb) => {
          /* eslint-disable standard/no-callback-literal */
          switch (headword) {
            case 'one':
              return cb({ definition: 'one two three four', link: 'http://example.com' })
            default:
              return cb(undefined)
          }
          /* eslint-enable standard/no-callback-literal */
        }
      }
    })

    mockBot.loadModule('urban')
  })

  it('should return a definition', async function () {
    let response = await mockBot.runCommand('!ud one')
    assert.strictEqual(response, 'one two three four')
  })

  it('should reject on 404', function () {
    assert.rejects(mockBot.runCommand('!ud two'))
  })

  after(function (done) {
    mockery.disable()
    mockery.deregisterAll()
    done()
  })
})

Fix timeout issue with newer version of Mocha


$(document).ready(function() {
    MageHero_App.bindUpvote();
    $('table.listing').tablesorter({
        headers: {
            1: { sorter: false },
            2: { sorter: false },
            4: { sorter: false },
            8: { sorter: false }
        },
        textExtraction: function(cell) {
            var votes = $(cell).find('.vote-count');
            if (votes.length) {
                return votes.text();
            }
            return $(cell).text();
        }
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // Nothing yet
});

MageHero_App = {
    bindUpvote: function() {
        var self = this;

        $('.upvote a').click(function() {
            var userId = $(this).closest('tr').attr('data-user-id');
            var upvoteCount = $(this).closest('.upvote').find('.vote-count')

            $.ajax({
                url: '/user/' + userId + '/upvote',
                method: 'GET',
                success: function(data) {
                    console.log(data);
                    if (! data.success) {
                        alert(data.message);
                        return;
                    }

                    upvoteCount.text(data.vote_count);
                }
            });
        });

        return this;
    }
};

$(document).ready(function() {
    MageHero_App.bindUpvote();
    $('table.listing').tablesorter({
        headers: {
            1: { sorter: false },
            2: { sorter: false },
            4: { sorter: false },
            8: { sorter: false }
        },
        textExtraction: function(cell) {
            var votes = $(cell).find('.vote-count');
            if (votes.length) {
                return votes.text();
            }
            return $(cell).text();
        }
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // Nothing yet
});

MageHero_App = {
    bindUpvote: function() {
        var self = this;

        $('.upvote a').click(function() {
            var userId = $(this).closest('tr').attr('data-user-id');
            var upvoteCount = $(this).closest('.upvote').find('.vote-count')

            $.ajax({
                url: '/user/' + userId + '/upvote',
                method: 'GET',
                success: function(data) {
                    console.log(data);
                    if (! data.success) {
                        alert(data.message);
                        return;
                    }

                    upvoteCount.text(data.vote_count).show();
                }
            });
        });

        return this;
    }
};

Make vote count visible after upvoting


$(document).ready(function(){
  $(window).scroll(function(){
        if ($(this).scrollTop() >= $(".section-3").offset().top) {
           $(".inner-phone").css("background-color","blue");
        }else if($(this).scrollTop() >= $(".section-2").offset().top) {
          $(".inner-phone").css("background-color","yellow");
        } else {
          $(".inner-phone").css("background-color","green");
        }
    });
});

$(document).ready(function(){
  $(window).scroll(function(){
        if ($(this).scrollTop() >= $(".section-3").offset().top) {
          $(".cell-phone-img").attr("src","img/flashF.jpg");
          $(".phone").addClass("fixed")
        }else if($(this).scrollTop() >= $(".section-2").offset().top) {
          $(".cell-phone-img").attr("src","img/fun.jpg");
          $(".phone").addClass("fixed")
        } else {
          $(".inner-phone").css("background-color","green");
          $(".phone").removeClass("fixed")
        }
    });
});

Add jquery to change image on phone when scroll


'use strict';

import mongoose, {Schema} from 'mongoose';

var MdphSchema = new Schema({
  zipcode:      { type: String, unique: true },
  name:         { type: String },
  logo:         { type: String },
  enabled:      { type: Boolean },
  opened:       { type: Boolean },
  likes:        [{ type: String }],
  outsideLink: {
    href:       { type: String },
    label:      { type: String }
  },
  locations: [
    {
      address:      { type: String },
      coordinates: {
        coordx:     { type: String },
        coordy:     { type: String },
      },
      phone:        { type: String },
      email:        { type: String },
      schedule:     { type: String },
    }
  ],
});

export default mongoose.model('Mdph', MdphSchema);

'use strict';

import mongoose, {Schema} from 'mongoose';

var MdphSchema = new Schema({
  zipcode:      { type: String, unique: true },
  name:         { type: String },
  logo:         { type: String },
  enabled:      { type: Boolean },
  opened:       { type: Boolean },
  likes:        [{ type: String }],
  outsideLink: {
    href:       { type: String },
    label:      { type: String }
  },
  locations: [
    {
      address:      { type: String },
      coordinates: {
        coordx:     { type: String },
        coordy:     { type: String },
      },
      phone:        { type: String },
      email:        { type: String },
      schedule:     { type: String },
      headquarters: { type: Boolean },
    }
  ],
});

export default mongoose.model('Mdph', MdphSchema);

Add boolean to specify which location is the headquarter


'use strict';

import React, { Component } from 'react';
import ReactCSS from 'reactcss';

import colors from '../styles/variables/colors';
import 'normalize.css';
import '../fonts/work-sans/WorkSans.css!';
import '../styles/felony.css!';

import Header from './header/Header';

export class Felony extends Component {
  classes() {
    return {
      'default': {
        app: {
          Absolute: '0 0 0 0',
          background: colors.bgLight,
        },
      },
    };
  }

  render() {
    return (
      <div is="app">
        <Header />
      </div>
    );
  }
}

export default ReactCSS(Felony);

'use strict';

import React, { Component } from 'react';
import ReactCSS from 'reactcss';

import colors from '../styles/variables/colors';
import 'normalize.css';
import '../fonts/work-sans/WorkSans.css!';
import '../styles/felony.css!';

import Header from './header/Header';
import FloatingButtonToggle from './floating-button/FloatingButtonToggle';

export class Felony extends Component {
  classes() {
    return {
      'default': {
        app: {
          Absolute: '0 0 0 0',
          background: colors.bgLight,
        },
      },
    };
  }

  render() {
    return (
      <div is="app">
        <Header />
        <FloatingButtonToggle />
      </div>
    );
  }
}

export default ReactCSS(Felony);

Add floating button toggle to main


(function() {
  'use strict';

  angular.module('app')
    .run(init);

  /** @ngInject */
  function init(gettextCatalog, gettext) {
    // prepend [MISSING] to untranslated strings
    gettextCatalog.debug = false;

    gettextCatalog.loadAndSet = function(lang) {
      gettextCatalog.setCurrentLanguage(lang);

      if (lang) {
        gettextCatalog.loadRemote("gettext/json/" + lang + "/manageiq-ui-self_service.json");
      }
    };

    window.N_ = gettext;
    window.__ = gettextCatalog.getString.bind(gettextCatalog);
  }
})();

(function() {
  'use strict';

  angular.module('app')
    .run(init);

  /** @ngInject */
  function init(gettextCatalog, gettext) {
    // prepend [MISSING] to untranslated strings
    gettextCatalog.debug = false;

    gettextCatalog.loadAndSet = function(lang) {
      if (lang) {
        lang = lang.replace('_', '-');
        gettextCatalog.setCurrentLanguage(lang);
        gettextCatalog.loadRemote("gettext/json/" + lang + "/manageiq-ui-self_service.json");
      }
    };

    window.N_ = gettext;
    window.__ = gettextCatalog.getString.bind(gettextCatalog);
  }
})();

Fix language code returned by ManageIQ rest API


import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
import canToggle from '../util/can-toggle';

require('../components/ha-card');
require('../components/entity/ha-entity-toggle');
require('../state-summary/state-card-content');

const { moreInfoActions } = hass;

export default new Polymer({
  is: 'ha-entities-card',

  properties: {
    states: {
      type: Array,
    },
    groupEntity: {
      type: Object,
    },
  },

  computeTitle(states, groupEntity) {
    return groupEntity ? groupEntity.entityDisplay :
                         states[0].domain.replace(/_/g, ' ');
  },

  entityTapped(ev) {
    if (ev.target.classList.contains('paper-toggle-button') ||
        ev.target.classList.contains('paper-icon-button')) {
      return;
    }
    ev.stopPropagation();
    const entityId = ev.model.item.entityId;
    this.async(() => moreInfoActions.selectEntity(entityId), 1);
  },

  showGroupToggle(groupEntity, states) {
    if (!groupEntity || !states || groupEntity.state !== 'on' && groupEntity.state !== 'off') {
      return false;
    }

    // only show if we can toggle 2+ entities in group
    return states.reduce((sum, state) => sum + canToggle(state.entityId)) > 1;
  },
});

import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
import canToggle from '../util/can-toggle';

require('../components/ha-card');
require('../components/entity/ha-entity-toggle');
require('../state-summary/state-card-content');

const { moreInfoActions } = hass;

export default new Polymer({
  is: 'ha-entities-card',

  properties: {
    states: {
      type: Array,
    },
    groupEntity: {
      type: Object,
    },
  },

  computeTitle(states, groupEntity) {
    return groupEntity ? groupEntity.entityDisplay :
                         states[0].domain.replace(/_/g, ' ');
  },

  entityTapped(ev) {
    if (ev.target.classList.contains('paper-toggle-button') ||
        ev.target.classList.contains('paper-icon-button')) {
      return;
    }
    ev.stopPropagation();
    const entityId = ev.model.item.entityId;
    this.async(() => moreInfoActions.selectEntity(entityId), 1);
  },

  showGroupToggle(groupEntity, states) {
    if (!groupEntity || !states || groupEntity.state !== 'on' && groupEntity.state !== 'off') {
      return false;
    }

    // only show if we can toggle 2+ entities in group
    return states.reduce((sum, state) => sum + canToggle(state.entityId), 0) > 1;
  },
});

Fix group toggle not showing


import React from 'react';

import PageTitle from '../components/layout/PageTitle';

const Documentation = () => {

    return (

              <PageTitle pageTitle={'Documentation'} />

    );

};

export default Documentation;

Add stub blocks to Docs page


var React = require('react');
var Gravatar = require('react-gravatar');

class QueueItem extends React.Component{
  render(){
    return (

          <Gravatar email={this.props.item.email} size={150} default="mm" />

 {this.props.item.name}

 {this.props.item.question}

    );
  }
};

QueueItem.propTypes = {}

module.exports = QueueItem;

var React = require('react');
var Gravatar = require('react-gravatar');

class QueueItem extends React.Component{
  render(){
    var styles = {
      avatar: {
        position: 'relative',
        padding: 0
      },
      imageText: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        textAlign: 'center',
        width: '130px',
        background: "rgba(0, 0, 0, 0.75)",
        color: '#fff',
        cursor: 'pointer',
        fontSize: '18px'
      }
    }
    var imageText = this.props.isAdmin === true ?  Answer  :  Remove ;
    return (

          <Gravatar email={this.props.item.email} size={130} default="mm" />
          {imageText}

 {this.props.item.name}

 {this.props.item.question}

    );
  }
};

QueueItem.propTypes = {}

module.exports = QueueItem;

Add layover on avatar image


import React, { PureComponent } from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';

import withTheme from '../hoc/withTheme';

import Box from '../box';
import theme from './theme.css';

class LoadingBar extends PureComponent {
  render() {
    const { className, ...others } = this.props;

    const classNames = cx(theme['loading-bar'], className);

    return (
      <Box data-teamleader-ui="loading-bar" className={classNames} {...others}>
        <div className={theme['loading-bar-indicator']} />
      </Box>
    );
  }
}

LoadingBar.propTypes = {
  /** A class name for the wrapper to add custom classes */
  className: PropTypes.string,
};

export default withTheme(theme)(LoadingBar);

import React, { PureComponent } from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';

import Box from '../box';
import theme from './theme.css';

class LoadingBar extends PureComponent {
  render() {
    const { className, color, size, tint, ...others } = this.props;

    const classNames = cx(
      theme['loading-bar'],
      theme[`is-${color}`],
      theme[`is-${size}`],
      theme[`is-${tint}`],
      className,
    );

    return (
      <Box data-teamleader-ui="loading-bar" className={classNames} {...others}>
        <div className={theme['loading-bar-indicator']} />
      </Box>
    );
  }
}

LoadingBar.propTypes = {
  /** A class name for the wrapper to add custom classes */
  className: PropTypes.string,
  /** The color of the components */
  color: PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']),
  /** Size of the component */
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  /** The tint of the components color */
  tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']),
};

LoadingBar.defaultProps = {
  color: 'mint',
  size: 'small',
  tint: 'neutral',
};

export default LoadingBar;

Set example component back to original state to keep the PR small and focused


const app = require('./server.js');
const http = require('http');
const https = require('https');
const port = process.env.PORT || 8080;
const httpsPort = process.env.HTTPS_PORT || 8443;
const socketio = require('socket.io');
const chatSockets = require('./sockets/group-chat-sockets.js');
const eventSockets = require('./sockets/event-sockets.js');
const fs = require('fs');

if (process.env.HTTPS_CERT) {
  const credentials = {
    key: process.env.HTTPS_KEY,
    cert: process.env.HTTPS_CERT
  };
} else {
  const credentials = {
    key: fs.readFileSync('privkey.pem'),
    cert: fs.readFileSync('fullchain.pem')
  };
}

const httpsServer = https.createServer(credentials, app);
const io = socketio(httpsServer);
app.io = io;
chatSockets(io);
eventSockets(io);

const httpsRedirect = http.createServer((req, res) => {
  res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url }).end();
});

httpsRedirect.listen(port, () => console.log('http listening on port:', port, 'to redirect to https'));

httpsServer.listen(httpsPort, () => console.log('https listening on port:', httpsPort));

const app = require('./server.js');
const http = require('http');
const https = require('https');
const port = process.env.PORT || 8080;
const httpsPort = process.env.HTTPS_PORT || 8443;
const socketio = require('socket.io');
const chatSockets = require('./sockets/group-chat-sockets.js');
const eventSockets = require('./sockets/event-sockets.js');
const fs = require('fs');

const credentials = {};

if (process.env.HTTPS_CERT) {
  credentials.key = process.env.HTTPS_KEY;
  credentials.cert = process.env.HTTPS_CERTl;
} else {
  credentials.key = fs.readFileSync('privkey.pem');
  cerdentials.cert = fs.readFileSync('fullchain.pem');
}
console.log(typeof process.env.HTTPS_CERT);

const httpsServer = https.createServer(credentials, app);
const io = socketio(httpsServer);
app.io = io;
chatSockets(io);
eventSockets(io);

const httpsRedirect = http.createServer((req, res) => {
  res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url }).end();
});

httpsRedirect.listen(port, () => console.log('http listening on port:', port, 'to redirect to https'));

httpsServer.listen(httpsPort, () => console.log('https listening on port:', httpsPort));

Split cert as travis was not instantiating it


(function (angular){
  'use strict';

  angular.module('app')
    .controller('counterController', counterController)
    .controller('todoController', todoController)

    counterController.$inject = []
    todoController.$inject = []

    function counterController(){
      this.counter = 0;

      this.add = function() {
       this.counter >= 10 ? this.counter : this.counter ++;
      }

      this.sub = function(){
        this.counter === 0 ? this.counter : this.counter --;
      }
    };

    function todoController(){
      this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}];
      this.newTask = '';
      this.completed = 1;
      this.total = this.tasks.length;

      this.add = function(){
        console.log(this.newTask)
        this.tasks.push({name: this.newTask, complete: false});

        this.total = this.tasks.length;
      }.bind(this)

      this.complete = function(taskIndex){
        console.log(taskIndex);
        this.tasks[taskIndex].complete = true;
        this.
         this.completed = this.tasks.reduce(function(p, n){
          return n.complete === true ? p + 1 : p;
        }, 0);

        this.removeCompleted= function(){

        };

      }

    }

})(window.angular);

(function (angular){
  'use strict';

  angular.module('app')
    .controller('counterController', counterController)
    .controller('todoController', todoController)

    counterController.$inject = []
    todoController.$inject = []

    function counterController(){
      this.counter = 0;

      this.add = function() {
       this.counter >= 10 ? this.counter : this.counter ++;
      }

      this.sub = function(){
        this.counter === 0 ? this.counter : this.counter --;
      }
    };

    function todoController(){
      this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}];
      this.newTask = '';
      this.completed = 1;
      this.total = this.tasks.length;
      this.showCompleted = true

      this.add = function(){
        console.log(this.newTask)
        this.tasks.push({name: this.newTask, complete: false});
        this.newTask = ''
        this.total = this.tasks.length;
      }.bind(this)

      this.complete = function(taskIndex){
        console.log(taskIndex);
        this.tasks[taskIndex].complete = true;

         this.completed = this.tasks.reduce(function(p, n){
          return n.complete === true ? p + 1 : p;
        }, 0);
      }

      this.hideCompleted= function(){
        showCompleted = false
        };

    }

})(window.angular);

Fix input submit, now clear itself after submit


function merge(a, b) {
  var r = {};
  for (var i=0;i<a.length;++i) {
    r[a[i]] = b[i];
  }
  return r;
}

function Houkou(pattern) {
  this.parameters = (pattern.match(/:([a-z_]+)/gi) || []).map(function(p) { return p.substr(1); });
  this.pattern = new RegExp(("^" + pattern.replace(/:[a-z_]+?!\(|:[a-z_]+$/gi, "(.+?)").replace(/:[a-z_]+/gi, "") + "$").replace(/\//g, "\\/"));
  this.build = new Function("v", 'return "' + pattern.replace(/:([a-z_]+)(?:\(.*?\))?/gi, '" + v["$1"] + "') + '";');
}

Houkou.prototype.match = function(url) {
  var matches;

  if (matches = this.pattern.exec(url)) {
    matches.shift();
    return merge(this.parameters, matches);
  }
};

(typeof module === "object") && (module.exports = Houkou);

function merge(a, b) {
  var r = {};
  for (var i=0;i<a.length;++i) {
    r[a[i]] = b[i];
  }
  return r;
}

function Houkou(pattern) {
  if (!(this instaceof Houkou) {
    return new Houkou(pattern);
  }
  this.parameters = (pattern.match(/:([a-z_]+)/gi) || []).map(function(p) { return p.substr(1); });
  this.pattern = new RegExp(("^" + pattern.replace(/:[a-z_]+?!\(|:[a-z_]+$/gi, "(.+?)").replace(/:[a-z_]+/gi, "") + "$").replace(/\//g, "\\/"));
  this.build = new Function("v", 'return "' + pattern.replace(/:([a-z_]+)(?:\(.*?\))?/gi, '" + v["$1"] + "') + '";');
}

Houkou.prototype.match = function(url) {
  var matches;

  if (matches = this.pattern.exec(url)) {
    matches.shift();
    return merge(this.parameters, matches);
  }
};

(typeof module === "object") && (module.exports = Houkou);

Make sure Houkou won't attempt to add "parameters", "pattern" and "build" as globals when the user called it without using "new"


"use strict";

var Spawner = require("./spawner.js");

var api = function(server) {
  var options = {};
  var port = 8000;
  if(typeof arguments[1] == "object") {
    options = arguments[1];
    port = options.port || port;
  } else if(typeof arguments[1] == "number") {
    port = arguments[1];
    if(typeof arguments[2] == "object") {
      options = arguments[2];
    }
  }
  var logger = options.logger || console;
  var workers = options.workers || 4;

  return new Spawner(server, port, logger);
};

module.exports = api;

"use strict";

var Spawner = require("./spawner.js");

var api = function(server) {
  var options = {};
  var port = 8000;
  if(typeof arguments[1] == "object") {
    options = arguments[1];
    port = options.port || port;
  } else if(typeof arguments[1] == "number") {
    port = arguments[1];
    if(typeof arguments[2] == "object") {
      options = arguments[2];
    }
  }
  var logger = options.logger || console;
  var workers = options.workers || 4;

  return new Spawner(server, port, workers, logger);
};

module.exports = api;

Send the amount of workers


const ServerChannel = require('./ServerChannel');
const VoiceChannelDataStore = require('./datastore/VoiceChannelDataStore');

class VoiceChannel extends ServerChannel {
  constructor(guild, data) {
    super(guild, data);
    this.store = new VoiceChannelDataStore();
  }

  setup(data) {
    super.setup(data);
    this.bitrate = data.bitrate;
  }
}

module.exports = VoiceChannel;

const ServerChannel = require('./ServerChannel');
const VoiceChannelDataStore = require('./datastore/VoiceChannelDataStore');

class VoiceChannel extends ServerChannel {
  constructor(guild, data) {
    super(guild, data);
    this.store = new VoiceChannelDataStore();
  }

  setup(data) {
    super.setup(data);
    this.bitrate = data.bitrate;
    this.userLimit = data.user_limit;
  }
}

module.exports = VoiceChannel;

Add userLimit param to voice channel


import React  from 'react';

export default class HireMe extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    if (!this.props.availableForWork) {
      return
Sorry, I'm not looking for a job now.
;
    }

    return (

        Interested to hire me (remote please) ? Send me a mail. No agencies sorry.

    );
  }
}

Hide HireMe component on print


var esformatter = require( 'esformatter' );
esformatter.register( require( '../lib/plugin' ) );

var fs = require( 'fs' );
var path = require( 'path' );

var files = fs.readdirSync( './entry/' );

files.forEach( function ( file ) {
  var codeStr = fs.readFileSync( './entry/' + file ).toString();
  var formattedCode = esformatter.format( codeStr, {
    'whiteSpace': {
      'value': ' ',
      'removeTrailing': 1,
      'before': {
        ObjectPatternClosingBrace: 1
      },
      'after': {
        ObjectPatternOpeningBrace: 1
      },
    },
    'jsx': {
      'formatJSX': true,
      'attrsOnSameLineAsTag': true,
      'maxAttrsOnTag': 3,
      'firstAttributeOnSameLine': true,
      'spaceInJSXExpressionContainers': ' ',
      'alignWithFirstAttribute': false,
      'formatJSXExpressions': false,
      'htmlOptions': {
        'brace_style': 'collapse',
        'indent_char': ' ',
        'indent_size': 2,
        'max_preserve_newlines': 2,
        'preserve_newlines': true
      }
    }
  } );

  fs.writeFileSync( './result/' + path.basename( file ), formattedCode );

} );

var esformatter = require( 'esformatter' );
esformatter.register( require( '../lib/plugin' ) );

var fs = require( 'fs' );
var path = require( 'path' );

var files = fs.readdirSync( './entry/' );

files.forEach( function ( file ) {
  var codeStr = fs.readFileSync( './entry/' + file ).toString();
  var options = {
    'whiteSpace': {
      'value': ' ',
      'removeTrailing': 1,
      'before': {
        ObjectPatternClosingBrace: 1
      },
      'after': {
        ObjectPatternOpeningBrace: 1
      },
    },
    'jsx': {
      'formatJSX': true,
      'attrsOnSameLineAsTag': true,
      'maxAttrsOnTag': 3,
      'firstAttributeOnSameLine': true,
      'spaceInJSXExpressionContainers': ' ',
      'alignWithFirstAttribute': false,
      'formatJSXExpressions': false,
      'htmlOptions': {
        'brace_style': 'collapse',
        'indent_char': ' ',
        'indent_size': 2,
        'max_preserve_newlines': 2,
        'preserve_newlines': true
      }
    }
  };
  var formattedCode = esformatter.format( codeStr, options );

  fs.writeFileSync( './result/' + path.basename( file ), formattedCode );

  var reformattedCode = esformatter.format( formattedCode, options );
  if (formattedCode !== reformattedCode) {
    throw new Error( 'Expected ' + file + ' to reformat to the same result' );
  }
} );

Reformat within demo to ensure equal results


window.c.AdminUserDetail = (function(m, _, c){
    return {
        controller: function(){
            return {
                actions: {
                    reset: {
                        property: 'user_password',
                        updateKey: 'password',
                        callToAction: 'Redefinir',
                        innerLabel: 'Nova senha de Usuário:',
                        outerLabel: 'Redefinir senha',
                        placeholder: 'ex: 123mud@r',
                        model: c.models.userDetail
                    },
                    reactivate: {
                        property: 'state',
                        updateKey: 'id',
                        callToAction: 'Reativar',
                        innerLabel: 'Tem certeza que deseja reativar esse usuário?',
                        outerLabel: 'Reativar usuário',
                        forceValue: 'deleted',
                        model: c.models.userDetail
                    }
                }
            };
        },

        view: function(ctrl, args){
            var actions = ctrl.actions,
                item = args.item,
                details = args.details;
            return m('#admin-contribution-detail-box', [
                m('.divider.u-margintop-20.u-marginbottom-20'),
                m('.w-row.u-marginbottom-30', [
                    m.component(c.AdminInputAction, {data: actions.reset, item: item}),
                    m.component(c.AdminInputAction, {data: actions.reactivate, item: item})
                ]),
            ]);
        }
    };
}(window.m, window._, window.c));

window.c.AdminUserDetail = (function(m, _, c){
    return {
        controller: function(){
            return {
                actions: {
                    reset: {
                        property: 'user_password',
                        updateKey: 'password',
                        callToAction: 'Redefinir',
                        innerLabel: 'Nova senha de Usuário:',
                        outerLabel: 'Redefinir senha',
                        placeholder: 'ex: 123mud@r',
                        model: c.models.userDetail
                    },
                    reactivate: {
                        property: 'state',
                        updateKey: 'id',
                        callToAction: 'Reativar',
                        innerLabel: 'Tem certeza que deseja reativar esse usuário?',
                        outerLabel: 'Reativar usuário',
                        forceValue: 'deleted',
                        model: c.models.userDetail
                    }
                }
            };
        },

        view: function(ctrl, args){
            var actions = ctrl.actions,
                item = args.item,
                details = args.details;
            return m('#admin-contribution-detail-box', [
                m('.divider.u-margintop-20.u-marginbottom-20'),
                m('.w-row.u-marginbottom-30', [
                    m.component(c.AdminInputAction, {data: actions.reset, item: item}),
                    (item.deactivated_at) ?
                    m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : ''
                ]),
            ]);
        }
    };
}(window.m, window._, window.c));

Add validation to show reactivate button to AdminUser list


import { createStore, combineReducers } from 'redux';
import header from './header';
import device from './device';

const types = {
  ACTIVE: 'module_active',
  LOGIN: 'app_login'
};

export { types }; // MUST put before reducers define

const reducers = combineReducers({
  header,
  device
});

export default createStore(reducers);

import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import header from './header';
import device from './device';

const types = {
  ACTIVE: 'module_active',
  LOGIN: 'app_login'
};

export { types }; // MUST put before reducers define

const reducers = combineReducers({
  header,
  device
});

export default createStore(reducers, applyMiddleware(thunkMiddleware));

Introduce redux-thunk for async actions


var goToUrlAndSetLocalStorage = require('../../../shared/specUtils').goToUrlAndSetLocalStorage;
var waitForPatientView = require('../../../shared/specUtils').waitForPatientView;
var assertScreenShotMatch = require('../../../shared/lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
const patienViewUrl = CBIOPORTAL_URL+'/patient?studyId=teststudy_genepanels&caseId=patientA';

describe('patient view page', function() {

    describe('gene panel icons', () => {

        const iconIndexGenePanelSample = 2;
        const iconIndexWholeGenomeSample = 3;

        beforeEach(()=>{
            goToUrlAndSetLocalStorage(patienViewUrl);
            waitForPatientView();
        });

        it('shows gene panel icons behind mutation and CNA genomic tracks',() => {
            var res = browser.checkElement('div.genomicOverviewTracksContainer');
            assertScreenShotMatch(res);
        });

        it('filters mutation tracks based on gene filter setting',() => {
            var filterIcon = $('div[data-test=patientview-mutation-table]').$('i[data-test=gene-filter-icon]');
            filterIcon.click();
            var selectMenu = $('.rc-tooltip');
            const allGenesRadio = selectMenu.$('input[value=allSamples]');
            allGenesRadio.click();
            var res = browser.checkElement('div.qtip-content');
            assertScreenShotMatch(res);
        });

    });

});

var goToUrlAndSetLocalStorage = require('../../../shared/specUtils').goToUrlAndSetLocalStorage;
var waitForPatientView = require('../../../shared/specUtils').waitForPatientView;
var assertScreenShotMatch = require('../../../shared/lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
const patienViewUrl = CBIOPORTAL_URL+'/patient?studyId=teststudy_genepanels&caseId=patientA';

describe('patient view page', function() {

    describe('gene panel icons', () => {

        const iconIndexGenePanelSample = 2;
        const iconIndexWholeGenomeSample = 3;

        beforeEach(()=>{
            goToUrlAndSetLocalStorage(patienViewUrl);
            waitForPatientView();
        });

        it('shows gene panel icons behind mutation and CNA genomic tracks',() => {
            var res = browser.checkElement('div.genomicOverviewTracksContainer');
            assertScreenShotMatch(res);
        });

        it('filters mutation tracks based on gene filter setting',() => {
            var filterIcon = $('div[data-test=patientview-mutation-table]').$('i[data-test=gene-filter-icon]');
            filterIcon.click();
            var selectMenu = $('.rc-tooltip');
            const allGenesRadio = selectMenu.$('input[value=allSamples]');
            allGenesRadio.click();
            var res = browser.checkElement('div.genomicOverviewTracksContainer');
            assertScreenShotMatch(res);
        });

    });

});

Correct reference to genomic tracks container


import demoTest from '../../../tests/shared/demoTest';

demoTest('table', {
  skip: process.env.REACT === '15' ? ['edit-row'] : [],
});

import demoTest from '../../../tests/shared/demoTest';

demoTest('table', {
  skip: process.env.REACT === '15' ? ['edit-row', 'drag-sorting'] : [],
});

Fix react-dnd demo broken in react 15


'use strict';

// MODULES //

var root = require( 'system.global' )(); // eslint-disable-line no-redeclare

// MAIN //

var nodeList = root.document && root.document.childNodes;

// EXPORTS //

module.exports = nodeList;

'use strict';

// MODULES //

var root = require( 'system.global' )(); // eslint-disable-line stdlib/no-redeclare

// MAIN //

var nodeList = root.document && root.document.childNodes;

// EXPORTS //

module.exports = nodeList;

Disable custom rule instead of default one


var quantify      = require('./quantifier');
var _escapeRegExp = require('./escaper').escapeRegExp;
var _translate    = require('./specialIdentifiers').translate;

var interpret = function(userArguments) {
    switch (userArguments.length) {
        case 2:
            return _makeNumberedConstraint(userArguments[0], userArguments[1]);
        case 1:
            return _makePatternedConstraint(userArguments[0]);
        default:
            throw new Error('interpret: wrong number of arguments: got ' + userArguments.length + ', expected 1 or 2');
    }
};

var _makeNumberedConstraint = function(count, type) {
    return quantify.exactly(_makePatternedConstraint(type), count);
};

var _makePatternedConstraint = function(pattern) {
    return _translate(_escapeRegExp(pattern));
};

module.exports = {
    interpret: interpret
};

var quantify      = require('./quantifier');
var _escapeRegExp = require('./escaper').escapeRegExp;
var _translate    = require('./specialIdentifiers').translate;

var interpret = function(userArguments) {
    return constraintBuilderFromArgCount[userArguments.length].apply(null, userArguments);
};

var _buildNumberedConstraint = function(count, type) {
    return quantify.exactly(_buildPatternedConstraint(type), count);
};

var _buildPatternedConstraint = function(pattern) {
    return _translate(_escapeRegExp(pattern));
};

var constraintBuilderFromArgCount = {
    1: _buildPatternedConstraint,
    2: _buildNumberedConstraint
};

module.exports = {
    interpret: interpret
};

Replace switch statement with an object literal.


module.exports = async (client, message) => {
  if (message === 'shutdown') {
    await client.log.info(`Shuting down!${client.shard ? ` | Shard ID: ${client.shard.id}` : ''}`, 'Client')
    await client.provider.destroy()
    await client.destroy()
    await process.exit(0)
  }
}

module.exports = async (client, message) => {
  if (message === 'shutdown') {
    await client.log.info(`Shuting down!${client.shard ? ` | Shard ID: ${client.shard.id}` : ''}`, 'Client')
    // Code to run before shutdown
    // ...
    process.exit(0)
  }
}

Fix bot not shutting down.


// import libraries
// react dom and app

// reactdom.render(app, document.get by id)

import ReactDOM from 'react-dom';
import App from 'components/app';

ReactDOM.render(<App />, document.getElementById('app'));

// import libraries
// react dom and app

// reactdom.render(app, document.get by id)

import ReactDOM from 'react-dom';
import App from './components/app';

ReactDOM.render(<App />, document.getElementById('app'));

Clarify directory location of app


var site= '../site'
var map= {
  localhost: site
 ,'127.0.0.1': site
}
extractHostFromHost= /([^:]+).*/

module.exports= function(req) {
  return map[req.headers.host.replace(extractHostFromHost,'$1')]
}

var site= '../site'
var map= {
  localhost: site
 ,'127.0.0.1': site
}

module.exports= function(req) {
  return map[req.malifi.utils.hostname()]
}

Use req.malifi.utils to get hostname


$(document).ready(function() {

 	$(".login_btn").on("click", function(event){
 			event.preventDefault();
 			console.log("YOU CLICKED");
 			$(".login_form").toggle();
 	});

 	$(".signup_btn").on("click", function(event){
 			event.preventDefault();
 			console.log("YOU CLICKED");
 			$(".signup_form").toggle();
 	});

});

$(document).ready(function() {

 	$(".login_btn").on("click", function(event){
 			event.preventDefault();
 			console.log("YOU CLICKED");
 			$(".login_form").toggle();
 	});

 	$(".signup_btn").on("click", function(event){
 			event.preventDefault();
 			console.log("YOU CLICKED");
 			$(".signup_form").toggle();
 	});

 	$(".login_ajax").on("submit", function(event){
		event.preventDefault();
		var $form = $(event.target)

		$.ajax({
			url:  $form.attr('action'),
			type: $form.attr('method'),
			data: $form.serialize(),
			success: function(response){
				$(".auth_btns").remove();
				$("#content").prepend(response);
				console.log(response);
			},
			error: function(){

			}
		});
	});

});

Add ajax -to success- for login


var i2c = require('i2c');
var _ = require('lodash');
var utils = require('./utils');

var BH1750 = function (opts) {
    this.options = _.extend({}, {
        address: 0x23,
        device: '/dev/i2c-1',
        command: 0x10,
        length: 2
    }, opts);
    this.verbose = this.options.verbose || false;
    this.wire = new i2c(this.options.address, {device: this.options.device});
};

BH1750.prototype.readLight = function (cb) {
    var self = this;
    if (!utils.exists(cb)) {
        throw new Error("Invalid param");
    }
    self.wire.readBytes(self.options.command, self.options.length, function (err, res) {
        if (utils.exists(err)) {
            if (self.verbose)
                console.error("error: I/O failure on BH1750 - command: ", self.options.command);
            return cb(err, null);
        }
        var hi = res.readUInt8(0);
        var lo = res.readUInt8(1);
        var lux = ((hi << 8) + lo)/1.2;
        if (self.options.command = 0x11) {
            lux = lux/2;
        }
        cb(null, lux);
    });
};

module.exports = BH1750;

var i2c = require('i2c');
var _ = require('lodash');
var utils = require('./utils');

var BH1750 = function (opts) {
    this.options = _.extend({}, {
        address: 0x23,
        device: '/dev/i2c-1',
        command: 0x10,
        length: 2
    }, opts);
    this.verbose = this.options.verbose || false;
    this.wire = new i2c(this.options.address, {device: this.options.device});
};

BH1750.prototype.readLight = function (cb) {
    var self = this;
    if (!utils.exists(cb)) {
        throw new Error("Invalid param");
    }
    self.wire.readBytes(self.options.command, self.options.length, function (err, res) {
        if (utils.exists(err)) {
            if (self.verbose)
                console.error("error: I/O failure on BH1750 - command: ", self.options.command);
            return cb(err, null);
        }
        var hi = res.readUInt8(0);
        var lo = res.readUInt8(1);
        var lux = ((hi << 8) + lo)/1.2;
        if (self.options.command === 0x11) {
            lux = lux/2;
        }
        cb(null, lux);
    });
};

module.exports = BH1750;

Fix comparaison of command (== 0x11) for half lx