<commit_before>import { Sequence, Parallel, Primitive } from './primitives'
import { FunctionTreeError } from './errors'

function getFunctionName(fn) {
  if (fn.displayName) return fn.displayName
  if (fn.name) return fn.name

  let ret = fn.toString()

  let startNameMatch
  if (ret.indexOf('async function') === 0) startNameMatch = 'async function '
  else if (ret.indexOf('function') === 0) startNameMatch = 'function '

  ret = ret.substr(startNameMatch ? startNameMatch.length : 0)
  ret = ret.substr(0, ret.indexOf('('))

  return ret
}

function isPaths(item) {
  return (
    item &&
    !Array.isArray(item) &&
    typeof item === 'object' &&
    !(item instanceof Primitive)
  )
}

function stringifyInvalidTreeItem(items, invalidItem) {
  return `
[
${items
    .map(item => {
      if (item === invalidItem) {
        return `  ${typeof invalidItem} <-- PROBLEM`
      }
      if (typeof item === 'function') {
        return `  ${getFunctionName(item)}`
      }
      if (item instanceof Primitive) {
        return `  [ ${item.type.toUpperCase()} ]`
      }
      if (Array.isArray(item)) {
        return `  [ SEQUENCE ]`
      }

      return `  { PATHS }`
    })
    .join('\n')}
]
  `
}

function analyze(name, functions, item, isParallel) {
  if (item instanceof Primitive) {
    const instance = item.toJSON()

    return Object.assign(instance, {
      items: analyze(name, functions, instance.items, item instanceof Parallel)
        .items,
    })
  } else if (Array.isArray(item)) {
    return new Sequence(
      item.reduce((allItems, subItem, index) => {
        if (subItem instanceof Primitive) {
          const instance = subItem.toJSON()

          return allItems.concat(
            Object.assign(instance, {
              items: analyze(
                name,
                functions,
                instance.items,
                subItem instanceof Parallel
              ).items,
            })
          )
        } else if (typeof subItem === 'function') {
          const funcDetails = {
            name: subItem.displayName || getFunctionName(subItem),
            functionIndex: functions.push(subItem) - 1,
            function: subItem,
          }
          const nextItem = item[index + 1]

          if (isPaths(nextItem)) {
            funcDetails.outputs = {}
            Object.keys(nextItem).forEach(key => {
              if (subItem.outputs && !~subItem.outputs.indexOf(key)) {
                throw new FunctionTreeError(
                  `Outputs object doesn't match list of possible outputs defined for function.`
                )
              }
              funcDetails.outputs[key] = analyze(
                name,
                functions,
                typeof nextItem[key] === 'function'
                  ? [nextItem[key]]
                  : nextItem[key]
              )
            })
          }

          return allItems.concat(funcDetails)
        } else if (isPaths(subItem)) {
          return allItems
        } else if (Array.isArray(subItem)) {
          const items = analyze(name, functions, subItem)

          return allItems.concat(items)
        } else {
          throw new FunctionTreeError(
            `Unexpected entry in "${name}". ${stringifyInvalidTreeItem(
              item,
              subItem
            )}`
          )
        }
      }, [])
    ).toJSON()
  } else {
    throw new FunctionTreeError('Unexpected entry in tree')
  }
}

export default (name, tree) => {
  const functions = []

  return analyze(name, functions, typeof tree === 'function' ? [tree] : tree)
}
<commit_msg>feat(function-tree): improve error report of static tree<commit_after>import { Sequence, Parallel, Primitive } from './primitives'
import { FunctionTreeError } from './errors'

function getFunctionName(fn) {
  if (fn.displayName) return fn.displayName
  if (fn.name) return fn.name

  let ret = fn.toString()

  let startNameMatch
  if (ret.indexOf('async function') === 0) startNameMatch = 'async function '
  else if (ret.indexOf('function') === 0) startNameMatch = 'function '

  ret = ret.substr(startNameMatch ? startNameMatch.length : 0)
  ret = ret.substr(0, ret.indexOf('('))

  return ret
}

function isPaths(item) {
  return (
    item &&
    !Array.isArray(item) &&
    typeof item === 'object' &&
    !(item instanceof Primitive)
  )
}

function stringifyInvalidTreeItem(items, invalidItem) {
  return `
[
${items
    .map(item => {
      if (item === invalidItem) {
        return `  ${typeof invalidItem}, <-- PROBLEM`
      }
      if (typeof item === 'function') {
        return `  ${getFunctionName(item)},`
      }
      if (item instanceof Primitive) {
        return `  [ ${item.type.toUpperCase()} ],`
      }
      if (Array.isArray(item)) {
        return `  [ SEQUENCE ],`
      }

      return `  { PATHS },`
    })
    .join('\n')}
]
  `
}

function analyze(name, functions, item, isParallel) {
  if (item instanceof Primitive) {
    const instance = item.toJSON()

    return Object.assign(instance, {
      items: analyze(name, functions, instance.items, item instanceof Parallel)
        .items,
    })
  } else if (Array.isArray(item)) {
    return new Sequence(
      item.reduce((allItems, subItem, index) => {
        if (subItem instanceof Primitive) {
          const instance = subItem.toJSON()

          return allItems.concat(
            Object.assign(instance, {
              items: analyze(
                name,
                functions,
                instance.items,
                subItem instanceof Parallel
              ).items,
            })
          )
        } else if (typeof subItem === 'function') {
          const funcDetails = {
            name: subItem.displayName || getFunctionName(subItem),
            functionIndex: functions.push(subItem) - 1,
            function: subItem,
          }
          const nextItem = item[index + 1]

          if (isPaths(nextItem)) {
            funcDetails.outputs = {}
            Object.keys(nextItem).forEach(key => {
              if (subItem.outputs && !~subItem.outputs.indexOf(key)) {
                throw new FunctionTreeError(
                  `Outputs object doesn't match list of possible outputs defined for function.`
                )
              }
              funcDetails.outputs[key] = analyze(
                name,
                functions,
                typeof nextItem[key] === 'function'
                  ? [nextItem[key]]
                  : nextItem[key]
              )
            })
          }

          return allItems.concat(funcDetails)
        } else if (isPaths(subItem)) {
          return allItems
        } else if (Array.isArray(subItem)) {
          const items = analyze(name, functions, subItem)

          return allItems.concat(items)
        } else {
          throw new FunctionTreeError(
            `Unexpected entry in "${name}". ${stringifyInvalidTreeItem(
              item,
              subItem
            )}`
          )
        }
      }, [])
    ).toJSON()
  } else {
    throw new FunctionTreeError('Unexpected entry in tree')
  }
}

export default (name, tree) => {
  const functions = []

  return analyze(name, functions, typeof tree === 'function' ? [tree] : tree)
}
<|endoftext|>


<commit_before>import React from 'react';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import RESOURCE_TYPES from 'common/RESOURCE_TYPES';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from "common/format";
import { formatNumber } from "../../../../common/format";

//1000ms/45focus = 22.2ms/focus

const debug = true;

class Tier19_2p extends Module {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  effectiveTrueshotReductionMs = 0;
  wastedTrueshotReductionMs = 0;

  focusUpdates = [];

  on_initialized() {
    this.active = this.combatants.selected.hasBuff(SPELLS.HUNTER_MM_T19_2P_BONUS.id);
  }
  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.AIMED_SHOT.id && spellId !== SPELLS.PIERCING_SHOT_TALENT.id && spellId !== SPELLS.BURSTING_SHOT.id && spellId !== SPELLS.MARKED_SHOT.id && spellId !== SPELLS.WINDBURST.id) {
      return;
    }
    if (event.classResources) {
      event.classResources
        .filter(resource => resource.type === RESOURCE_TYPES.FOCUS)
        .forEach(({ cost }) => {
          const focusCost = cost || 0;
          this.focusUpdates.unshift({
            used: focusCost,
          });
        });
    }
    debug && console.log(`focusUpdates is now at: `, this.focusUpdates[0].used);
    const COOLDOWN_REDUCTION_MS = 22.22222 * this.focusUpdates[0].used;
    const trueshotIsOnCooldown = this.spellUsable.isOnCooldown(SPELLS.TRUESHOT.id);
    if (trueshotIsOnCooldown) {
      const reductionMs = this.spellUsable.reduceCooldown(SPELLS.TRUESHOT.id, COOLDOWN_REDUCTION_MS);
      this.effectiveTrueshotReductionMs += reductionMs;
    } else {
      this.wastedTrueshotReductionMs += COOLDOWN_REDUCTION_MS;
    }
  }
  a
  item() {
    return {
      id: `spell-${SPELLS.HUNTER_MM_T19_2P_BONUS.id}`,
      icon: <SpellIcon id={SPELLS.TRUESHOT.id} />,
      title: <SpellLink id={SPELLS.HUNTER_MM_T19_2P_BONUS.id} />,
      result: (
        <dfn data-tip={`Your utilization of tier 19 2 piece:
 You effectively reduced Trueshots cooldown by: ${formatNumber(this.effectiveTrueshotReductionMs / 1000)} seconds.
 You wasted   ${formatNumber(this.wastedTrueshotReductionMs / 1000)} seconds of CDR.
 `}>
          T19 2p CDR effectiveness: {formatPercentage(this.effectiveTrueshotReductionMs / (this.effectiveTrueshotReductionMs + this.wastedTrueshotReductionMs))}%
        </dfn>
      ),
    };
  }
}

export default Tier19_2p;
<commit_msg>debug to false, and moved clarification as to why cdr is 22.2 down so it's clearer<commit_after>import React from 'react';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import RESOURCE_TYPES from 'common/RESOURCE_TYPES';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from "common/format";
import { formatNumber } from "../../../../common/format";

const debug = false;

class Tier19_2p extends Module {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  effectiveTrueshotReductionMs = 0;
  wastedTrueshotReductionMs = 0;

  focusUpdates = [];

