<commit_before>/*global exports, document*/

/*
 * Movico
 * https://github.com/d-plaindoux/movico
 *
 * Copyright (c) 2015 Didier Plaindoux
 * Licensed under the LGPL2 license.
 */

exports.M = (function() {

    function getType(object) {
        if (typeof(object) === 'object') {
            return object.constructor.toString(object).match(/^function\s(.*)\(/)[1];
        } else {
            return typeof(object);
        }
    }

    // ---------------------------------------------------------

    function Lazy(f) {
        this.value = f;
        this.evaluation = undefined;
    }

    function Apply(f,a) {
        this.abstraction = f;
        this.argument = a;
    }

    function Unit() {
        // Nothing
    }

    function Number(a) {
        this.value = a;
    }

    function String(a) {
        this.value = a;
    }

    function Tag(n,a,b) {
        this.name = n;
        this.attributes = a;
        this.body = b;
    }

    function Ident(n) {
        this.value = n;
    }

    function Invoke(o,n) {
        this.instance = o;
        this.name = n;
    }

    function Instance(o) {
        this.instance = o;
    }

    function Controller(c) {
        this.controller = c;
    }

    // ---------------------------------------------------------
    // Dictionnary
    // ---------------------------------------------------------

    function Movico() {
        this.environment = {};
        /**
         * Basic definitions - default but can be overriden
         */
        this.define('Pair', function(left,right) { return { '[id]':'Pair',_1:left, _2:right };});
        this.define('string', function(native) { return { '[id]':'number',_:native };});
        this.define('number', function(native) { return { '[id]':'string',_:native };});
    }

    // ---------------------------------------------------------
    // Dictionnary
    // ---------------------------------------------------------

    Movico.prototype.define = function (name, entity) {
        this.environment[name] = entity;
        return entity;
    };

    // ---------------------------------------------------------
    // Abstract instructions
    // ---------------------------------------------------------

    Movico.prototype.unit = new Unit();

    Movico.prototype.string = function(s) {
        return new String(s);
    };

    Movico.prototype.number = function(n) {
        return new Number(n);
    };

    Movico.prototype.lazy = function(f) {
        return new Lazy(f);
    };

    Movico.prototype.apply = function(f,a) {
        return new Apply(f,a);
    };

    Movico.prototype.tag = function(n,a,f) {
        return new Tag(n,a,f);
    };

    Movico.prototype.ident = function(i) {
        return new Ident(i);
    };

    Movico.prototype.invoke = function(o,n) {
        return new Invoke(o,n);
    };

    Movico.prototype.instance = function(o) {
        return new Instance(o);
    };

    Movico.prototype.instance = function(o) {
        return new Instance(o);
    };

    Movico.prototype.controller = function(o) {
        return new Controller(o);
    };

    // ---------------------------------------------------------
    // Operational interpretation
    // ---------------------------------------------------------

    function getId(o) {
        if (getType(o) === 'Object' && o.hasOwnProperty('[id]')) {
            return o['[id]'];
        }

        return undefined;
    }

    Movico.prototype.fun = function(o) {
        var id = getId(o);
        if (id !== undefined) {
            return this.$$(this.ident(id));
        }

        return o;
    };

    Movico.prototype.lookup = function(o,n) {
        var methodName = n;

        if (getType(o) === 'Object' && o.hasOwnProperty('[this]')) {
            var id = getId(this.$$(o['this']));
            if (o.hasOwnProperty(id + "::" + n)) {
                methodName = id + "::" + n;
            }
        }

        return o[methodName];
    };

    Movico.prototype.$$ = function(code) {
        switch (getType(code)) {
            case 'Number':
                return this.$$(this.apply(this.ident("number"),code.value));
            case 'String':
                return this.$$(this.apply(this.ident("string"),code.value));
            case 'Lazy':
                if (code.evaluation === undefined) {
                    code.evaluation = this.$$(code.value());
                }
                return code.evaluation;
            case 'Apply':
                return this.$$(this.fun(this.$$(code.abstraction))(code.argument));
            case 'Tag':
                var element = document.createElement(code.name);
                code.attributes.forEach(function (attribute) {
                    element.appendChild(document.createAttribute(attribute[0],this.$$(attribute[1])));
                });
                code.body.forEach(function (body) {
                    element.appendChild(this.$$(this.$$(body)));
                });
                return element;
            case 'Ident':
                return this.$$(this.environment[code.value]);
            case 'Invoke':
                return this.$$(this.lookup(this.$$(code.instance),code.name));
            case 'Instance':
                return code.instance;
            case 'Controller':
                return code.controller(code); // self - fermeture transitive
            default:
                return code;
        }
    };

    return new Movico();

}());<commit_msg>JS-Hint broken (once again :-()<commit_after>/*global exports, document*/

/*
 * Movico
 * https://github.com/d-plaindoux/movico
 *
 * Copyright (c) 2015 Didier Plaindoux
 * Licensed under the LGPL2 license.
 */

exports.M = (function() {

    function getType(object) {
        if (typeof(object) === 'object') {
            return object.constructor.toString(object).match(/^function\s(.*)\(/)[1];
        } else {
            return typeof(object);
        }
    }

    // ---------------------------------------------------------

    function Lazy(f) {
        this.value = f;
        this.evaluation = undefined;
    }

    function Apply(f,a) {
        this.abstraction = f;
        this.argument = a;
    }

    function UnitAtom() {
        // Nothing
    }

    function NumberAtom(a) {
        this.value = a;
    }

    function StringAtom(a) {
        this.value = a;
    }

    function Tag(n,a,b) {
        this.name = n;
        this.attributes = a;
        this.body = b;
    }

    function Ident(n) {
        this.value = n;
    }

    function Invoke(o,n) {
        this.instance = o;
        this.name = n;
    }

    function Instance(o) {
        this.instance = o;
    }

    function Controller(c) {
        this.controller = c;
    }

    // ---------------------------------------------------------
    // Dictionnary
    // ---------------------------------------------------------

    function Movico() {
        this.environment = {};
        /**
         * Basic definitions - default but can be overriden
         */
        this.define('Pair', function(left,right) { return { '[id]':'Pair',_1:left, _2:right };});
        this.define('string', function(native) { return { '[id]':'number',_:native };});
        this.define('number', function(native) { return { '[id]':'string',_:native };});
    }

    // ---------------------------------------------------------
    // Dictionnary
    // ---------------------------------------------------------

    Movico.prototype.define = function (name, entity) {
        this.environment[name] = entity;
        return entity;
    };

    // ---------------------------------------------------------
    // Abstract instructions
    // ---------------------------------------------------------

    Movico.prototype.unit = new UnitAtom();

    Movico.prototype.string = function(s) {
        return new StringAtom(s);
    };

    Movico.prototype.number = function(n) {
        return new NumberAtom(n);
    };

    Movico.prototype.lazy = function(f) {
        return new Lazy(f);
    };

    Movico.prototype.apply = function(f,a) {
        return new Apply(f,a);
    };

    Movico.prototype.tag = function(n,a,f) {
        return new Tag(n,a,f);
    };

    Movico.prototype.ident = function(i) {
        return new Ident(i);
    };

    Movico.prototype.invoke = function(o,n) {
        return new Invoke(o,n);
    };

    Movico.prototype.instance = function(o) {
        return new Instance(o);
    };

    Movico.prototype.instance = function(o) {
        return new Instance(o);
    };

    Movico.prototype.controller = function(o) {
        return new Controller(o);
    };

    // ---------------------------------------------------------
    // Operational interpretation
    // ---------------------------------------------------------

    function getId(o) {
        if (getType(o) === 'Object' && o.hasOwnProperty('[id]')) {
            return o['[id]'];
        }

        return undefined;
    }

    Movico.prototype.fun = function(o) {
        var id = getId(o);
        if (id !== undefined) {
            return this.$$(this.ident(id));
        }

        return o;
    };

    Movico.prototype.lookup = function(o,n) {
        var methodName = n;

        if (getType(o) === 'Object' && o.hasOwnProperty('[this]')) {
            var id = getId(this.$$(o['this']));
            if (o.hasOwnProperty(id + "::" + n)) {
                methodName = id + "::" + n;
            }
        }

        return o[methodName];
    };

    Movico.prototype.$$ = function(code) {
        switch (getType(code)) {
            case 'NumberAtom':
                return this.$$(this.apply(this.ident("number"),code.value));
            case 'StringAtom':
                return this.$$(this.apply(this.ident("string"),code.value));
            case 'Lazy':
                if (code.evaluation === undefined) {
                    code.evaluation = this.$$(code.value());
                }
                return code.evaluation;
            case 'Apply':
                return this.$$(this.fun(this.$$(code.abstraction))(code.argument));
            case 'Tag':
                var element = document.createElement(code.name);
                code.attributes.forEach(function (attribute) {
                    element.appendChild(document.createAttribute(attribute[0],this.$$(attribute[1])));
                });
                code.body.forEach(function (body) {
                    element.appendChild(this.$$(this.$$(body)));
                });
                return element;
            case 'Ident':
                return this.$$(this.environment[code.value]);
            case 'Invoke':
                return this.$$(this.lookup(this.$$(code.instance),code.name));
            case 'Instance':
                return code.instance;
            case 'Controller':
                return code.controller(code); // self - fermeture transitive
            default:
                return code;
        }
    };

    return new Movico();

}());<|endoftext|>


<commit_before><commit_msg>Fix getter functions on Stopwatch constructor<commit_after><|endoftext|>


<commit_before>const info = require('../package.json');
const conf = require('../config');

exports.register = function (server, options, next) {

  server.route({
    method: '*',                            // all methods
    path: '/proxy/{path}',                  // all routes prefixed with `/api/`
    handler: {
      proxy: {
        passThrough: true,                  // forwards the headers sent from the client to the upstream service
        xforward: true,                     // sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers
        timeout: conf.get('/http/timeout'), // number of milliseconds before aborting the upstream request

        // SIMPLE
        // host: conf.get('/heroku/api'),
        // port: 443,
        // protocol: 'https',

        // ADVANCED
        mapUri: function(request, callback) {
          const host = conf.get('/heroku/api');
          const path = request.url.path.slice(4); // strip `/api` prefix

          // set custom headers
          const headers = Hoek.applyToDefaults(request.headers, {
            'host': host,
            'x-heroku-legacy-ids': true,
            'user-agent': conf.get('/heroku/user-agent')
          });

          callback(null, `https://${host}${path}`, headers);
        }
      }
    }
  });

  next();
};

exports.register.attributes = {
  name: 'proxy',
  version: info.version,
  multiple: true
};
<commit_msg>reference lodash rather than the not-included Hoek library<commit_after>const info = require('../package.json');
const conf = require('../config');
const _ = require('lodash');

exports.register = function (server, options, next) {

  server.route({
    method: '*',                            // all methods
    path: '/proxy/{path}',                  // all routes prefixed with `/api/`
    handler: {
      proxy: {
        passThrough: true,                  // forwards the headers sent from the client to the upstream service
        xforward: true,                     // sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers
        timeout: conf.get('/http/timeout'), // number of milliseconds before aborting the upstream request

        // SIMPLE
        // host: conf.get('/heroku/api'),
        // port: 443,
        // protocol: 'https',

        // ADVANCED
        mapUri: function(request, callback) {
          const host = conf.get('/heroku/api');
          const path = request.url.path.slice(4); // strip `/api` prefix

          // set custom headers
          const headers = _.defaults({}, {
            'host': host,
            'x-heroku-legacy-ids': true,
            'user-agent': conf.get('/heroku/user-agent')
          }, request.headers);

          callback(null, `https://${host}${path}`, headers);
        }
      }
    }
  });

  next();
};

exports.register.attributes = {
  name: 'proxy',
  version: info.version,
  multiple: true
};
<|endoftext|>


<commit_before>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');
var roleRepair = require('role.repair');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'repair') {
        roleRepair.run(creep);
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create() {

	clean();

	if (createCreep('harvester', 6, [WORK, WORK, WORK, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, WORK, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('builder', 2, [WORK, WORK, CARRY, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('repair', 2, [WORK, CARRY, CARRY, MOVE, MOVE, MOVE])){
		return;
	}
	if(createCreep('guard', 4, [ATTACK, ATTACK, MOVE, MOVE, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}
<commit_msg>One repair creep for the start.<commit_after>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');
var roleRepair = require('role.repair');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'repair') {
        roleRepair.run(creep);
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create() {

	clean();

	if (createCreep('harvester', 6, [WORK, WORK, WORK, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, WORK, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('builder', 2, [WORK, WORK, CARRY, CARRY, CARRY, MOVE])){
		return;
	}
	if(createCreep('repair', 1, [WORK, CARRY, CARRY, MOVE, MOVE, MOVE])){
		return;
	}
	if(createCreep('guard', 4, [ATTACK, ATTACK, MOVE, MOVE, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}
<|endoftext|>


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

import { WifHeader as DefaultArticleHeader } from './variants/world-if/header';
import { WifSubheader as DefaultArticleSubheader } from './variants/world-if/subheader';
import { WifFooter as DefaultArticleFooter } from './variants/world-if/footer';
import DefaultArticleBody from './body';

import { passthroughComponentPropTypesOnly, defaultGenerateClassNameList } from './utils';
const defaultVariant = '';

const ArticleContainer = ({ generateClassNameList, sectionName, children }) => (
  <article
    className={classnames(generateClassNameList(`ArticleTemplate--container`))}
    data-section={sectionName}
    itemScope
    itemType="http://schema.org/NewsArticle"
  >
    {children}
  </article>
);
class ArticleTemplate extends Component {

  static get propTypes() {
    return {
      generateClassNameList: PropTypes.func,
      variantName: PropTypes.string,
      components: PropTypes.object,

      id: PropTypes.string.isRequired,
      slug: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      flytitle: PropTypes.string.isRequired,
      rubric: PropTypes.string.isRequired,
      mainImage: PropTypes.shape({
        src: PropTypes.object.isRequired,
        alt: PropTypes.string,
      }).isRequired,
      content: PropTypes.array.isRequired,
      sectionName: PropTypes.string.isRequired,
      sections: PropTypes.object.isRequired,
    };
  }

  static get defaultProps() {
    return {
      variantName: defaultVariant,
      generateClassNameList: defaultGenerateClassNameList,
      components: {
        ArticleHeader: DefaultArticleHeader,
        ArticleSubheader: DefaultArticleSubheader,
        ArticleBody: DefaultArticleBody,
        ArticleFooter: DefaultArticleFooter,
      },
    };
  }

  render() {
    const { variantName, generateClassNameList, sectionName, content } = this.props;
    const { ArticleHeader, ArticleSubheader, ArticleBody, ArticleFooter } = this.props.components;
    return (
      <ArticleContainer generateClassNameList={generateClassNameList} sectionName={sectionName}>
        <ArticleHeader {...passthroughComponentPropTypesOnly(ArticleHeader, this.props)} />
        <ArticleSubheader {...passthroughComponentPropTypesOnly(ArticleSubheader, this.props)} />
        <ArticleBody
          variantName={variantName}
          generateClassNameList={generateClassNameList}
          content={content}
        />
        <ArticleFooter {...passthroughComponentPropTypesOnly(ArticleFooter, this.props)} />
      </ArticleContainer>
    );
  }
}

export default ArticleTemplate;
<commit_msg>Use pof PropTypes.shape instead of PropTypes.object<commit_after>import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';

import { WifHeader as DefaultArticleHeader } from './variants/world-if/header';
import { WifSubheader as DefaultArticleSubheader } from './variants/world-if/subheader';
import { WifFooter as DefaultArticleFooter } from './variants/world-if/footer';
import DefaultArticleBody from './body';

import { passthroughComponentPropTypesOnly, defaultGenerateClassNameList } from './utils';
const defaultVariant = '';

const ArticleContainer = ({ generateClassNameList, sectionName, children }) => (
  <article
    className={classnames(generateClassNameList(`ArticleTemplate--container`))}
    data-section={sectionName}
    itemScope
    itemType="http://schema.org/NewsArticle"
  >
    {children}
  </article>
);
const isComponent = PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]);
class ArticleTemplate extends Component {

  static get propTypes() {
    return {
      generateClassNameList: PropTypes.func,
      variantName: PropTypes.string,
      components: PropTypes.shape({
        ArticleHeader: isComponent,
        ArticleSubheader: isComponent,
        ArticleBody: isComponent,
        ArticleFooter: isComponent,
      }),

      id: PropTypes.string.isRequired,
      slug: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      flytitle: PropTypes.string.isRequired,
      rubric: PropTypes.string.isRequired,
      mainImage: PropTypes.shape({
        src: PropTypes.object.isRequired,
        alt: PropTypes.string,
      }).isRequired,
      content: PropTypes.array.isRequired,
      sectionName: PropTypes.string.isRequired,
      sections: PropTypes.object.isRequired,
    };
  }

  static get defaultProps() {
    return {
      variantName: defaultVariant,
      generateClassNameList: defaultGenerateClassNameList,
      components: {
        ArticleHeader: DefaultArticleHeader,
        ArticleSubheader: DefaultArticleSubheader,
        ArticleBody: DefaultArticleBody,
        ArticleFooter: DefaultArticleFooter,
      },
    };
  }

  render() {
    const { variantName, generateClassNameList, sectionName, content } = this.props;
    const { ArticleHeader, ArticleSubheader, ArticleBody, ArticleFooter } = this.props.components;
    return (
      <ArticleContainer generateClassNameList={generateClassNameList} sectionName={sectionName}>
        <ArticleHeader {...passthroughComponentPropTypesOnly(ArticleHeader, this.props)} />
        <ArticleSubheader {...passthroughComponentPropTypesOnly(ArticleSubheader, this.props)} />
        <ArticleBody
          variantName={variantName}
          generateClassNameList={generateClassNameList}
          content={content}
        />
        <ArticleFooter {...passthroughComponentPropTypesOnly(ArticleFooter, this.props)} />
      </ArticleContainer>
    );
  }
}

export default ArticleTemplate;
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

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.
*/

/**
 * @name cURL
 * @constructor
 *
 * @class
 * Network access via libcurl.
 *
 *
Example:

 *

 * Import('cURL')
 * c = new cURL();
 * c.url = 'http://www.google.com';
 * var status = c.perform();
 *
 * // Currently there is no auto-following of redirects, so:
 * while (status >= 300 && status <= 399) {
 *  c.url = c.header.Location;
 *  status = c.perform();
 * }
 * IO.stdout.write(c.responseBlob);
 *

 *
 */
(function() {
  // Load binary module
  Import('cURL', true);

  try {
    // If we have HTTP.Headers, define a default header callback that
    // creates
    Import('HTTP.Headers');

    /**
     * Array of protocols by the linked version of libcurl.
     * @name supportedProtocols
     * @fieldOf cURL
     */
    /**
     * libcurl version number in hex. For example 7.18.2 is 0x071202
     * @name versionHex
     * @fieldOf cURL
     * @type int
     */
    /**
     * libcurl version number in dotted-decimal string form.
     * @name versionStr
     * @fieldOf cURL
     * @type string
     */

    /**
     * The URL to request
     * @name url
     * @fieldOf cURL.prototype
     */
    /**
     * HTTP Protocol version. Unknown/undefined for non-HTTP requests. See
     * {@link #headerReceived} for caveats.
     * @name protocol
     * @fieldof cURL.prototype
     */
    /**
     * Numeric status code. Might not be defined for non-HTTP requests. See
     * {@link #headerReceived} for caveats.
     * @name status
     * @fieldof cURL.prototype
     */
    /**
     * HUman readable status message. Might not be defined for non-HTTP
     * requests. See {@link #headerReceived} for caveats.
     * @name status
     * @fieldof cURL.prototype
     */
    /**
     * {@link Blob} of the response content. If you replace the
     * {@link #dataReceived} callback than you will have to update this blob
     * yourself.
     * @name responseBlob
     * @fieldOf cURL.prototpe
     */
    /**
     * {@link HTTP.Headers} object containing response headers. See
     * {@link headerReceived} for caveats.
     * @name headers
     * @fieldOf cURL.prototype
     */

    /**
     * Called for each line of the headers. The line includes the new line
     * characters, and the end of headers are signified by "\r\n".

     *
     * Populates the {@link #headers}, {@link #protocol}, {@link #status} and
     * {@link #statusMessage} properties after all headers have been
     * received.

     *
     * This default implementation is conditionally provided on being able to
     * load the {@link HTTP.Headers} module. If it cannot be loaded then the
     * {@link #headers}, {@link #protocol}, {@link #status} and
     * {@link #statusMessage} properties will not be defined.
     *
     * @param line a single line of header data
     * @event
     */
    cURL.prototype.headerReceived = function headerReceived(hdr) {
      if (hdr.match(/^\r\n/)) {
        // Empty line signals end of headers
        try {
          // Pull out HTTP status line.
          var match = /^(HTTP\/1.[10])\s+(\d+)\s+(.*?)\r\n/.exec(this.header_buffer);
          if (match) {
            this.header_buffer = this.header_buffer.substr(match[0].length);
            [undefined, this.protocol, this.status, this.statusMessage] = match;
          }

          this.headers = HTTP.Headers.parse(this.header_buffer);
          delete this.header_buffer;
        }
        catch (e)
        {
        } // Do nothing on error
      }
      else
        this.header_buffer += hdr;
    }
  }
  catch (e if /Unable to find library/.exec(e))
  { // Stomp on the module not found message
  }

  cURL.prototype.dataReceived = function (blob) {
    this.responseBlob.append(blob);
  }

  if (cURL.prototype.perform.old === undefined) {
    var old_perform = cURL.prototype.perform;
    /**
     * Perform the request on {@link #url}.
     *
     * Before the request starts the {@link #headers}, {@link #protocol},
     * {@link #status}, {@link #statusMessage} and the {@link #responseBlob}
     * properties are cleared
     */
    cURL.prototype.perform = function perform() {
      this.header_buffer = "";
      delete this.headers;
      delete this.protocol;
      delete this.status;
      delete this.statusMessage;
      this.responseBlob = new Blob(0);
      return perform.old.apply(this, arguments);
    }
    cURL.prototype.perform.old = old_perform;
  }

  return cURL;
})()

/**
 * Class: cURL
 *
 * Network access via libcurl.
 *
 * Synopsis:
 *
 * (code)
 * import('curl')
 * c = new cURL();
 * c.url = 'http://www.google.com';
 * var status = c.perform();
 *
 * // Currently there is no auto-following of redirects, so:
 * while (status >= 300 && status <= 399) {
 *  c.url = c.header.Location;
 *  status = c.perform();
 * }
 * IO.stdout.write(c.responseBlob);
 * (end code)
 *
 * Group: Constructor Properties
 *
 * Property: supportedProtocols
 *
 * Array of protocols by this module.
 *
 * Property: versionHex
 *
 * libcurl version number in hex. For example 7.18.2 is 0x071202
 *
 * Property: versionStr
 *
 * libcurl version number in dotted-decimal string form.
 *
 * Group: Constructor
 *
 * Constructor: cURL
 *
 * Construct a cURL object. Takes no parameters
 *
 * Group: Methods
 *
 * Method: perform
 *
 * Perform the request on <url>.
 *
 * Before the request starts the <headers>, <protocol>, <status>,
 * <statusMessage> and the <responseBlob> properties are cleared
 *
 * Method: setMethod
 *
 * Set the request method to use when <perform> is called. Currently understood
 * values are "GET", "POST", "PUT" and "HEAD".
 *
 * Parameters:
 *  method - request method
 *
 *
 * Group: Callback Methods
 *
 * Optional methods that get called when headers or data are received.
 *
 * Method: dataReceived
 *
 * Called when a chunk of body data is available. The default implementation
 * simply appends each chunk of data into <responseBlob>.
 *
 * Parameters:
 *  data - a <Blob> of body data.
 *
 * Method: headerReceived
 *
 * Called for each line of the headers. The line includes the new line
 * characters, and the end of headers are signified by "\r\n".
 *
 * Populates the <headers>, <protocol>, <status> and <statusMessage> properties
 * after all headers have been received.
 *
 * Parameters:
 *  line - a single line of header data
 *
 * This default implementation is conditionally provided on being able to load
 * the <HTTP.Headers> module. If it cannot be loaded then the <headers>,
 * <protocol>, <status> and <statusMessage> properties will not be defined.
 */
<commit_msg>Update rest of cURL docs to JsDoc format<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

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.
*/

/**
 * Construct a cURL object. Takes no parameters
 * @name cURL
 * @constructor
 *
 * @class
 * Network access via libcurl.
 *
 *
Example:

 *

 * Import('cURL')
 * c = new cURL();
 * c.url = 'http://www.google.com';
 * var status = c.perform();
 *
 * // Currently there is no auto-following of redirects, so:
 * while (status >= 300 && status <= 399) {
 *  c.url = c.header.Location;
 *  status = c.perform();
 * }
 * IO.stdout.write(c.responseBlob);
 *

 *
 */
(function() {
  // Load binary module
  Import('cURL', true);

  try {
    // If we have HTTP.Headers, define a default header callback that
    // creates
    Import('HTTP.Headers');

    /**
     * Array of protocols by the linked version of libcurl.
     * @name supportedProtocols
     * @fieldOf cURL
     */
    /**
     * libcurl version number in hex. For example 7.18.2 is 0x071202
     * @name versionHex
     * @fieldOf cURL
     * @type int
     */
    /**
     * libcurl version number in dotted-decimal string form.
     * @name versionStr
     * @fieldOf cURL
     * @type string
     */

    /**
     * The URL to request
     * @name url
     * @fieldOf cURL.prototype
     */
    /**
     * HTTP Protocol version. Unknown/undefined for non-HTTP requests. See
     * {@link #headerReceived} for caveats.
     * @name protocol
     * @fieldof cURL.prototype
     * @type strings
     */
    /**
     * Numeric status code. Might not be defined for non-HTTP requests. See
     * {@link #headerReceived} for caveats.
     * @name status
     * @fieldof cURL.prototype
     * @type int
     */
    /**
     * Human readable status message. Might not be defined for non-HTTP
     * requests. See {@link #headerReceived} for caveats.
     * @name statusMessage
     * @fieldof cURL.prototype
     * @type string
     */
    /**
     * Binary response content. If you replace the
     * {@link #dataReceived} callback than you will have to update this blob
     * yourself.
     * @name responseBlob
     * @fieldOf cURL.prototype
     * @type Blob
     */

    /**
     * HTTP response headers (if applicable). See * {@link headerReceived} for
     * caveats.
     * @name headers
     * @fieldOf cURL.prototype
     * @type HTTP.Headers
     */

    /**
     * Set the request method to use when {@link #perform} is called. Currently understood
     * values are "GET", "POST", "PUT" and "HEAD".
     * @name setMethod
     * @methodOf cURL.prototype
     *
     * @param {string} method
     */

    /**
     * Called for each line of the headers. The line includes the new line
     * characters, and the end of headers are signified by "\r\n".

     *
     * Populates the {@link #headers}, {@link #protocol}, {@link #status} and
     * {@link #statusMessage} properties after all headers have been
     * received.

     *
     * This default implementation is conditionally provided on being able to
     * load the {@link HTTP.Headers} module. If it cannot be loaded then the
     * {@link #headers}, {@link #protocol}, {@link #status} and
     * {@link #statusMessage} properties will not be defined.
     *
     * @param line a single line of header data
     * @event
     */
    cURL.prototype.headerReceived = function headerReceived(hdr) {
      if (hdr.match(/^\r\n/)) {
        // Empty line signals end of headers
        try {
          // Pull out HTTP status line.
          var match = /^(HTTP\/1.[10])\s+(\d+)\s+(.*?)\r\n/.exec(this.header_buffer);
          if (match) {
            this.header_buffer = this.header_buffer.substr(match[0].length);
            [undefined, this.protocol, this.status, this.statusMessage] = match;
          }

          this.headers = HTTP.Headers.parse(this.header_buffer);
          delete this.header_buffer;
        }
        catch (e)
        {
        } // Do nothing on error
      }
      else
        this.header_buffer += hdr;
    }
  }
  catch (e if /Unable to find library/.exec(e))
  { // Stomp on the module not found message
  }

  /**
   * Called when a chunk of body data is available. The default implementation
   * simply appends each chunk of data into <responseBlob>.
   * @event
   *
   * @param {Blob} blob chunk of response data
   */
  cURL.prototype.dataReceived = function (blob) {
    this.responseBlob.append(blob);
  }

  if (cURL.prototype.perform.old === undefined) {
    var old_perform = cURL.prototype.perform;
    /**
     * Perform the request on {@link #url}.
     *
     * Before the request starts the {@link #headers}, {@link #protocol},
     * {@link #status}, {@link #statusMessage} and the {@link #responseBlob}
     * properties are cleared
     */
    cURL.prototype.perform = function perform() {
      this.header_buffer = "";
      delete this.headers;
      delete this.protocol;
      delete this.status;
      delete this.statusMessage;
      this.responseBlob = new Blob(0);
      return perform.old.apply(this, arguments);
    }
    cURL.prototype.perform.old = old_perform;
  }

  return cURL;
})()
<|endoftext|>


<commit_before>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create() {

	clean();

	if (createCreep('harvester', 4, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('builder', 6, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('guard', 4, [ATTACK, ATTACK, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	console.log("Waiting for creating new creep with role "+roleTyp);
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}
<commit_msg>More havester<commit_after>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create() {

	clean();

	if (createCreep('harvester', 6, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('builder', 6, [WORK, WORK, CARRY, MOVE])){
		return;
	}
	if(createCreep('guard', 4, [ATTACK, ATTACK, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	console.log("Waiting for creating new creep with role "+roleTyp);
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}
<|endoftext|>


<commit_before>import { css } from "../../src/literals.js";

export default css`
#container {
    display: flex;
    position: fixed;
    top: 0; bottom: 0; left: -300px;
    width: 90vw;
    height: 100vh;
    max-width: 300px;
    z-index: 10001;

    background: white;
    font-family: var(--magnon-font);

    transition: left 0.15s ease-out;
}

#main-nav > ::slotted(a) {
    color: var(--magnon-dark-teal);
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 20px;
    margin: 30px 30px;
    flex-grow: 1;
}

#blackout {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 10000;

    background: var(--magnon-black-blue);
    opacity: 0;
    pointer-events: none;

    transition: opacity 0.2s ease-in-out;
}
`;
<commit_msg>Remove whitespace<commit_after>import { css } from "../../src/literals.js";

export default css`
#container {
    display: flex;
    position: fixed;
    top: 0; bottom: 0; left: -300px;
    width: 90vw;
    height: 100vh;
    max-width: 300px;
    z-index: 10001;

    background: white;
    font-family: var(--magnon-font);

    transition: left 0.15s ease-out;
}

#main-nav > ::slotted(a) {
    color: var(--magnon-dark-teal);
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 20px;
    margin: 30px 30px;
    flex-grow: 1;
}

#blackout {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 10000;

    background: var(--magnon-black-blue);
    opacity: 0;
    pointer-events: none;

    transition: opacity 0.2s ease-in-out;
}
`;
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async-chainable');
var colors = require('colors');
var copy = require('copy');

module.exports = {
	name: 'locations',
	description: 'Backup specified on-disk directories',
	backup: function(finish) {
		async()
			.then(function(next) {
				// Sanity checks {{{
				if (!mindstate.config.enabled) {
					if (mindstate.program.verbose) console.log(colors.grey('Locations backup is disabled'));
					return next('SKIP');
				}

				if (!mindstate.config.locations.dir.length) {
					if (mindstate.program.verbose) console.log(colors.grey('No additional locations to backup'));
					return next('SKIP');
				}
				next();
				// }}}
			})
			.forEach(mindstate.config.locations.dir, function(next, dir) {
				copy.dir(dir, mindstate.tempDir + '/files/' + dir, next);
			})
			.then(function(next) {
				if (mindstate.program.verbose) console.log(colors.blue('[File]'), colors.cyan(mindstate.config.locations.dir.length), 'paths copied');
				return next();
			})
			.end(finish);
	},
	config: function(finish) {
		return finish(null, {
			locations: {
				enabled: true,
				dir: [],
			},
		});
	},
};
<commit_msg>BUGFIX: Incorrect config path when determining if locations backup is enabled<commit_after>var _ = require('lodash');
var async = require('async-chainable');
var colors = require('colors');
var copy = require('copy');

module.exports = {
	name: 'locations',
	description: 'Backup specified on-disk directories',
	backup: function(finish) {
		async()
			.then(function(next) {
				// Sanity checks {{{
				if (!mindstate.config.locations.enabled) {
					if (mindstate.program.verbose) console.log(colors.grey('Locations backup is disabled'));
					return next('SKIP');
				}

				if (!mindstate.config.locations.dir.length) {
					if (mindstate.program.verbose) console.log(colors.grey('No additional locations to backup'));
					return next('SKIP');
				}
				next();
				// }}}
			})
			.forEach(mindstate.config.locations.dir, function(next, dir) {
				copy.dir(dir, mindstate.tempDir + '/files/' + dir, next);
			})
			.then(function(next) {
				if (mindstate.program.verbose) console.log(colors.blue('[File]'), colors.cyan(mindstate.config.locations.dir.length), 'paths copied');
				return next();
			})
			.end(finish);
	},
	config: function(finish) {
		return finish(null, {
			locations: {
				enabled: true,
				dir: [],
			},
		});
	},
};
<|endoftext|>


<commit_before>var Util = require('util');
var Querystring = require('querystring');
var Config = require('../config');

var getHdDefault = function (userAgent) {
  if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Chrome') == -1) {
    return false;
  }

  return true;
};

var makePcConfig = function (iceTransports) {
  var pcConfig = {
    iceServers: [],
    bundlePolicy: 'max-bundle',
    rtcpMuxPolicy: 'require'
  };

  if (iceTransports) {
    pcConfig.iceTransports = iceTransports;
  }

  return pcConfig;
};

var maybeAddConstraint = function (constraints, param, constraint) {
  var object = {};

  if (param && param.toLowerCase() == 'true') {
    object[constraint] = true;
    constraints['optional'].push(object);
  } else if (param && param.toLowerCase() == 'false') {
    object[constraint] = false;
    constraints['optional'].push(object);
  }

  return constraints;
};

var makePcConstraints = function (dtls, dscp, ipv6) {
  var constraints = { optional: [] };
  maybeAddConstraint(constraints, dtls, 'DtlsSrtpKeyAgreement');
  maybeAddConstraint(constraints, dscp, 'googDscp');
  maybeAddConstraint(constraints, ipv6, 'googIPv6');

  return constraints;
};

function addMediaTrackConstraint(trackConstraints, constraintString) {
  var tokens = constraintString.split(':');
  var mandatory = true;

  if (tokens.length == 2) {
    mandatory = (tokens[0] == 'mandatory');
  } else {
    mandatory = !tokens[0].indexOf('goog') == 0;
  }

  tokens = tokens[tokens.length-1].split('=');

  if (tokens.length == 2) {
    if (mandatory) {
      trackConstraints.mandatory[tokens[0]] = tokens[1];
    } else {
      var object = {};
      object[tokens[0]] = tokens[1];
      trackConstraints.optional.push(object);
    }
  } else {
    console.error('Ignoring malformed constraint: ' + constraintString);
  }
};

var makeMediaTrackConstraints = function (constraintsString) {
  var trackConstraints;

  if (!constraintsString || constraintsString.toLowerCase() == 'true') {
    trackConstraints = true;
  } else if (constraintsString.toLowerCase() == 'false') {
    trackConstraints = false;
  } else {
    trackConstraints = { mandatory: {}, optional: [] };
    var constraintsArray = constraintsString.split(',');

    for (var i in constraintsArray) {
      var constraintString = constraintsArray[i];
      addMediaTrackConstraint(trackConstraints, constraintString);
    }
  }

  return trackConstraints;
};

var makeMediaStreamConstraints = function (audio, video, firefoxFakeDevice) {
  var streamConstraints = {
    audio: makeMediaTrackConstraints(audio),
    video: makeMediaTrackConstraints(video)
  };

  if (firefoxFakeDevice) streamConstraints.fake = true;

  console.log('Applying media constraints: ' + JSON.stringify(streamConstraints))

  return streamConstraints;
};

var getWSSParameters = function (request) {
  var wssHostPortPair = request.params.wshpp;
  var wssTLS = request.query.wstls;

  if (!wssHostPortPair) {
    wssHostPortPair = Config.constant.WSS_HOST_PORT_PAIRS[0];
  }

  if (wssTLS && wssTLS == 'false') {
    return {
      wssUrl: 'ws://' + wssHostPortPair + '/ws',
      wssPostUrl: 'http://' + wssHostPortPair
    }
  } else {
    return {
      wssUrl: 'wss://' + wssHostPortPair + '/ws',
      wssPostUrl: 'https://' + wssHostPortPair
    }
  }
};

var getVersionInfo = function () {
  return null;
};

var generateRandom = function (length) {
  var word = '';

  for (var i = 0; i < length; i++) {
    word += Math.floor((Math.random() * 10));
  }

  return word;
};

exports.getRoomParameters = function (request, roomId, clientId, isInitiator) {
  var errorMessages = [];
  var warningMessages = [];

  var userAgent = request.headers['user-agent'];
  var responseType = request.params.t;
  var iceTransports = request.params.it;
  var turnTransports = request.params.tt;
  var turnBaseUrl = request.params.ts || Config.constant.TURN_BASE_URL;

  var audio = request.params.audio;
  var video = request.params.video;
  var firefoxFakeDevice = request.params.firefox_fake_device;
  var hd = request.params.hd ? request.params.hd.toLowerCase() : null;

  if (video && hd) {
    var message = 'The "hd" parameter has overridden video=' + video;
    errorMessages.push(message);
    console.log(message);
  }

  if (hd == 'true') {
    video = 'mandatory:minWidth=1280,mandatory:minHeight=720';
  } else if (!video && !hd && getHdDefault(userAgent)) {
    video = 'optional:minWidth=1280,optional:minHeight=720';
  }

  if (request.params.minre || request.params.maxre) {
    var message = 'The "minre" and "maxre" parameters are no longer supported. Use "video" instead.';
    errorMessages.push(message);
    console.error(message);
  }

  var dtls = request.params.dtls;
  var dscp = request.params.dscp;
  var ipv6 = request.params.ipv6;

  var debug = request.params.debug;

  if (debug == 'loopback') {
    var includeLoopbackJS = '<script src="/js/loopback.js"></script>';
    dtls = 'false';
  } else {
    var includeLoopbackJS = '';
  }

  var username = clientId ? clientId : generateRandom(9);
  var turnUrl = turnBaseUrl.length > 0 ? Util.format(Config.constant.TURN_URL_TEMPLATE, turnBaseUrl, 'webrtc', 'webrtc') : null;

  var pcConfig = makePcConfig(iceTransports);
  var pcConstraints = makePcConstraints(dtls, dscp, ipv6);
  var offerOptions = {};
  var mediaConstraints = makeMediaStreamConstraints(audio, video, firefoxFakeDevice);

  var wssParams = getWSSParameters(request);
  var wssUrl = wssParams.wssUrl;
  var wssPostUrl = wssParams.wssPostUrl;

  var bypassJoinConfirmation = false;

  var params = {
    'error_messages': errorMessages,
    'warning_messages': warningMessages,
    'is_loopback' : JSON.stringify(debug == 'loopback'),
    'pc_config': JSON.stringify(pcConfig),
    'pc_constraints': JSON.stringify(pcConstraints),
    'offer_options': JSON.stringify(offerOptions),
    'media_constraints': JSON.stringify(mediaConstraints),
    'turn_url': turnUrl,
    'turn_transports': turnTransports,
    'include_loopback_js' : includeLoopbackJS,
    'wss_url': wssUrl,
    'wss_post_url': wssPostUrl,
    'bypass_join_confirmation': JSON.stringify(bypassJoinConfirmation),
    'version_info': JSON.stringify(getVersionInfo())
  };

  var protocol = request.headers['x-forwarded-proto'] || 'http';

  if (roomId) {
    params['room_id'] = roomId;
    params['room_link'] =  protocol + '://' + request.headers['host'] + '/r/' + roomId;
  }

  if (clientId) {
    params['client_id'] = clientId;
  }

  if (typeof isInitiator === 'boolean') {
    params['is_initiator'] = JSON.stringify(isInitiator);
  }

  return params;
};

exports.getCacheKeyForRoom = function (host, roomId) {
  return host + '/' + roomId;
};

exports.generateRandom = generateRandom;
<commit_msg>Make sure userAgent is not undefined.<commit_after>var Util = require('util');
var Querystring = require('querystring');
var Config = require('../config');

var getHdDefault = function (userAgent) {
  if (typeof userAgent !== 'undefined') {
    if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Chrome') == -1) {
      return false;
    }
  }

  return true;
};

var makePcConfig = function (iceTransports) {
  var pcConfig = {
    iceServers: [],
    bundlePolicy: 'max-bundle',
    rtcpMuxPolicy: 'require'
  };

  if (iceTransports) {
    pcConfig.iceTransports = iceTransports;
  }

  return pcConfig;
};

var maybeAddConstraint = function (constraints, param, constraint) {
  var object = {};

  if (param && param.toLowerCase() == 'true') {
    object[constraint] = true;
    constraints['optional'].push(object);
  } else if (param && param.toLowerCase() == 'false') {
    object[constraint] = false;
    constraints['optional'].push(object);
  }

  return constraints;
};

var makePcConstraints = function (dtls, dscp, ipv6) {
  var constraints = { optional: [] };
  maybeAddConstraint(constraints, dtls, 'DtlsSrtpKeyAgreement');
  maybeAddConstraint(constraints, dscp, 'googDscp');
  maybeAddConstraint(constraints, ipv6, 'googIPv6');

  return constraints;
};

function addMediaTrackConstraint(trackConstraints, constraintString) {
  var tokens = constraintString.split(':');
  var mandatory = true;

  if (tokens.length == 2) {
    mandatory = (tokens[0] == 'mandatory');
  } else {
    mandatory = !tokens[0].indexOf('goog') == 0;
  }

  tokens = tokens[tokens.length-1].split('=');

  if (tokens.length == 2) {
    if (mandatory) {
      trackConstraints.mandatory[tokens[0]] = tokens[1];
    } else {
      var object = {};
      object[tokens[0]] = tokens[1];
      trackConstraints.optional.push(object);
    }
  } else {
    console.error('Ignoring malformed constraint: ' + constraintString);
  }
};

var makeMediaTrackConstraints = function (constraintsString) {
  var trackConstraints;

  if (!constraintsString || constraintsString.toLowerCase() == 'true') {
    trackConstraints = true;
  } else if (constraintsString.toLowerCase() == 'false') {
    trackConstraints = false;
  } else {
    trackConstraints = { mandatory: {}, optional: [] };
    var constraintsArray = constraintsString.split(',');

    for (var i in constraintsArray) {
      var constraintString = constraintsArray[i];
      addMediaTrackConstraint(trackConstraints, constraintString);
    }
  }

  return trackConstraints;
};

var makeMediaStreamConstraints = function (audio, video, firefoxFakeDevice) {
  var streamConstraints = {
    audio: makeMediaTrackConstraints(audio),
    video: makeMediaTrackConstraints(video)
  };

  if (firefoxFakeDevice) streamConstraints.fake = true;

  console.log('Applying media constraints: ' + JSON.stringify(streamConstraints))

  return streamConstraints;
};

var getWSSParameters = function (request) {
  var wssHostPortPair = request.params.wshpp;
  var wssTLS = request.query.wstls;

  if (!wssHostPortPair) {
    wssHostPortPair = Config.constant.WSS_HOST_PORT_PAIRS[0];
  }

  if (wssTLS && wssTLS == 'false') {
    return {
      wssUrl: 'ws://' + wssHostPortPair + '/ws',
      wssPostUrl: 'http://' + wssHostPortPair
    }
  } else {
    return {
      wssUrl: 'wss://' + wssHostPortPair + '/ws',
      wssPostUrl: 'https://' + wssHostPortPair
    }
  }
};

var getVersionInfo = function () {
  return null;
};

var generateRandom = function (length) {
  var word = '';

  for (var i = 0; i < length; i++) {
    word += Math.floor((Math.random() * 10));
  }

  return word;
};

exports.getRoomParameters = function (request, roomId, clientId, isInitiator) {
  var errorMessages = [];
  var warningMessages = [];

  var userAgent = request.headers['user-agent'];
  var responseType = request.params.t;
  var iceTransports = request.params.it;
  var turnTransports = request.params.tt;
  var turnBaseUrl = request.params.ts || Config.constant.TURN_BASE_URL;

  var audio = request.params.audio;
  var video = request.params.video;
  var firefoxFakeDevice = request.params.firefox_fake_device;
  var hd = request.params.hd ? request.params.hd.toLowerCase() : null;

  if (video && hd) {
    var message = 'The "hd" parameter has overridden video=' + video;
    errorMessages.push(message);
    console.log(message);
  }

  if (hd == 'true') {
    video = 'mandatory:minWidth=1280,mandatory:minHeight=720';
  } else if (!video && !hd && getHdDefault(userAgent)) {
    video = 'optional:minWidth=1280,optional:minHeight=720';
  }

  if (request.params.minre || request.params.maxre) {
    var message = 'The "minre" and "maxre" parameters are no longer supported. Use "video" instead.';
    errorMessages.push(message);
    console.error(message);
  }

  var dtls = request.params.dtls;
  var dscp = request.params.dscp;
  var ipv6 = request.params.ipv6;

  var debug = request.params.debug;

  if (debug == 'loopback') {
    var includeLoopbackJS = '<script src="/js/loopback.js"></script>';
    dtls = 'false';
  } else {
    var includeLoopbackJS = '';
  }

  var username = clientId ? clientId : generateRandom(9);
  var turnUrl = turnBaseUrl.length > 0 ? Util.format(Config.constant.TURN_URL_TEMPLATE, turnBaseUrl, 'webrtc', 'webrtc') : null;

  var pcConfig = makePcConfig(iceTransports);
  var pcConstraints = makePcConstraints(dtls, dscp, ipv6);
  var offerOptions = {};
  var mediaConstraints = makeMediaStreamConstraints(audio, video, firefoxFakeDevice);

  var wssParams = getWSSParameters(request);
  var wssUrl = wssParams.wssUrl;
  var wssPostUrl = wssParams.wssPostUrl;

  var bypassJoinConfirmation = false;

  var params = {
    'error_messages': errorMessages,
    'warning_messages': warningMessages,
    'is_loopback' : JSON.stringify(debug == 'loopback'),
    'pc_config': JSON.stringify(pcConfig),
    'pc_constraints': JSON.stringify(pcConstraints),
    'offer_options': JSON.stringify(offerOptions),
    'media_constraints': JSON.stringify(mediaConstraints),
    'turn_url': turnUrl,
    'turn_transports': turnTransports,
    'include_loopback_js' : includeLoopbackJS,
    'wss_url': wssUrl,
    'wss_post_url': wssPostUrl,
    'bypass_join_confirmation': JSON.stringify(bypassJoinConfirmation),
    'version_info': JSON.stringify(getVersionInfo())
  };

  var protocol = request.headers['x-forwarded-proto'] || 'http';

  if (roomId) {
    params['room_id'] = roomId;
    params['room_link'] =  protocol + '://' + request.headers['host'] + '/r/' + roomId;
  }

  if (clientId) {
    params['client_id'] = clientId;
  }

  if (typeof isInitiator === 'boolean') {
    params['is_initiator'] = JSON.stringify(isInitiator);
  }

  return params;
};

exports.getCacheKeyForRoom = function (host, roomId) {
  return host + '/' + roomId;
};

exports.generateRandom = generateRandom;
<|endoftext|>


<commit_before>// Generated on 2015-07-27 using generator-angular 0.12.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates'
  });

  grunt.loadNpmTasks('grunt-connect-proxy');

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'src',
    dist: 'target'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      proxies: [{
        context: '/policy', // the context of the data service
        host: '127.0.0.1', // wherever the data service is running
        port: 9090, // the port that the data service is running on,
        changeOrigin: true,
        ws: true
      }],
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app),
              require('grunt-connect-proxy/lib/utils').proxyRequest
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//,
        "dependencies": {
          "compass-mixins": "0.12.7"
        },
        "overrides": {
          "compass-mixins": {
            "main": "."
          }
        }
      }
    },

    sass: {
      options: {
        sourceMap: true
      },
      dist: {
        files: {
          '.tmp/styles/main.css': '<%= yeoman.app %>/styles/main.scss'
        }
      },
      server: {
        options: {
          debugInfo: true
        },
        files: {
          '.tmp/styles/main.css': '<%= yeoman.app %>/styles/main.scss'
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ],
        patterns: {
          js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
        }
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    ngtemplates: {
      dist: {
        options: {
          module: 'webApp',
          htmlmin: '<%= htmlmin.dist.options %>',
          usemin: 'scripts/scripts.js'
        },
        cwd: '<%= yeoman.app %>',
        src: 'views/{,*/}*.html',
        dest: '.tmp/templateCache.js'
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
       server: [
          'sass:server'
        ],
        test: [
          'sass'
        ],
        dist: [
          'sass:dist',
          'imagemin',
          'svgmin'
        ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'configureProxies:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'ngtemplates',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>Fix gruntfile<commit_after>// Generated on 2015-07-27 using generator-angular 0.12.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates'
  });

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'src',
    dist: 'target'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      proxies: [
      {
        context: '/policy', // the context of the data service
        host: '127.0.0.1', // wherever the data service is running
        port: 9090, // the port that the data service is running on,
        changeOrigin: true,
        ws: true
      },
      {
        context: '/template', // the context of the data service
        host: '127.0.0.1', // wherever the data service is running
        port: 9090, // the port that the data service is running on,
        changeOrigin: true,
        ws: true
      }],
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app),
              require('grunt-connect-proxy/lib/utils').proxyRequest
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//,
        "dependencies": {
          "compass-mixins": "0.12.7"
        },
        "overrides": {
          "compass-mixins": {
            "main": "."
          }
        }
      }
    },

    sass: {
      options: {
        sourceMap: true
      },
      dist: {
        files: {
          '.tmp/styles/main.css': '<%= yeoman.app %>/styles/main.scss'
        }
      },
      server: {
        options: {
          debugInfo: true
        },
        files: {
          '.tmp/styles/main.css': '<%= yeoman.app %>/styles/main.scss'
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ],
        patterns: {
          js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
        }
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    ngtemplates: {
      dist: {
        options: {
          module: 'webApp',
          htmlmin: '<%= htmlmin.dist.options %>',
          usemin: 'scripts/scripts.js'
        },
        cwd: '<%= yeoman.app %>',
        src: 'views/{,*/}*.html',
        dest: '.tmp/templateCache.js'
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
       server: [
          'sass:server'
        ],
        test: [
          'sass'
        ],
        dist: [
          'sass:dist',
          'imagemin',
          'svgmin'
        ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    grunt.loadNpmTasks('grunt-connect-proxy');
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'configureProxies:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'ngtemplates',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>