  on_initialized() {
    this.active = this.combatants.selected.hasBuff(SPELLS.HUNTER_MM_T19_2P_BONUS.id);
  }
  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.AIMED_SHOT.id && spellId !== SPELLS.PIERCING_SHOT_TALENT.id && spellId !== SPELLS.BURSTING_SHOT.id && spellId !== SPELLS.MARKED_SHOT.id && spellId !== SPELLS.WINDBURST.id) {
      return;
    }
    if (event.classResources) {
      event.classResources
        .filter(resource => resource.type === RESOURCE_TYPES.FOCUS)
        .forEach(({ cost }) => {
          const focusCost = cost || 0;
          this.focusUpdates.unshift({
            used: focusCost,
          });
        });
    }
    debug && console.log(`focusUpdates is now at: `, this.focusUpdates[0].used);
    //1000ms/45focus = 22.2ms/focus
    const COOLDOWN_REDUCTION_MS = 22.22222 * this.focusUpdates[0].used;
    const trueshotIsOnCooldown = this.spellUsable.isOnCooldown(SPELLS.TRUESHOT.id);
    if (trueshotIsOnCooldown) {
      const reductionMs = this.spellUsable.reduceCooldown(SPELLS.TRUESHOT.id, COOLDOWN_REDUCTION_MS);
      this.effectiveTrueshotReductionMs += reductionMs;
    } else {
      this.wastedTrueshotReductionMs += COOLDOWN_REDUCTION_MS;
    }
  }
  a
  item() {
    return {
      id: `spell-${SPELLS.HUNTER_MM_T19_2P_BONUS.id}`,
      icon: <SpellIcon id={SPELLS.TRUESHOT.id} />,
      title: <SpellLink id={SPELLS.HUNTER_MM_T19_2P_BONUS.id} />,
      result: (
        <dfn data-tip={`Your utilization of tier 19 2 piece:
 You effectively reduced Trueshots cooldown by: ${formatNumber(this.effectiveTrueshotReductionMs / 1000)} seconds.
 You wasted   ${formatNumber(this.wastedTrueshotReductionMs / 1000)} seconds of CDR.
 `}>
          T19 2p CDR effectiveness: {formatPercentage(this.effectiveTrueshotReductionMs / (this.effectiveTrueshotReductionMs + this.wastedTrueshotReductionMs))}%
        </dfn>
      ),
    };
  }
}

export default Tier19_2p;
<|endoftext|>


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

var is_array = function(a) {
	"use strict";
    return Array.isArray(a);
};

var is_object = function(obj) {
	"use strict";
    return obj === Object(obj);
};

var is_string = function(str) {
	"use strict";
	return typeof str == 'string' || str instanceof String;
};

var is_number = function(n) {
	"use strict";
	return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
};
var is_int = function(n) {
	"use strict";
	return parseInt(n,10) === n;
};

var is_float = function(n) {
	"use strict";
	return is_number(n) && ! is_int(n);
};

var renderOutputModel = module.exports.renderOutputModel = function(format, models, original, url_params){
	"use strict";
	var ret = {};
	var i = 0;
	try {
		if (format.type) {
			if (is_array(format.type)) {
				ret = [];
				for (i = 0; i < parseInt(format.number,10); i++) {
					var url_params2 = url_params || {};
					url_params2.index = i;
					ret.push(renderOutputModel(format.model, models, original, url_params2));
				}
			}
		}
		else {
			if (is_object(format)) {
				for (i = 0; i < Object.keys(format).length; i++) {
					var attr = Object.keys(format)[i];
					ret[attr] = renderOutputModel(format[attr], models, original, url_params);
				}
			}
			else {
				if (is_string(format)) {
					if (models[format]) {
						return models[format]({
							params:url_params
						});
					}
					else {
						console.log("renderOutputModel", original);
						throw "Error Model " + format;
					}
				}
				else {
					console.log("renderOutputModel",original);
					throw "Error Model " + format;
				}
			}
		}
	}
	catch (e){
		console.log("renderOutputModel",e,e.stack);
		return null;
	}

	return ret;
};

var is_model = function (obj, models){
	"use strict";
	for (var i = 0; i < Object.keys(models).length; i++) {
		var attr = Object.keys(models)[i];
		var found = true;
		if (Object.keys(obj).length != Object.keys(models[attr]()).length) {
			found = false;
		}
		for (var j = 0; found && j < Object.keys(models[attr]()).length; j++) {
			//console.log(obj);
			var at = Object.keys(models[attr]())[j];
			if (obj[at] === undefined) {
				found = false;
				break;
			}
		}

		if(found) {
			return attr;
		}
	}
	//console.log("FOUND",obj);
	return false;
};

var rendermodel = function(model,models){
	"use strict";
	var ret = {};
	for (var i = 0; i < Object.keys(model).length; i++) {
		var attr = Object.keys(model)[i];
		var val = model[attr];
		if (is_number(val)) {
			if (is_int(val)) {
				ret[attr] = "Int";
			}
			else {
				ret[attr] = "Float";
			}
		}
		else if (val === true || val === false) {
			ret[attr] = "Bool";
		}
		else {
			if (is_string(val) || val === null || val === undefined){
				ret[attr] = "String";
			}
			else {
				if (is_array(val)) {
					var m = "Undefined";
					if (val.length) {
						m = is_model(val[0],models);
					}
					ret[attr] = "array<"+m+">";
				}
				else {
					var my_model = is_model(val, models);
					if (is_object(val) && !my_model) {
						ret[attr] = "Undefined model";//rendermodel(val, models);
					}
					else {
						ret[attr] = my_model;
					}
				}
			}
		}
	}
	return ret;
};

var renderModelsHtml = module.exports.renderModelsHtml = function(models){
	"use strict";
	var r_models = [];
	for (var i = 0; i < Object.keys(models).length; i++) {
		var attr = Object.keys(models)[i];
		if (attr.indexOf("incomplete") < 0){
			console.log("PROCESS",attr);
			var mod = models[attr]();
			if (mod === null){
				console.log(attr, "model not found");
			}
			else {
				var r_m = {
					name: attr,
					def: rendermodel(mod, models)
				};
				r_models.push(r_m);
			}
		}
	}
	return r_models;
};

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

var is_array = function(a) {
	"use strict";
    return Array.isArray(a);
};

var is_object = function(obj) {
	"use strict";
    return obj === Object(obj);
};

var is_string = function(str) {
	"use strict";
	return typeof str == 'string' || str instanceof String;
};

var is_number = function(n) {
	"use strict";
	return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
};
var is_int = function(n) {
	"use strict";
	return parseInt(n,10) === n;
};

var is_float = function(n) {
	"use strict";
	return is_number(n) && ! is_int(n);
};

var renderOutputModel = module.exports.renderOutputModel = function(format, models, original, params){
	"use strict";
	var ret = {};
	var i = 0;
	try {
		if (format.type) {
			if (is_array(format.type)) {
				ret = [];
				for (i = 0; i < parseInt(format.number,10); i++) {
					var url_params2 = url_params || {};
					url_params2.index = i;
					ret.push(renderOutputModel(format.model, models, original, url_params2));
				}
			}
		}
		else {
			if (is_object(format)) {
				for (i = 0; i < Object.keys(format).length; i++) {
					var attr = Object.keys(format)[i];
					ret[attr] = renderOutputModel(format[attr], models, original, params);
				}
			}
			else {
				if (is_string(format)) {
					if (models[format]) {
						return models[format](params);
					}
					else {
						console.log("renderOutputModel", original);
						throw "Error Model " + format;
					}
				}
				else {
					console.log("renderOutputModel",original);
					throw "Error Model " + format;
				}
			}
		}
	}
	catch (e){
		console.log("renderOutputModel",e,e.stack);
		return null;
	}

	return ret;
};

var is_model = function (obj, models){
	"use strict";
	for (var i = 0; i < Object.keys(models).length; i++) {
		var attr = Object.keys(models)[i];
		var found = true;
		if (Object.keys(obj).length != Object.keys(models[attr]()).length) {
			found = false;
		}
		for (var j = 0; found && j < Object.keys(models[attr]()).length; j++) {
			//console.log(obj);
			var at = Object.keys(models[attr]())[j];
			if (obj[at] === undefined) {
				found = false;
				break;
			}
		}

		if(found) {
			return attr;
		}
	}
	//console.log("FOUND",obj);
	return false;
};

var rendermodel = function(model,models){
	"use strict";
	var ret = {};
	for (var i = 0; i < Object.keys(model).length; i++) {
		var attr = Object.keys(model)[i];
		var val = model[attr];
		if (is_number(val)) {
			if (is_int(val)) {
				ret[attr] = "Int";
			}
			else {
				ret[attr] = "Float";
			}
		}
		else if (val === true || val === false) {
			ret[attr] = "Bool";
		}
		else {
			if (is_string(val) || val === null || val === undefined){
				ret[attr] = "String";
			}
			else {
				if (is_array(val)) {
					var m = "Undefined";
					if (val.length) {
						m = is_model(val[0],models);
					}
					ret[attr] = "array<"+m+">";
				}
				else {
					var my_model = is_model(val, models);
					if (is_object(val) && !my_model) {
						ret[attr] = "Undefined model";//rendermodel(val, models);
					}
					else {
						ret[attr] = my_model;
					}
				}
			}
		}
	}
	return ret;
};

var renderModelsHtml = module.exports.renderModelsHtml = function(models){
	"use strict";
	var r_models = [];
	for (var i = 0; i < Object.keys(models).length; i++) {
		var attr = Object.keys(models)[i];
		if (attr.indexOf("incomplete") < 0){
			console.log("PROCESS",attr);
			var mod = models[attr]();
			if (mod === null){
				console.log(attr, "model not found");
			}
			else {
				var r_m = {
					name: attr,
					def: rendermodel(mod, models)
				};
				r_models.push(r_m);
			}
		}
	}
	return r_models;
};

<|endoftext|>


<commit_before>'use strict';
import _ from 'lodash';
import chalk from 'chalk';
import GenBase from '../genBase';
import mkdirp from 'mkdirp';
import path from 'path';
import pkg from '../../package.json';
import utils from '../utils';
import yosay from 'yosay';

export default class Generator extends GenBase {
  constructor(...args) {
    super(...args);
  }

  get initializing() {
    return function () {
      this.host = this.options.host || 'localhost';
      this.port = this.options.port || 3000;
      this.appDir = this.options['app-dir'] || 'app';
      this.unitTestDir = this.options['unit-test-dir'] || 'app';
      this.skipController = this.options['skip-controller'] || false;

      console.log(chalk.yellow(`Using host: ${this.host}`));
      console.log(chalk.yellow(`Using port: ${this.port}`));
      console.log(chalk.yellow(`Using app directory: ${this.appDir}`));
      console.log(chalk.yellow(`Using unit test directory: ${this.unitTestDir}`));
      console.log(chalk.yellow(`Route generator will
        ${(this.skipController ? chalk.red('NOT ') : '')} create controllers`));
    };
  }

  get prompting() {
    return function () {
      const done = this.async();

      this.log(yosay('Welcome to ngPoly!'));

      // ask for app name
      // get preferred langugaes
      this.prompt([
        {
          name: 'appName',
          message: 'What is the app\'s name?',
          validate: input => !!input
        },
        {
          type: 'list',
          name: 'ngversion',
          message: 'Which version of Angular should be used?',
          default: '1.4.*',
          choices: [
            {
              name: '1.4.*',
              value: '1.4.*'
            },
            {
              name: '1.3.*',
              value: '1.3.*'
            },
            {
              name: '1.2.*',
              value: '1.2.*'
            }
          ]
        },
        {
          type: 'list',
          name: 'structure',
          message: 'Which structure should be used?',
          default: 'module-only',
          choices: [
            {
              name: ['app/',
                    '├── module1/',
                    '│   ├── module2/',
                    '│   ├── module1-module.js',
                    '│   └── module1-controller.js',
                    '└── app.js'].join('\n'),
              value: 'module-only'
            },
            {
              name: ['app/',
                    '├── module1/',
                    '│   ├── controllers/',
                    '│   │   └── module1-controller.js',
                    '│   ├── module2/',
                    '│   └── module1-module.js',
                    '└── app.js'].join('\n'),
              value: 'module-type'
            }
          ]
        },
        {
          type: 'list',
          name: 'markup',
          message: 'Which is the preferred markup language?',
          default: 'jade',
          choices: [
            {
              name: 'HAML',
              value: 'haml'
            },
            {
              name: 'HTML',
              value: 'html'
            },
            {
              name: 'Jade',
              value: 'jade'
            }
          ]
        },
        {
          type: 'list',
          name: 'appScript',
          message: 'Which is the preferred application scripting language?',
          default: 'js',
          choices: [
            {
              name: 'CoffeeScript',
              value: 'coffee'
            },
            {
              name: 'EcmaScript2015 (ES6) using Babel',
              value: 'es6'
            },
            {
              name: 'JavaScript (ES5)',
              value: 'js'
            },
            {
              name: 'TypeScript',
              value: 'ts'
            }
          ]
        },
        {
          type: 'confirm',
          name: 'controllerAs',
          message: 'Want to use Controller As syntax?',
          default: true
        },
        {
          type: 'list',
          name: 'testScript',
          message: 'Which is the preferred test scripting language?',
          default: answers => answers.appScript,
          choices: [
            {
              name: 'CoffeeScript',
              value: 'coffee'
            },
            {
              name: 'EcmaScript2015 (ES6) using Babel',
              value: 'es6'
            },
            {
              name: 'JavaScript (ES5)',
              value: 'js'
            },
            {
              name: 'TypeScript',
              value: 'ts'
            }
          ]
        },
        {
          type: 'list',
          name: 'testFramework',
          message: 'Which is the preferred unit testing framework?',
          default: 'jasmine',
          choices: [
            {
              name: 'Jasmine',
              value: 'jasmine'
            },
            {
              name: 'Mocha with Chai',
              value: 'mocha'
            }
          ]
        },
        {
          type: 'list',
          name: 'e2eTestFramework',
          message: 'Which is the preferred e2e testing framework?',
          default: answers => answers.testFramework,
          choices: [
            {
              name: 'Jasmine',
              value: 'jasmine'
            },
            {
              name: 'Mocha with Chai',
              value: 'mocha'
            }
          ]
        },
        {
          type: 'list',
          name: 'style',
          message: 'Which is the preferred style language?',
          default: 'less',
          choices: [
            {
              name: 'CSS',
              value: 'css'
            },
            {
              name: 'LESS',
              value: 'less'
            },
            {
              name: 'SCSS',
              value: 'scss'
            },
            {
              name: 'Stylus',
              value: 'styl'
            }
          ]
        },
        {
          type: 'confirm',
          name: 'polymer',
          message: 'Should Polymer support be enabled?',
          default: false
        },
        {
          type: 'list',
          name: 'framework',
          message: 'Should a framework be setup?',
          choices: answers => utils.getUIFrameworks(answers.ngVersion)
        },
        {
          type: 'confirm',
          name: 'ngRoute',
          message: 'Should ngRoute be used instead of UI Router?',
          default: false
        },
        {
          type: 'checkbox',
          name: 'bower',
          message: 'Which additional Bower components should be installed?',
          choices: answers => {
            let choices;

            choices = [
              {
                name: 'Angular Animate',
                value: 'animate'
              },
              {
                name: 'Angular Cookies',
                value: 'cookies'
              },
              {
                name: 'Angular Resource',
                value: 'resource'
              },
              {
                name: 'Angular Sanitize',
                value: 'sanitize'
              },
              {
                name: 'Angular Touch',
                value: 'touch'
              },
              {
                name: 'Font Awesome',
                value: 'fontawesome'
              },
              {
                name: 'Lo-Dash',
                value: 'lodash'
              },
              {
                name: 'Restangular (installs Lo-Dash)',
                value: 'restangular'
              }
            ];

            if (answers.ngversion !== '1.2.*') {
              choices.splice(1, 0, {
                name: 'Angular Aria',
                value: 'aria'
              });
              choices.splice(3, 0, {
                name: 'Angular Messages',
                value: 'messages'
              });
            }

            return choices;
          }
        }
      ], props => {
        // needs to be a string
        props.bower = props.bower.join(',');

        // attach answers to `this`
        _.merge(this, props);

        done();
      });
    };
  }

  get configuring() {
    return function () {
      // create a directory named `appName`
      this.destinationRoot(this.appName);

      // save config
      ['appScript',
        'controllerAs',
        'e2eTestFramework',
        'markup',
        'ngRoute',
        'structure',
        'style',
        'testFramework',
        'testScript'
      ].forEach(option => this.config.set(option, this[option]));

      this.context = {
        pkg,
        appName: this.appName,
        structure: this.structure,
        ngversion: this.ngversion,
        appDir: this.appDir,
        appScript: this.appScript,
        testScript: this.testScript,
        markup: this.markup,
        style: this.style,
        unitTestDir: this.unitTestDir,
        host: this.host,
        port: this.port,
        moduleName: utils.lowerCamel(this.appName),
        polymer: this.polymer,
        framework: this.framework,
        testFramework: this.testFramework,
        e2eTestFramework: this.e2eTestFramework,
        ngRoute: this.ngRoute,
        bower: this.bower
      };

      // copy over common project files
      ['.bowerrc',
        '.editorconfig',
        '.eslintrc',
        '.jscsrc',
        '.jshintrc',
        '_bower.json',
        '_build.config.js',
        '_karma.config.js',
        '_package.json',
        '_protractor.config.js',
        'gulp/analyze.js',
        'gulp/_build.js',
        'gulp/_test.js',
        'gulp/watch.js'
      ].forEach(file => this.copySimpleFile(file));

      // files that need to be renamed when copied
      this.copySimpleFile('_gulpfile.js', 'Gulpfile.js');
      this.copySimpleFile('gitignore', '.gitignore');
      this.copySimpleFile('_readme.md', 'README.md');

      if (this.appScript === 'ts') {
        this.copySimpleFile('_tsd.json');
      }
    };
  }

  get writing() {
    return function () {
      // create main module and index.html
      this.copySimpleFile(`_app.${this.appScript}`, path.join(this.appDir, `app-module.${this.appScript}`));
      this.copySimpleFile(`_app-routes.${this.appScript}`, path.join(this.appDir, `app-routes.${this.appScript}`));
      this.copySimpleFile(`_index.${this.markup}`, path.join(this.appDir, `index.${this.markup}`));

      mkdirp.sync(path.join(this.appDir, 'fonts'));
      mkdirp.sync(path.join(this.appDir, 'images'));
    };
  }

  get install() {
    return function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
        if (this.appScript === 'ts') {
          this.log(`Running ${chalk.yellow.bold('tsd reinstall --save')}. If this fails run the commands ` +
            'yourself. TSD must be installed via `npm install -g tsd`.');
          this.spawnCommand('tsd', ['reinstall', '--save']);
        }
      }
    };
  }

  get end() {
    return function () {
      this.composeWith('ng-poly:module', {
        args: ['home'],
        options: {
          module: 'home',
          markup: this.markup,
          style: this.style,
          'test-dir': this.testDir,
          'test-script': this.testScript,
          'controller-as': this.controllerAs,
          'skip-controller': this.skipController,
          'ng-route': this.ngRoute
        }
      }, {
        local: require.resolve('../module'),
        link: 'strong'
      });
    };
  }
}
<commit_msg>style(app): report route generating creating controller on single line<commit_after>'use strict';
import _ from 'lodash';
import chalk from 'chalk';
import GenBase from '../genBase';
import mkdirp from 'mkdirp';
import path from 'path';
import pkg from '../../package.json';
import utils from '../utils';
import yosay from 'yosay';

export default class Generator extends GenBase {
  constructor(...args) {
    super(...args);
  }

  get initializing() {
    return function () {
      this.host = this.options.host || 'localhost';
      this.port = this.options.port || 3000;
      this.appDir = this.options['app-dir'] || 'app';
      this.unitTestDir = this.options['unit-test-dir'] || 'app';
      this.skipController = this.options['skip-controller'] || false;

      console.log(chalk.yellow(`Using host: ${this.host}`));
      console.log(chalk.yellow(`Using port: ${this.port}`));
      console.log(chalk.yellow(`Using app directory: ${this.appDir}`));
      console.log(chalk.yellow(`Using unit test directory: ${this.unitTestDir}`));
      console.log(chalk.yellow(
        `Route generator will ${(this.skipController ? chalk.red('NOT ') : '')}create controllers`));
    };
  }

  get prompting() {
    return function () {
      const done = this.async();

      this.log(yosay('Welcome to ngPoly!'));

      // ask for app name
      // get preferred langugaes
      this.prompt([
        {
          name: 'appName',
          message: 'What is the app\'s name?',
          validate: input => !!input
        },
        {
          type: 'list',
          name: 'ngversion',
          message: 'Which version of Angular should be used?',
          default: '1.4.*',
          choices: [
            {
              name: '1.4.*',
              value: '1.4.*'
            },
            {
              name: '1.3.*',
              value: '1.3.*'
            },
            {
              name: '1.2.*',
              value: '1.2.*'
            }
          ]
        },
        {
          type: 'list',
          name: 'structure',
          message: 'Which structure should be used?',
          default: 'module-only',
          choices: [
            {
              name: ['app/',
                    '├── module1/',
                    '│   ├── module2/',
                    '│   ├── module1-module.js',
                    '│   └── module1-controller.js',
                    '└── app.js'].join('\n'),
              value: 'module-only'
            },
            {
              name: ['app/',
                    '├── module1/',
                    '│   ├── controllers/',
                    '│   │   └── module1-controller.js',
                    '│   ├── module2/',
                    '│   └── module1-module.js',
                    '└── app.js'].join('\n'),
              value: 'module-type'
            }
          ]
        },
        {
          type: 'list',
          name: 'markup',
          message: 'Which is the preferred markup language?',
          default: 'jade',
          choices: [
            {
              name: 'HAML',
              value: 'haml'
            },
            {
              name: 'HTML',
              value: 'html'
            },
            {
              name: 'Jade',
              value: 'jade'
            }
          ]
        },
        {
          type: 'list',
          name: 'appScript',
          message: 'Which is the preferred application scripting language?',
          default: 'js',
          choices: [
            {
              name: 'CoffeeScript',
              value: 'coffee'
            },
            {
              name: 'EcmaScript2015 (ES6) using Babel',
              value: 'es6'
            },
            {
              name: 'JavaScript (ES5)',
              value: 'js'
            },
            {
              name: 'TypeScript',
              value: 'ts'
            }
          ]
        },
        {
          type: 'confirm',
          name: 'controllerAs',
          message: 'Want to use Controller As syntax?',
          default: true
        },
        {
          type: 'list',
          name: 'testScript',
          message: 'Which is the preferred test scripting language?',
          default: answers => answers.appScript,
          choices: [
            {
              name: 'CoffeeScript',
              value: 'coffee'
            },
            {
              name: 'EcmaScript2015 (ES6) using Babel',
              value: 'es6'
            },
            {
              name: 'JavaScript (ES5)',
              value: 'js'
            },
            {
              name: 'TypeScript',
              value: 'ts'
            }
          ]
        },
        {
          type: 'list',
          name: 'testFramework',
          message: 'Which is the preferred unit testing framework?',
          default: 'jasmine',
          choices: [
            {
              name: 'Jasmine',
              value: 'jasmine'
            },
            {
              name: 'Mocha with Chai',
              value: 'mocha'
            }
          ]
        },
        {
          type: 'list',
          name: 'e2eTestFramework',
          message: 'Which is the preferred e2e testing framework?',
          default: answers => answers.testFramework,
          choices: [
            {
              name: 'Jasmine',
              value: 'jasmine'
            },
            {
              name: 'Mocha with Chai',
              value: 'mocha'
            }
          ]
        },
        {
          type: 'list',
          name: 'style',
          message: 'Which is the preferred style language?',
          default: 'less',
          choices: [
            {
              name: 'CSS',
              value: 'css'
            },
            {
              name: 'LESS',
              value: 'less'
            },
            {
              name: 'SCSS',
              value: 'scss'
            },
            {
              name: 'Stylus',
              value: 'styl'
            }
          ]
        },
        {
          type: 'confirm',
          name: 'polymer',
          message: 'Should Polymer support be enabled?',
          default: false
        },
        {
          type: 'list',
          name: 'framework',
          message: 'Should a framework be setup?',
          choices: answers => utils.getUIFrameworks(answers.ngVersion)
        },
        {
          type: 'confirm',
          name: 'ngRoute',
          message: 'Should ngRoute be used instead of UI Router?',
          default: false
        },
        {
          type: 'checkbox',
          name: 'bower',
          message: 'Which additional Bower components should be installed?',
          choices: answers => {
            let choices;

            choices = [
              {
                name: 'Angular Animate',
                value: 'animate'
              },
              {
                name: 'Angular Cookies',
                value: 'cookies'
              },
              {
                name: 'Angular Resource',
                value: 'resource'
              },
              {
                name: 'Angular Sanitize',
                value: 'sanitize'
              },
              {
                name: 'Angular Touch',
                value: 'touch'
              },
              {
                name: 'Font Awesome',
                value: 'fontawesome'
              },
              {
                name: 'Lo-Dash',
                value: 'lodash'
              },
              {
                name: 'Restangular (installs Lo-Dash)',
                value: 'restangular'
              }
            ];

            if (answers.ngversion !== '1.2.*') {
              choices.splice(1, 0, {
                name: 'Angular Aria',
                value: 'aria'
              });
              choices.splice(3, 0, {
                name: 'Angular Messages',
                value: 'messages'
              });
            }

            return choices;
          }
        }
      ], props => {
        // needs to be a string
        props.bower = props.bower.join(',');

        // attach answers to `this`
        _.merge(this, props);

        done();
      });
    };
  }

  get configuring() {
    return function () {
      // create a directory named `appName`
      this.destinationRoot(this.appName);

      // save config
      ['appScript',
        'controllerAs',
        'e2eTestFramework',
        'markup',
        'ngRoute',
        'structure',
        'style',
        'testFramework',
        'testScript'
      ].forEach(option => this.config.set(option, this[option]));

      this.context = {
        pkg,
        appName: this.appName,
        structure: this.structure,
        ngversion: this.ngversion,
        appDir: this.appDir,
        appScript: this.appScript,
        testScript: this.testScript,
        markup: this.markup,
        style: this.style,
        unitTestDir: this.unitTestDir,
        host: this.host,
        port: this.port,
        moduleName: utils.lowerCamel(this.appName),
        polymer: this.polymer,
        framework: this.framework,
        testFramework: this.testFramework,
        e2eTestFramework: this.e2eTestFramework,
        ngRoute: this.ngRoute,
        bower: this.bower
      };

      // copy over common project files
      ['.bowerrc',
        '.editorconfig',
        '.eslintrc',
        '.jscsrc',
        '.jshintrc',
        '_bower.json',
        '_build.config.js',
        '_karma.config.js',
        '_package.json',
        '_protractor.config.js',
        'gulp/analyze.js',
        'gulp/_build.js',
        'gulp/_test.js',
        'gulp/watch.js'
      ].forEach(file => this.copySimpleFile(file));

      // files that need to be renamed when copied
      this.copySimpleFile('_gulpfile.js', 'Gulpfile.js');
      this.copySimpleFile('gitignore', '.gitignore');
      this.copySimpleFile('_readme.md', 'README.md');

      if (this.appScript === 'ts') {
        this.copySimpleFile('_tsd.json');
      }
    };
  }

  get writing() {
    return function () {
      // create main module and index.html
      this.copySimpleFile(`_app.${this.appScript}`, path.join(this.appDir, `app-module.${this.appScript}`));
      this.copySimpleFile(`_app-routes.${this.appScript}`, path.join(this.appDir, `app-routes.${this.appScript}`));
      this.copySimpleFile(`_index.${this.markup}`, path.join(this.appDir, `index.${this.markup}`));

      mkdirp.sync(path.join(this.appDir, 'fonts'));
      mkdirp.sync(path.join(this.appDir, 'images'));
    };
  }

  get install() {
    return function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
        if (this.appScript === 'ts') {
          this.log(`Running ${chalk.yellow.bold('tsd reinstall --save')}. If this fails run the commands ` +
            'yourself. TSD must be installed via `npm install -g tsd`.');
          this.spawnCommand('tsd', ['reinstall', '--save']);
        }
      }
    };
  }

  get end() {
    return function () {
      this.composeWith('ng-poly:module', {
        args: ['home'],
        options: {
          module: 'home',
          markup: this.markup,
          style: this.style,
          'test-dir': this.testDir,
          'test-script': this.testScript,
          'controller-as': this.controllerAs,
          'skip-controller': this.skipController,
          'ng-route': this.ngRoute
        }
      }, {
        local: require.resolve('../module'),
        link: 'strong'
      });
    };
  }
}
<|endoftext|>


<commit_before>import classnames from 'classnames'
import React, { PropTypes } from 'react'

import { states } from '../misc/constants'

const Paragraph = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-paragraph'
  )

  return (

      {children}

  )
}

Paragraph.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Link = ({ children, className, state, ...rest }) => {
  className = classnames(
    className,
    'c-link', {
      [`c-link--${state}`]: state
    }
  )

  return (

      {children}

  )
}

Link.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  state: PropTypes.oneOf(states)
}

const Highlight = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--highlight'
  )

  return (

      {children}

  )
}

Highlight.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Loud = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--loud'
  )

  return (

      {children}

  )
}

Loud.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Quiet = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--quiet'
  )

  return (

      {children}

  )
}

Quiet.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Abbr = ({ children, className, title, ...rest }) => {
  className = classnames(
    className,
    'c-text--help'
  )

  return (

      {children}

  )
}

Abbr.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  title: PropTypes.string.isRequired
}

const Mono = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--mono'
  )

  return (

      {children}

  )
}

Mono.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Kbd = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-kbd'
  )

  return (

      {children}

  )
}

Kbd.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Code = ({ children, className, multiline, ...rest }) => {
  className = classnames(
    className,
    'c-code', {
      'c-code--multiline': multiline
    }
  )

  return (

      {children}

  )
}

Code.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  multiline: PropTypes.bool
}

const Blockquote = ({ children, className, from, state, ...rest }) => {
  className = classnames(
    className,
    'c-blockquote', {
      [`c-blockquote--${state}`]: state
    }
  )

  return (

        {children}

        — {from}

  )
}

Blockquote.propTypes = {
  children: PropTypes.any.isRequired,
  className: PropTypes.string,
  from: PropTypes.string.isRequired,
  state: PropTypes.oneOf(states)
}

export {
  Abbr,
  Paragraph,
  Blockquote,
  Code,
  Highlight,
  Kbd,
  Link,
  Loud,
  Mono,
  Quiet
}
<commit_msg>Add customLink and plain link support to Link component<commit_after>import classnames from 'classnames'
import React, { PropTypes } from 'react'

import { states } from '../misc/constants'

const Paragraph = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-paragraph'
  )

  return (

      {children}

  )
}

Paragraph.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Link = ({ children, className, customLink, plain, state, ...rest }) => {
  className = classnames(
    className, {
      'c-link': !plain,
      [`c-link--${state}`]: state && !plain
    }
  )

  if (customLink) {
    const CustomLink = customLink

    return (
      <CustomLink className={className} {...rest}>
        {children}
      </CustomLink>
    )
  }

  return (

      {children}

  )
}

Link.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  customLink: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.string
  ]),
  plain: PropTypes.bool,
  state: PropTypes.oneOf(states)
}

Link.defaultProps = {
  plain: false
}

const Highlight = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--highlight'
  )

  return (

      {children}

  )
}

Highlight.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Loud = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--loud'
  )

  return (

      {children}

  )
}

Loud.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Quiet = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--quiet'
  )

  return (

      {children}

  )
}

Quiet.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Abbr = ({ children, className, title, ...rest }) => {
  className = classnames(
    className,
    'c-text--help'
  )

  return (

      {children}

  )
}

Abbr.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  title: PropTypes.string.isRequired
}

const Mono = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-text--mono'
  )

  return (

      {children}

  )
}

Mono.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Kbd = ({ children, className, ...rest }) => {
  className = classnames(
    className,
    'c-kbd'
  )

  return (

      {children}

  )
}

Kbd.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string
}

const Code = ({ children, className, multiline, ...rest }) => {
  className = classnames(
    className,
    'c-code', {
      'c-code--multiline': multiline
    }
  )

  return (

      {children}

  )
}

Code.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  multiline: PropTypes.bool
}

const Blockquote = ({ children, className, from, state, ...rest }) => {
  className = classnames(
    className,
    'c-blockquote', {
      [`c-blockquote--${state}`]: state
    }
  )

  return (

        {children}

        — {from}

  )
}

Blockquote.propTypes = {
  children: PropTypes.any.isRequired,
  className: PropTypes.string,
  from: PropTypes.string.isRequired,
  state: PropTypes.oneOf(states)
}

export {
  Abbr,
  Paragraph,
  Blockquote,
  Code,
  Highlight,
  Kbd,
  Link,
  Loud,
  Mono,
  Quiet
}
<|endoftext|>


<commit_before>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { Component, PropTypes } from 'react'
import Immutable, { List, Map } from 'immutable'

import provide from 'react-redux-provide'
import selectn from 'selectn'
//import QueryString from 'query-string';

import PromiseWrapper from 'views/components/Document/PromiseWrapper'

// Operations
import DirectoryOperations from 'operations/DirectoryOperations'
import DocumentOperations from 'operations/DocumentOperations'

import GridList from 'material-ui/lib/grid-list/grid-list'
import GridTile from 'material-ui/lib/grid-list/grid-tile'
import CircularProgress from 'material-ui/lib/circular-progress'

import ProviderHelpers from 'common/ProviderHelpers'

import { RaisedButton } from 'material-ui'

import MediaList from 'views/components/Browsing/media-list'
import withPagination from 'views/hoc/grid-list/with-pagination'
import withFilter from 'views/hoc/grid-list/with-filter'

import providers from '../../providers/index.js'

//import elasticsearch from 'elasticsearch';

const DefaultFetcherParams = { filters: { 'properties.dc:title': '', dialect: '78086057-9c34-48f7-995f-9dc3b313231b' } }

const FilteredPaginatedMediaList = withFilter(withPagination(MediaList, 10), 'SharedPictures', DefaultFetcherParams)

const argsFunction = function argumentNames(fun) {
  var names = fun
    .toString()
    .match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
    .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
    .replace(/\s+/g, '')
    .split(',')
  return names.length == 1 && !names[0] ? [] : names
}

/**
 * Explore Archive page shows all the families in the archive
 */
@provide
export default class PageDebugAPI extends Component {
  static propTypes = {
    properties: PropTypes.object.isRequired,
    fetchPortal: PropTypes.func.isRequired,
    computePortal: PropTypes.object.isRequired,
    pushWindowPath: PropTypes.func.isRequired,
    routeParams: PropTypes.object.isRequired,
    fetchSharedPictures: PropTypes.func.isRequired,
    computeSharedPictures: PropTypes.object.isRequired,
    fetchWord: PropTypes.func.isRequired,
    computeWord: PropTypes.object.isRequired,
  }

  /*static contextTypes = {
      muiTheme: React.PropTypes.object.isRequired
  };*/

  constructor(props, context) {
    super(props, context)
    /*let computeEntities = new List();

    let computePortal = new Map([['id', '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect'], ['entity', this.props.computePortal]]);
*/

    this.state = {
      filteredList: null,
      fetcherParams: Object.assign(
        {
          currentPageIndex: 0,
          pageSize: 10,
        },
        DefaultFetcherParams
      ),
      pathOrId: '/FV/Workspaces/Data/Athabascan/Beaver/Tsaaʔ%20Dane%20-%20Beaver%20People/Dictionary/119430',
    }

    this.fetchData = this.fetchData.bind(this)
    this.fixedListFetcher = this.fixedListFetcher.bind(this)

    /*var client = new elasticsearch.Client({
      host: 'https://preprod.firstvoices.com/nuxeo/site/es',
      httpAuth: 'null:null',
      log: 'trace'
    });

    var test123 = client.search({
      index: 'nuxeo',
      'enrichers.document': 'breadcrumb', // enrichers -- not working here
      'enrichers.document': 'breadcrumb', // enrichers -- not working here
      'fetch.document' : 'dc:creator', // marshallers - not working here
      headers: {
        'enrichers.document': 'breadcrumb', // enrichers -- not working here
        'enrichers.document': 'breadcrumb', // enrichers -- not working here
        'fetch.document' : 'dc:creator' // marshallers - not working here
      },
      body: {
          "from" : 0,
          "size" : 100,
          //"_source": ["dc:title"],
          "query": {
            "filtered": {
              "filter": {
                  "bool": {
                      "must":
                          [
                              {
                                "term": {
                                  "ecm:primaryType": "FVPortal"
                                }
                              },
                              {
                                "term": {
                                  "ecm:isVersion": 0
                                }
                              },
                              {
                                "prefix": {
                                  "ecm:path": "/FV/Workspaces/"
                                }
                              }
                          ]
                      ,
                      "must_not": [
                        {"term": {
                          "ecm:isTrashed": "0"
                        }}
                      ]
                    }
              }
            }
          }
      }
    }).then(function (resp) {
        var hits = resp.hits.hits;
    }, function (err) {
        console.trace(err.message);
    });*/
  }

  fixedListFetcher(list) {
    this.setState({
      filteredList: list,
    })
  }

  fetchData() {
    // this.props.fetchWord(this.state.pathOrId);
  }

  // Fetch data on initial render
  componentDidMount() {
    // this.fetchData();
  }

  // Refetch data on URL change
  componentWillReceiveProps(nextProps) {
    //if (nextProps.windowPath !== this.props.windowPath || nextProps.routeParams.area != this.props.routeParams.area) {
    //  this.fetchData(nextProps);
    //}
  }

  shouldComponentUpdate(nextProps, nextState) {
    return false
  }

  _onNavigateRequest() {}

  render() {
    //let computeEntities = new List();
    //let computePortal = new Map([['id', '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect'], ['entity', this.props.computePortal]]);

    /*let portalOperation = ProviderHelpers.getEntry(computePortal, '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect');
    console.log(portalOperation);

    if (!portalOperation || portalOperation.isFetching) {
      return
<CircularProgress mode="indeterminate" size={5} /> {selectn('message', portalOperation)}
;
    }

    if (portalOperation.isError) {
      return
{portalOperation.message}

    }

    let portalResponse = selectn('response', portalOperation);*/

    const dialectPath = '/FV/sections/Data/MyTestLanguage/MyTestLanguage/Test444'
    const languagePath = '/FV/sections/Data/MyTestLanguage/MyTestLanguage'
    const languageFamilyPath = '/FV/sections/Data/MyTestLanguage'

    const dialectPathWP = '/FV/Workspaces/Data/MyTestLanguage/MyTestLanguage/Test444'
    const languagePathWP = '/FV/Workspaces/Data/MyTestLanguage/MyTestLanguage'
    const languageFamilyPathWP = '/FV/Workspaces/Data/MyTestLanguage'

    let providersElements = []

    for (var providerKey in providers) {
      let provider = providers[providerKey]

      if (
        provider.hasOwnProperty('actions') &&
        provider.hasOwnProperty('reducers') &&
        provider.hasOwnProperty('mockRequest')
      ) {
        let providerActions = []
        let providerReducers = []

        for (let actionKey in provider['actions']) {
          if (provider['mockRequest'].hasOwnProperty(actionKey)) {
            let method = provider['actions'][actionKey]
            let mockRequestArgs = provider['mockRequest'][actionKey]['args']
            let mockRequestEvaluateResults = provider['mockRequest'][actionKey]['evaluateResults']
            let name = method.name
            let args = argsFunction(method)

            //let test = method.call(this, "/FV/Workspaces/", "");
            //let output = "test";

            if (name == 'query') {
              DirectoryOperations.getDocuments(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocuments(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
            } else if (name == 'create') {
              DocumentOperations.createDocument(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocument(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
            } else if (name == 'fetch') {
              DocumentOperations.getDocument(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocument(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
            }

            // console.log(args);
            // console.log(test);

            providerActions.push(

                {actionKey} - {name}

            )
          } else {
            console.warn('Missing tests for ' + actionKey + ' in provider ' + providerKey)
          }
        }

        for (var reducerKey in provider['reducers']) {
          providerReducers.push(
{reducerKey}
)
        }

        providersElements.push(

Provider {providerKey}

Actions

            {providerActions}

Reducers

            {providerReducers}

        )
      } else {
        console.warn('Missing tests for provider ' + providerKey)
      }
    }

    return (

{providersElements}

    )
  }
}
<commit_msg>Reduxed: `<PageDebugAPI />`<commit_after>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { Component, PropTypes } from 'react'

// REDUX
import { connect } from 'react-redux'
// REDUX: actions/dispatch/func
import { fetchPortal } from 'providers/redux/reducers/fvPortal'
import { fetchSharedPictures } from 'providers/redux/reducers/fvPicture'
import { fetchWord } from 'providers/redux/reducers/fvWord'
import { pushWindowPath } from 'providers/redux/reducers/windowPath'

// Operations
import DirectoryOperations from 'operations/DirectoryOperations'
import DocumentOperations from 'operations/DocumentOperations'
import providers from '../../providers/index.js'

const DefaultFetcherParams = { filters: { 'properties.dc:title': '', dialect: '78086057-9c34-48f7-995f-9dc3b313231b' } }

// const argsFunction = function argumentNames(fun) {
//   const names = fun
//     .toString()
//     .match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] // eslint-disable-line
//     .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
//     .replace(/\s+/g, '')
//     .split(',')
//   return names.length == 1 && !names[0] ? [] : names
// }
const { func, object } = PropTypes
/**
 * Explore Archive page shows all the families in the archive
 */
export class PageDebugAPI extends Component {
  static propTypes = {
    routeParams: object.isRequired,
    // REDUX: reducers/state
    computePortal: object.isRequired,
    computeSharedPictures: object.isRequired,
    computeWord: object.isRequired,
    properties: object.isRequired,
    // REDUX: actions/dispatch/func
    fetchPortal: func.isRequired,
    fetchSharedPictures: func.isRequired,
    fetchWord: func.isRequired,
    pushWindowPath: func.isRequired,
  }

  /*static contextTypes = {
      muiTheme: React.object.isRequired
  };*/

  constructor(props, context) {
    super(props, context)
    /*let computeEntities = new List();

    let computePortal = new Map([['id', '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect'], ['entity', this.props.computePortal]]);
*/

    this.state = {
      filteredList: null,
      fetcherParams: Object.assign(
        {
          currentPageIndex: 0,
          pageSize: 10,
        },
        DefaultFetcherParams
      ),
      pathOrId: '/FV/Workspaces/Data/Athabascan/Beaver/Tsaaʔ%20Dane%20-%20Beaver%20People/Dictionary/119430',
    }

    this.fetchData = this.fetchData.bind(this)
    this.fixedListFetcher = this.fixedListFetcher.bind(this)

    /*var client = new elasticsearch.Client({
      host: 'https://preprod.firstvoices.com/nuxeo/site/es',
      httpAuth: 'null:null',
      log: 'trace'
    });

    var test123 = client.search({
      index: 'nuxeo',
      'enrichers.document': 'breadcrumb', // enrichers -- not working here
      'enrichers.document': 'breadcrumb', // enrichers -- not working here
      'fetch.document' : 'dc:creator', // marshallers - not working here
      headers: {
        'enrichers.document': 'breadcrumb', // enrichers -- not working here
        'enrichers.document': 'breadcrumb', // enrichers -- not working here
        'fetch.document' : 'dc:creator' // marshallers - not working here
      },
      body: {
          "from" : 0,
          "size" : 100,
          //"_source": ["dc:title"],
          "query": {
            "filtered": {
              "filter": {
                  "bool": {
                      "must":
                          [
                              {
                                "term": {
                                  "ecm:primaryType": "FVPortal"
                                }
                              },
                              {
                                "term": {
                                  "ecm:isVersion": 0
                                }
                              },
                              {
                                "prefix": {
                                  "ecm:path": "/FV/Workspaces/"
                                }
                              }
                          ]
                      ,
                      "must_not": [
                        {"term": {
                          "ecm:isTrashed": "0"
                        }}
                      ]
                    }
              }
            }
          }
      }
    }).then(function (resp) {
        var hits = resp.hits.hits;
    }, function (err) {
        console.trace(err.message);
    });*/
  }

  fixedListFetcher(list) {
    this.setState({
      filteredList: list,
    })
  }

  fetchData() {
    // this.props.fetchWord(this.state.pathOrId);
  }

  // Fetch data on initial render
  componentDidMount() {
    // this.fetchData();
  }

  // Refetch data on URL change
  componentWillReceiveProps(/*nextProps*/) {
    //if (nextProps.windowPath !== this.props.windowPath || nextProps.routeParams.area != this.props.routeParams.area) {
    //  this.fetchData(nextProps);
    //}
  }

  shouldComponentUpdate(/*nextProps, nextState*/) {
    return false
  }

  _onNavigateRequest() {}

  render() {
    //let computeEntities = new List();
    //let computePortal = new Map([['id', '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect'], ['entity', this.props.computePortal]]);

    /*let portalOperation = ProviderHelpers.getEntry(computePortal, '/FV/sections/Data/TestFamily/TestLanguage/PopoDialect');
    console.log(portalOperation);

    if (!portalOperation || portalOperation.isFetching) {
      return
<CircularProgress mode="indeterminate" size={5} /> {selectn('message', portalOperation)}
;
    }

    if (portalOperation.isError) {
      return
{portalOperation.message}

    }

    let portalResponse = selectn('response', portalOperation);*/

    // const dialectPath = '/FV/sections/Data/MyTestLanguage/MyTestLanguage/Test444'
    // const languagePath = '/FV/sections/Data/MyTestLanguage/MyTestLanguage'
    // const languageFamilyPath = '/FV/sections/Data/MyTestLanguage'

    // const dialectPathWP = '/FV/Workspaces/Data/MyTestLanguage/MyTestLanguage/Test444'
    // const languagePathWP = '/FV/Workspaces/Data/MyTestLanguage/MyTestLanguage'
    // const languageFamilyPathWP = '/FV/Workspaces/Data/MyTestLanguage'

    const providersElements = []

    for (const providerKey in providers) {
      const provider = providers[providerKey]

      if (
        provider.hasOwnProperty('actions') &&
        provider.hasOwnProperty('reducers') &&
        provider.hasOwnProperty('mockRequest')
      ) {
        const providerActions = []
        const providerReducers = []

        for (const actionKey in provider.actions) {
          if (provider.mockRequest.hasOwnProperty(actionKey)) {
            const method = provider.actions[actionKey]
            const mockRequestArgs = provider.mockRequest[actionKey].args
            const mockRequestEvaluateResults = provider.mockRequest[actionKey].evaluateResults
            const name = method.name
            // const args = argsFunction(method)

            //let test = method.call(this, "/FV/Workspaces/", "");
            //let output = "test";

            if (name == 'query') {
              /* eslint-disable */
              DirectoryOperations.getDocuments(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocuments(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
              /* eslint-enable */
            } else if (name == 'create') {
              /* eslint-disable */
              DocumentOperations.createDocument(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocument(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
              /* eslint-enable */
            } else if (name == 'fetch') {
              /* eslint-disable */
              DocumentOperations.getDocument(...mockRequestArgs)
                .then((response) => {
                  console.log(actionKey + '-' + name)
                  console.log('CALLED: DocumentOperations.getDocument(' + mockRequestArgs.toString() + ')')
                  console.log('RESPONSE: ')
                  console.log(response)
                  console.log('RESPONSE EVALUATION: ' + mockRequestEvaluateResults(response))
                  console.log('*******************')
                })
                .catch((error) => {
                  console.log(error)
                })
              /* eslint-enable */
            }

            // console.log(args);
            // console.log(test);

            providerActions.push(

                {actionKey} - {name}

            )
          } else {
            // eslint-disable-next-line
            console.warn('Missing tests for ' + actionKey + ' in provider ' + providerKey)
          }
        }

        for (const reducerKey in provider.reducers) {
          providerReducers.push(
{reducerKey}
)
        }

        providersElements.push(

Provider {providerKey}

Actions

            {providerActions}

Reducers

            {providerReducers}

        )
      } else {
        // eslint-disable-next-line
        console.warn('Missing tests for provider ' + providerKey)
      }
    }

    return (

{providersElements}

    )
  }
}

// REDUX: reducers/state
const mapStateToProps = (state /*, ownProps*/) => {
  const { fvPortal, navigation, fvPicture, fvWord } = state

  const { properties } = navigation
  const { computePortal } = fvPortal
  const { computeSharedPictures } = fvPicture
  const { computeWord } = fvWord

  return {
    computePortal,
    computeSharedPictures,
    computeWord,
    properties,
  }
}

// REDUX: actions/dispatch/func
const mapDispatchToProps = {
  fetchPortal,
  fetchSharedPictures,
  fetchWord,
  pushWindowPath,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageDebugAPI)
<|endoftext|>


<commit_before>/**
 * Noire server manager
 * @module
 */
const Fs = require('fs');
const Glue = require('@hapi/glue');
const Hoek = require('@hapi/hoek');
const Exiting = require('exiting');
const Config = require('config');
const ConfigValidation = require('utils/config-validation');

const internals = {
    pluginsPath: 'plugins'
};

internals.relativizePluginPath = plugins =>
    plugins.map(plugin =>
        typeof plugin === 'string'
            ? `./${plugin}`
            : plugin.plugin
            ? { ...plugin, plugin: `./${plugin.plugin}` }
            : plugin
    );

internals.readCertificates = () => ({
    key: Fs.readFileSync(Config.tls.key),
    cert: Fs.readFileSync(Config.tls.cert)
});

// check https://github.com/hapijs/glue/blob/master/API.md for manifest syntax
internals.buildManifest = plugins => ({
    server: {
        app: { name: 'api' },
        host: Config.api.host,
        port: Config.api.port,
        tls: Config.api.tls ? internals.readCertificates() : undefined,
        routes: {
            cors: Config.api.cors ? { origin: Config.api.cors } : undefined
        },
        router: {
            isCaseSensitive: false,
            stripTrailingSlash: true
        }
    },
    register: { plugins: plugins ? internals.relativizePluginPath(plugins) : [] }
});

/**
 * Starts the noire server
 * @async
 * @param {Array.<(Object|string)>} plugins plugins to register
 * @returns {Object.<Hapi.Server>} the hapi server
 */
exports.start = async function(plugins) {
    ConfigValidation.validate(Config);

    // create a new hapi server
    const server = await Glue.compose(
        internals.buildManifest(plugins),
        {
            relativeTo: internals.pluginsPath
        }
    );

    Hoek.assert(server.settings.app, 'server settings should not be empty');

    // get the server name
    const connection = server.settings.app.name;
    Hoek.assert(connection, 'server requires a name setting');

    // create a new exiting manager for all the hapi servers
    internals.manager = Exiting.createManager(server);
    await internals.manager.start();

    return server;
};

/**
 * Stops the noire server
 * @async
 */
exports.stop = async function() {
    if (internals.manager) {
        await internals.manager.stop();
    }
};

/**
 * Gets the noire server status
 * ['starting', 'started', 'stopping', 'prestopped', 'stopped', 'startAborted', 'errored', 'timeout']
 * @returns {string} the server process status
 */
exports.getState = function() {
    return internals.manager ? internals.manager.state : 'stopped';
};

/**
 * Resets the noire server, used mainly for testing purposes
 */
exports.reset = async function() {
    if (internals.manager && internals.manager.state === 'started') {
        internals.manager.stop();
    }

    Exiting.reset();

    internals.manager = null;
};
<commit_msg>fixed pagination headers not exposed<commit_after>/**
 * Noire server manager
 * @module
 */
const Fs = require('fs');
const Glue = require('@hapi/glue');
const Hoek = require('@hapi/hoek');
const Exiting = require('exiting');
const Config = require('config');
const ConfigValidation = require('utils/config-validation');

const internals = {
    pluginsPath: 'plugins'
};

internals.relativizePluginPath = plugins =>
    plugins.map(plugin =>
        typeof plugin === 'string'
            ? `./${plugin}`
            : plugin.plugin
            ? { ...plugin, plugin: `./${plugin.plugin}` }
            : plugin
    );

internals.readCertificates = () => ({
    key: Fs.readFileSync(Config.tls.key),
    cert: Fs.readFileSync(Config.tls.cert)
});

// check https://github.com/hapijs/glue/blob/master/API.md for manifest syntax
internals.buildManifest = plugins => ({
    server: {
        app: { name: 'api' },
        host: Config.api.host,
        port: Config.api.port,
        tls: Config.api.tls ? internals.readCertificates() : undefined,
        routes: {
            cors: Config.api.cors
                ? {
                      additionalExposedHeaders: ['Content-Range', 'Link'],
                      origin: Config.api.cors
                  }
                : false
        },
        router: {
            isCaseSensitive: false,
            stripTrailingSlash: true
        }
    },
    register: { plugins: plugins ? internals.relativizePluginPath(plugins) : [] }
});

/**
 * Starts the noire server
 * @async
 * @param {Array.<(Object|string)>} plugins plugins to register
 * @returns {Object.<Hapi.Server>} the hapi server
 */
exports.start = async function(plugins) {
    ConfigValidation.validate(Config);

    // create a new hapi server
    const server = await Glue.compose(
        internals.buildManifest(plugins),
        {
            relativeTo: internals.pluginsPath
        }
    );

    Hoek.assert(server.settings.app, 'server settings should not be empty');

    // get the server name
    const connection = server.settings.app.name;
    Hoek.assert(connection, 'server requires a name setting');

    // create a new exiting manager for all the hapi servers
    internals.manager = Exiting.createManager(server);
    await internals.manager.start();

    return server;
};

/**
 * Stops the noire server
 * @async
 */
exports.stop = async function() {
    if (internals.manager) {
        await internals.manager.stop();
    }
};

/**
 * Gets the noire server status
 * ['starting', 'started', 'stopping', 'prestopped', 'stopped', 'startAborted', 'errored', 'timeout']
 * @returns {string} the server process status
 */
exports.getState = function() {
    return internals.manager ? internals.manager.state : 'stopped';
};

/**
 * Resets the noire server, used mainly for testing purposes
 */
exports.reset = async function() {
    if (internals.manager && internals.manager.state === 'started') {
        internals.manager.stop();
    }

    Exiting.reset();

    internals.manager = null;
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    relationship = require('mongoose-relationship'),
    Schema = mongoose.Schema,
    ObjectId = Schema.Objectid;

var StepSchema = new Schema({
    stepCount: {type: Number, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    // each step count has one user
    user: {type: Schema.ObjectId, ref: "User", childPath: "steps"}
});

StepSchema.plugin(relationship, {relationshipPathName: 'users'});

var StepModel = mongoose.model('Steps', StepSchema);

module.exports = StepModel;
<commit_msg>interim changes to steps scheme<commit_after>var mongoose = require('mongoose'),
    relationship = require('mongoose-relationship'),
    Schema = mongoose.Schema,
    ObjectId = Schema.Objectid;

var StepSchema = new Schema({
    stepCount: {type: Number, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    // each step count has one user
    user: {type: String, required: true}
    //user: {type: Schema.ObjectId, ref: "User", childPath: "steps"}
});

//StepSchema.plugin(relationship, {relationshipPathName: 'users'});

var StepModel = mongoose.model('Steps', StepSchema);

module.exports = StepModel;
<|endoftext|>


<commit_before>import { connect } from           'react-redux'
import { browserHistory } from    'react-router'
import Promise from               'promise-polyfill'

import getBusStopsAroundMe from   '../services/busStops.js'
import Home from                  '../components/home/home.jsx'
import store from                 '../stores/store'

const goToResults = ( dispatch ) => {
    let busStopsResults = store.getState().default
    if ( busStopsResults.errors.length > 0 ) {
        dispatch( browserHistory.push( '/errors' ) )
    } else {
        dispatch( browserHistory.push( '/results' ) )
    }
}

const setCoordsInStore = ( dispatch, coords ) => {
    return new Promise ( ( resolve ) => {
        let unsuscribe = store.subscribe( () => {
            resolve( { coords: store.getState().default.coords, meters: store.getState().default.meters } );
            unsuscribe();
        })
        dispatch( { type: 'SET_COORDS_AROUND_ME', coords: coords } )
    });
}

const setCoordsAndGetBusStops = ( coords ) => {
    return dispatch => {
        return setCoordsInStore( dispatch, coords ).then(
            position => {
                dispatch( getBusStopsAroundMe( { coords: position.coords, meters: position.meters } ) )
                let unsuscribe = store.suscribe( () => {
                    goToResults( dispatch );
                    unsuscribe();
                })
            }
        )
    }
}

const mapStateToProps = ( state ) => {
    return {
        meters: state.default.meters,
        coords: state.default.coords
    }
}

const mapDispatchToProps = ( dispatch ) => {
    return {
        setMetersAroundMe: ( meters ) => {
            dispatch( { type: 'SET_METERS_AROUND_ME', meters: meters } );
        },
        getBusStopsAroundMeAndGoToResults: ( coords ) => {
            dispatch( setCoordsAndGetBusStops( coords ) )
        }
    }
}

const GetBusStopsGeoState = connect(
    mapStateToProps,
    mapDispatchToProps
)( Home )

export default GetBusStopsGeoState
<commit_msg>🚚  apply redux thunk middleware to async actions in home, simplify logic<commit_after>import { connect } from             'react-redux'
import Promise from                 'promise-polyfill'

import fetchBusStopsAroundMe from   '../services/busStops.js'
import goToResults from             '../router/router.js'
import Home from                    '../components/home/home.jsx'
import store from                   '../stores/store'

const getBusStopsAroundMeAndGoToResults = ( dispatch, position ) => {
    return fetchBusStopsAroundMe( position )
        .then( response => {
            return response.json();
        } )
        .then( busStops => {
            dispatch( { type: 'GET_BUS_STOPS_AROUND_ME_SUCCESS', busStopsAroundMe: busStops } )
        } )
        .then ( () => {
            goToResults( dispatch )
            dispatch( { type: 'SET_LOADING', state: false } );
        } )
        .catch( error => {
            //dispatch( { type: 'GET_BUS_STOPS_AROUND_ME_ERROR', error: error } )
            throw error
        } )
}

const setCoordsInStore = ( dispatch, coords ) => {
    return new Promise ( ( resolve ) => {
        let unsuscribe = store.subscribe( () => {
            resolve( { coords: store.getState().positionAroundMe.coords, meters: store.getState().positionAroundMe.meters } )
            unsuscribe()
        } )
        dispatch( { type: 'SET_COORDS_AROUND_ME', coords: coords } )
    } )
}

const setCoordsAndGetBusStopsAndGoToResults = ( coords ) => {
    return dispatch => {
        return setCoordsInStore( dispatch, coords )
            .then( position => {
                getBusStopsAroundMeAndGoToResults( dispatch, { coords: position.coords, meters: position.meters } )
            } )
            .catch( error => {
                throw error
            } )
    }
}

const mapStateToProps = ( state ) => {
    return {
        meters: state.positionAroundMe.meters,
        coords: state.positionAroundMe.coords,
        loading: state.loading.state
    }
}

const mapDispatchToProps = ( dispatch ) => {
    return {
        setLoading: (isLoading) => {
            dispatch( { type: 'SET_LOADING', state: isLoading } );
        },
        setMetersAroundMe: ( meters ) => {
            dispatch( { type: 'SET_METERS_AROUND_ME', meters: meters } );
        },
        getBusStopsAroundMe: ( coords ) => {
            dispatch( setCoordsAndGetBusStopsAndGoToResults( coords ) )
        }
    }
}

const GetBusStopsGeoState = connect(
    mapStateToProps,
    mapDispatchToProps
)( Home )

export default GetBusStopsGeoState
<|endoftext|>


<commit_before>var socket = {};

var debug    = require('debug')('socket')
var moment   = require('moment-timezone');
var async    = require('async');
var marked   = require('marked');

var users    = require('../models/users.js');
var messages = require('../models/messages.js');

marked.setOptions({
  tables: false,
  sanitize: true
});

// Ping du client toutes les 50 secondes pour éviter
// un drop de la connexion par Heroku au bout de 55
// secondes ( erreur H15 )
var heartbeatInterval = 50000;

socket.init = function( io ) {

  function sendHeartbeat() {
    setTimeout( sendHeartbeat, heartbeatInterval );
    io.emit('ping', { beat : 1 });
  }

  io.on('connection', function( socket ) {

    var session = socket.handshake.session;
    var dateFormat = 'DD/MM à HH:mm:ss'
    var time = moment().tz('Europe/Paris').format( dateFormat );

    // TODO: Utiliser les promises pour éviter une piramide de doom (callback hell)
    if( session.user ) {
      session.user.socket = socket.id;
      users.exist(session.user.name, function( exist ) {
        if( ! exist ) {
          users.banned(session.user.name, function( isBanned ) {
            if( ! isBanned ) {
              users.add( session.user );
              users.list(function( usersList ) {
                // On previent les autres utilisateurs qu'un membre vient de se connecter
                io.emit('user_new');
                addBotMessage(io, time, session.user.name + " s'est connecté");
                async.eachSeries(usersList, function( user, next ) {
                  io.emit('user_connected', user);
                  next();
                }, function() {
                  // Réception la réponse (pong) du client
                  socket.on('pong', function( data ) {
                    debug('Pong received from client');
                  });
                  // Réception d'un message
                  socket.on('message', function( message ) {
                    time = moment().tz('Europe/Paris').format( dateFormat );
                    if( message && message.length <= 1000 )
                      addMessage(io, time, session.user, marked( message ));
                  });
                  // Déconnexion de l'utilisateur
                  socket.on('disconnect', function() {
                    users.remove( session.user.name );
                    time = moment().tz('Europe/Paris').format( dateFormat );
                    io.emit('user_disconnected', session.user.id);
                    addBotMessage(io, time, session.user.name + " s'est déconnecté");
                  });
                  // Ban d'un utilisateur par un admin
                  socket.on('ban', function( username ) {
                    if( session.user.isAdmin ) {
                      users.getUserSocket( username, function( userSocket ) {
                        if( userSocket ) {
                          users.ban( username );
                          io.to( userSocket ).emit('ban');
                          time = moment().tz('Europe/Paris').format( dateFormat );
                          addBotMessage(io, time, username + " a été kick du chat");
                        } else {
                          io.to( socket.id ).emit('user_notfound');
                        }
                      });
                    }
                  });
                  // Deban d'un utilisateur
                  socket.on('unban', function( username ) {
                    if( session.user.isAdmin )
                      users.unban( username );
                  });
                });
              });
            } else {
              io.to( socket.id ).emit('user_banned');
            }
          });
        } else {
          io.to( socket.id ).emit('already_connected');
        }
      });
    }
  });
  // Envoi du premier Heartbeat
  setTimeout( sendHeartbeat, heartbeatInterval );
};

var addMessage = function( io, time, user, message ) {
  messages.add( time, user.name, message );
  io.emit('message', time, user, message);
};

var addBotMessage = function( io, time, message ) {
  messages.add( time, null, message );
  io.emit('botMessage', time, message);
};

module.exports = socket;<commit_msg>Ajout d'un message en broadcast lors du deban<commit_after>var socket = {};

var debug    = require('debug')('socket')
var moment   = require('moment-timezone');
var async    = require('async');
var marked   = require('marked');

var users    = require('../models/users.js');
var messages = require('../models/messages.js');

marked.setOptions({
  tables: false,
  sanitize: true
});

// Ping du client toutes les 50 secondes pour éviter
// un drop de la connexion par Heroku au bout de 55
// secondes ( erreur H15 )
var heartbeatInterval = 50000;

socket.init = function( io ) {

  function sendHeartbeat() {
    setTimeout( sendHeartbeat, heartbeatInterval );
    io.emit('ping', { beat : 1 });
  }

  io.on('connection', function( socket ) {

    var session = socket.handshake.session;
    var dateFormat = 'DD/MM à HH:mm:ss'
    var time = moment().tz('Europe/Paris').format( dateFormat );

    // TODO: Utiliser les promises pour éviter une piramide de doom (callback hell)
    if( session.user ) {
      session.user.socket = socket.id;
      users.exist(session.user.name, function( exist ) {
        if( ! exist ) {
          users.banned(session.user.name, function( isBanned ) {
            if( ! isBanned ) {
              users.add( session.user );
              users.list(function( usersList ) {
                // On previent les autres utilisateurs qu'un membre vient de se connecter
                io.emit('user_new');
                addBotMessage(io, time, session.user.name + " s'est connecté");
                async.eachSeries(usersList, function( user, next ) {
                  io.emit('user_connected', user);
                  next();
                }, function() {
                  // Réception la réponse (pong) du client
                  socket.on('pong', function( data ) {
                    debug('Pong received from client');
                  });
                  // Réception d'un message
                  socket.on('message', function( message ) {
                    time = moment().tz('Europe/Paris').format( dateFormat );
                    if( message && message.length <= 1000 )
                      addMessage(io, time, session.user, marked( message ));
                  });
                  // Déconnexion de l'utilisateur
                  socket.on('disconnect', function() {
                    users.remove( session.user.name );
                    time = moment().tz('Europe/Paris').format( dateFormat );
                    io.emit('user_disconnected', session.user.id);
                    addBotMessage(io, time, session.user.name + " s'est déconnecté");
                  });
                  // Ban d'un utilisateur par un admin
                  socket.on('ban', function( username ) {
                    if( session.user.isAdmin ) {
                      users.getUserSocket( username, function( userSocket ) {
                        if( userSocket ) {
                          users.ban( username );
                          io.to( userSocket ).emit('ban');
                          time = moment().tz('Europe/Paris').format( dateFormat );
                          addBotMessage(io, time, username + " a été kick du chat");
                        } else {
                          io.to( socket.id ).emit('user_notfound');
                        }
                      });
                    }
                  });
                  // Deban d'un utilisateur
                  socket.on('unban', function( username ) {
                    if( session.user.isAdmin ) {
                      users.unban( username );
                      time = moment().tz('Europe/Paris').format( dateFormat );
                      addBotMessage(io, time, " Une seconde chance a été offerte à " + username);
                    }
                  });
                });
              });
            } else {
              io.to( socket.id ).emit('user_banned');
            }
          });
        } else {
          io.to( socket.id ).emit('already_connected');
        }
      });
    }
  });
  // Envoi du premier Heartbeat
  setTimeout( sendHeartbeat, heartbeatInterval );
};

var addMessage = function( io, time, user, message ) {
  messages.add( time, user.name, message );
  io.emit('message', time, user, message);
};

var addBotMessage = function( io, time, message ) {
  messages.add( time, null, message );
  io.emit('botMessage', time, message);
};

module.exports = socket;<|endoftext|>


<commit_before>/**
 * Server control via TCP socket
 *
 * Listens on localhost:8888 by default
 */

var net                = require('net'),
    kiwiModules        = require('../server/modules'),
    ControlInterface   = require('../server/controlinterface.js'),
    _                  = require('lodash');

var control_module = new kiwiModules.Module('Control');

/**
 * The socket client
 */
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    console.log('Control connection from ' + this.socket.remoteAddress + ' opened');

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        console.log('adding command', command_name);
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}

SocketClient.prototype.bindEvents = function() {
    var that = this;

    this.socket.on('close', function() { that.onClose.apply(that, arguments); });
};

SocketClient.prototype.unbindEvents = function() {
    this.socket.removeAllListeners();
};

SocketClient.prototype.onClose = function() {
    this.control_interface.dispose();
    this.control_interface = null;

    this.unbindEvents();
    this.socket = null;

    console.log('Control connection from ' + this.remoteAddress + ' closed');
};

/**
 * Available commands
 * Each function is run in context of the SocketClient
 */
var socket_commands = {
    quit: function(data) {
        this.socket.destroy();
        this.socket_closing = true;
    },
    exit: function(data) {
        this.socket.destroy();
        this.socket_closing = true;
    }
};

/**
 * Start the control socket server to serve connections
 */
var server = net.createServer(function (socket) {
    new SocketClient(socket);
});
server.listen(8888);

control_module.on('dispose', function() {
    server.close();
});
<commit_msg>Removing console.log()s<commit_after>/**
 * Server control via TCP socket
 *
 * Listens on localhost:8888 by default
 */

var net                = require('net'),
    kiwiModules        = require('../server/modules'),
    ControlInterface   = require('../server/controlinterface.js'),
    _                  = require('lodash');

var control_module = new kiwiModules.Module('Control');

/**
 * The socket client
 */
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    console.log('Control connection from ' + this.socket.remoteAddress + ' opened');

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}

SocketClient.prototype.bindEvents = function() {
    var that = this;

    this.socket.on('close', function() { that.onClose.apply(that, arguments); });
};

SocketClient.prototype.unbindEvents = function() {
    this.socket.removeAllListeners();
};

SocketClient.prototype.onClose = function() {
    this.control_interface.dispose();
    this.control_interface = null;

    this.unbindEvents();
    this.socket = null;

    console.log('Control connection from ' + this.remoteAddress + ' closed');
};

/**
 * Available commands
 * Each function is run in context of the SocketClient
 */
var socket_commands = {
    quit: function(data) {
        this.socket.destroy();
        this.socket_closing = true;
    },
    exit: function(data) {
        this.socket.destroy();
        this.socket_closing = true;
    }
};

/**
 * Start the control socket server to serve connections
 */
var server = net.createServer(function (socket) {
    new SocketClient(socket);
});
server.listen(8888);

control_module.on('dispose', function() {
    server.close();
});
<|endoftext|>