<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Config;

(function ()
{
    Config =
    {
        configObject: {},
        types: {}
    };

    $(document).ready(loadConfig);

    function loadConfig()
    {
        var configXML = $($.parseXML($('#config').text())).children('config');
        var config = {};

        var defaultScopes = { statementScope: 'independent' };
        config.properties = loadPropertyCollection(configXML.children('properties'), 'toplevel', defaultScopes);

        Config.configObject = config;
    }

    function loadPropertyNode(nodeXML, parentScopes)
    {
        if (nodeXML.nodeName === "property")
        {
            var propertyScopes = loadScopes(nodeXML);
            mergeScopes(propertyScopes, parentScopes);
            return {
                kind: 'property',
                id: nodeXML.getAttribute('id'),
                name: nodeXML.getAttribute('name'),
                description: nodeXML.getAttribute('description'),
                optional: Boolean(nodeXML.getAttribute('optional')),
                scopes: propertyScopes,
                type: loadType($(nodeXML).children().eq(0))
            };
        }
        else if (nodeXML.nodeName === "propertySection")
        {
            var subResult = loadPropertyCollection($(nodeXML), 'section', parentScopes);
            subResult.name = nodeXML.getAttribute('name');
            return subResult;
        }
        else
        {
            return loadPropertyCollection($(nodeXML), 'group', parentScopes);
        }
    }

    function loadPropertyCollection(collectionXML, kind, parentScopes)
    {
        var collectionScopes = loadScopes(collectionXML[0]);
        mergeScopes(collectionScopes, parentScopes);

        var sequence = [];
        var byId = {};
        collectionXML.children().each(function (index, childXML)
        {
            var subResult = loadPropertyNode(childXML, collectionScopes);
            if (subResult.kind === 'property')
            {
                sequence.push(subResult);
                byId[subResult.id] = subResult;
            }
            else if (subResult.kind === 'group')
            {
                sequence = sequence.concat(subResult.sequence);
                $.extend(byId, subResult.byId);
            }
            else if (subResult.kind === 'section')
            {
                sequence.push(subResult);
                $.extend(byId, subResult.byId);
            }
        });
        return { kind: kind, scopes: collectionScopes, sequence: sequence, byId: byId };
    }

    function loadScopes(scopedXML)
    {
        return { statementScope: scopedXML.getAttribute('statementScope') };
    }

    function mergeScopes(localScopes, parentScopes)
    {
        for (var scopeName in parentScopes)
        {
            if (!localScopes[scopeName])
            {
                localScopes[scopeName] = parentScopes[scopeName];
            }
        }
    }

    function loadType(typeXML)
    {
        var typeName = typeXML[0].nodeName.substr('type'.length).toLowerCase();
        return Config.types[typeName].loadType(typeXML);
    }

    function appendChild(parentXML, name)
    {
        parentXML.appendChild(document.createElementNS(parentXML.namespaceURI, name));
    }

    function toXMLSimple(valueXML, value)
    {
        valueXML.textContent = value;
    }

    Config.types =
    {
        'string':
        {
            name: 'string',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeString');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'text' }));
            },
            getFromDOM: function(containerEl)
            {
                return containerEl.children('input').first().val();
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return valueXML.textContent;
            },
            toXML: toXMLSimple
        },
        'integer':
        {
            name: 'integer',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeInteger');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'number', value: 0 }));
            },
            getFromDOM: function(containerEl)
            {
                // Note the defaulting of NaN to 0: we want to avoid
                // NaNs where integers are expected at all costs.
                var value = parseInt(containerEl.children('input').first().val(), 10);
                return isNaN(value) ? 0 : parseInt(value, 10);
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return parseInt(valueXML.textContent, 10);
            },
            toXML: toXMLSimple
        },
        'boolean':
        {
            name: 'boolean',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeBoolean');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'checkbox' }));
            },
            getFromDOM: function(containerEl)
            {
                return Boolean(containerEl.children('input').first().prop('checked'));
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().prop('checked', value);
            },
            fromXML: function(valueXML)
            {
                return Boolean(valueXML.textContent);
            },
            toXML: toXMLSimple
        },
        'enumeration':
        {
            name: 'enumeration',
            loadType: function(typeXML)
            {
                var values = [];
                typeXML.children('option').each(function(index, valueXML)
                {
                    values.push(valueXML.textContent);
                });
                return $.extend({ values: values }, this);
            },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeString');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                var selectEl = $('<select>', { id: htmlId });
                this.values.forEach(function(value)
                {
                    selectEl.append($('<option>', { text: value, value: value }));
                });
                containerEl.append(selectEl);
            },
            getFromDOM: function(containerEl)
            {
                return containerEl.children('select').first().val();
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('select').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return valueXML.textContent;
            },
            toXML: toXMLSimple
        }
    };
})();
<commit_msg>Implemented character loading from config<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Config;

(function ()
{
    Config =
    {
        configObject: {},
        types: {}
    };

    var defaultScopes = { statementScope: 'independent' };
    var defaultPropertyCollection = { kind: 'toplevel', scopes: defaultScopes, sequence: [], byId: {} };

    $(document).ready(loadConfig);

    function loadConfig()
    {
        var configXML = $($.parseXML($('#config').text())).children('config');
        var config = {};

        config.properties = loadPropertyCollection(configXML.children('properties'), 'toplevel', defaultScopes);

        if (configXML.children('character').length > 0)
        {
            config.characters = { properties: $.extend({}, defaultPropertyCollection) };
            config.characters['character'] = loadCharacterNode(configXML.children('character'), 'character');
        }
        else
        {
            config.characters = loadCharacterCollection(configXML.children('characters'));
        }

        Config.configObject = config;
    }

    function loadPropertyNode(nodeXML, parentScopes)
    {
        if (nodeXML.nodeName === "property")
        {
            var propertyScopes = loadScopes(nodeXML);
            mergeScopes(propertyScopes, parentScopes);
            return {
                kind: 'property',
                id: nodeXML.getAttribute('id'),
                name: nodeXML.getAttribute('name'),
                description: nodeXML.getAttribute('description'),
                optional: Boolean(nodeXML.getAttribute('optional')),
                scopes: propertyScopes,
                type: loadType($(nodeXML).children().eq(0))
            };
        }
        else if (nodeXML.nodeName === "propertySection")
        {
            var subResult = loadPropertyCollection($(nodeXML), 'section', parentScopes);
            subResult.name = nodeXML.getAttribute('name');
            return subResult;
        }
        else
        {
            return loadPropertyCollection($(nodeXML), 'group', parentScopes);
        }
    }

    function loadPropertyCollection(collectionXML, kind, parentScopes)
    {
        var collectionScopes = loadScopes(collectionXML[0]);
        mergeScopes(collectionScopes, parentScopes);

        var sequence = [];
        var byId = {};
        collectionXML.children().each(function (index, childXML)
        {
            var subResult = loadPropertyNode(childXML, collectionScopes);
            if (subResult.kind === 'property')
            {
                sequence.push(subResult);
                byId[subResult.id] = subResult;
            }
            else if (subResult.kind === 'group')
            {
                sequence = sequence.concat(subResult.sequence);
                $.extend(byId, subResult.byId);
            }
            else if (subResult.kind === 'section')
            {
                sequence.push(subResult);
                $.extend(byId, subResult.byId);
            }
        });
        return { kind: kind, scopes: collectionScopes, sequence: sequence, byId: byId };
    }

    function loadScopes(scopedXML)
    {
        return { statementScope: scopedXML.getAttribute('statementScope') };
    }

    function mergeScopes(localScopes, parentScopes)
    {
        for (var scopeName in parentScopes)
        {
            if (!localScopes[scopeName])
            {
                localScopes[scopeName] = parentScopes[scopeName];
            }
        }
    }

    function loadType(typeXML)
    {
        var typeName = typeXML[0].nodeName.substr('type'.length).toLowerCase();
        return Config.types[typeName].loadType(typeXML);
    }

    function appendChild(parentXML, name)
    {
        parentXML.appendChild(document.createElementNS(parentXML.namespaceURI, name));
    }

    function toXMLSimple(valueXML, value)
    {
        valueXML.textContent = value;
    }

    function loadCharacterCollection(collectionXML)
    {
        var characters = {};
        collectionXML.children('character').each(function(index, childXML)
        {
            var characterID = 'character' + index;
            characters[characterID] = loadCharacterNode(childXML, characterID);
        });
        characters.properties = loadPropertyCollectionOrDefault($(collectionXML).children('properties'));
        return characters;
    }

    function loadCharacterNode(nodeXML, characterID)
    {
        var properties = loadPropertyCollectionOrDefault($(nodeXML).children('properties'));
        return { id: characterID, properties: properties};
    }

    function loadPropertyCollectionOrDefault(propertiesXML)
    {
        var properties = {};
        if (propertiesXML.length > 0)
        {
            properties = loadPropertyCollection(propertiesXML, 'toplevel', defaultScopes);
        }
        else
        {
            $.extend(properties, defaultPropertyCollection);
        }
        return properties;
    }

    Config.types =
    {
        'string':
        {
            name: 'string',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeString');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'text' }));
            },
            getFromDOM: function(containerEl)
            {
                return containerEl.children('input').first().val();
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return valueXML.textContent;
            },
            toXML: toXMLSimple
        },
        'integer':
        {
            name: 'integer',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeInteger');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'number', value: 0 }));
            },
            getFromDOM: function(containerEl)
            {
                // Note the defaulting of NaN to 0: we want to avoid
                // NaNs where integers are expected at all costs.
                var value = parseInt(containerEl.children('input').first().val(), 10);
                return isNaN(value) ? 0 : parseInt(value, 10);
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return parseInt(valueXML.textContent, 10);
            },
            toXML: toXMLSimple
        },
        'boolean':
        {
            name: 'boolean',
            loadType: function(typeXML) { return this; },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeBoolean');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                containerEl.append($('<input>', { id: htmlId, type: 'checkbox' }));
            },
            getFromDOM: function(containerEl)
            {
                return Boolean(containerEl.children('input').first().prop('checked'));
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('input').first().prop('checked', value);
            },
            fromXML: function(valueXML)
            {
                return Boolean(valueXML.textContent);
            },
            toXML: toXMLSimple
        },
        'enumeration':
        {
            name: 'enumeration',
            loadType: function(typeXML)
            {
                var values = [];
                typeXML.children('option').each(function(index, valueXML)
                {
                    values.push(valueXML.textContent);
                });
                return $.extend({ values: values }, this);
            },
            insertUnderlyingType: function(typeXML)
            {
                appendChild(typeXML, 'typeString');
            },
            appendControlTo: function(containerEl, htmlId)
            {
                var selectEl = $('<select>', { id: htmlId });
                this.values.forEach(function(value)
                {
                    selectEl.append($('<option>', { text: value, value: value }));
                });
                containerEl.append(selectEl);
            },
            getFromDOM: function(containerEl)
            {
                return containerEl.children('select').first().val();
            },
            setInDOM: function(containerEl, value)
            {
                containerEl.children('select').first().val(value);
            },
            fromXML: function(valueXML)
            {
                return valueXML.textContent;
            },
            toXML: toXMLSimple
        }
    };
})();
<|endoftext|>


<commit_before>import {ipcRenderer} from 'electron'
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router'

export default class SideMenu extends Component {
    render() {
        const {account, onClickedNewTweet} = this.props;

        return (

                <Link to="/">

                </Link>
                <Link to="/favorites">

                </Link>
                <Link to="/account-info">

                </Link>

        );
    }

}

SideMenu.propTypes = {
    account: PropTypes.object.isRequired,
    onClickedNewTweet: PropTypes.func.isRequired
};
<commit_msg>Lint: SideMenu<commit_after>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';

export default class SideMenu extends Component {
  render() {
    const { account, onClickedNewTweet } = this.props;

    return (

        <Link to="/">

        </Link>
        <Link to="/favorites">

        </Link>
        <Link to="/account-info">

        </Link>

    );
  }

}

SideMenu.propTypes = {
  account: PropTypes.object.isRequired,
  onClickedNewTweet: PropTypes.func.isRequired
};
<|endoftext|>


<commit_before>import td from 'testdouble';
import { expect } from 'chai';

describe('requestWrapper', () => {
  let constantsBuilder;
  let actionsBuilder;
  let sagasBuilder;
  let requestWrapper;

  let request;
  let constantCreator;

  beforeEach(() => {
    constantsBuilder = td.replace('../constantsBuilder.js').constantsBuilder;
    actionsBuilder = td.replace('../actionsBuilder.js').actionsBuilder;
    sagasBuilder = td.replace('../sagasBuilder.js').sagasBuilder;
    requestWrapper = require('../requestWrapper.js').requestWrapper;

    request = td.function();
    constantCreator = {
      createChild: td.function(),
      createConstant: td.function(),
    };

    const constants = {
      REQUEST: 'REQUEST',
      PENDING: 'PENDING',
      SUCCESS: 'SUCCESS',
      FAILURE: 'FAILURE',
    };
    td.when(constantsBuilder(td.matchers.anything())).thenReturn(constants);

    const actions = {
      request: td.function(),
      pending: td.function(),
      success: td.function(),
      failure: td.function(),
    };
    td.when(actionsBuilder(td.matchers.anything())).thenReturn(actions);

    td.when(sagasBuilder(request, constants.REQUEST, actions, { throwErrors: false })).thenReturn({
      makeRequest: td.function(),
      watchForRequest: td.function(),
    });
  });

  afterEach(() => {
    td.reset();
  });

  it('should be a function', () => {
    expect(requestWrapper).to.be.a('function');
  });

  describe('default', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator);
    });

    it('should export constants', () => {
      expect(result).to.have.property('constants');
      const { constants } = result;
      expect(constants).to.have.property('REQUEST');
      expect(constants).to.have.property('PENDING');
      expect(constants).to.have.property('SUCCESS');
      expect(constants).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('actions');
      const { actions } = result;
      expect(actions).to.have.property('request');
      expect(actions).to.have.property('pending');
      expect(actions).to.have.property('success');
      expect(actions).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('sagas');
      const { sagas } = result;
      expect(sagas).to.have.property('makeRequest');
      expect(sagas).to.have.property('watchForRequest');
    });
  });

  describe('namespaced', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { namespace: 'namespace' });
    });

    it('should export constants', () => {
      expect(result).to.have.property('constants');
      const { constants } = result;
      expect(constants).to.have.property('REQUEST');
      expect(constants).to.have.property('PENDING');
      expect(constants).to.have.property('SUCCESS');
      expect(constants).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('actions');
      const { actions } = result;
      expect(actions).to.have.property('request');
      expect(actions).to.have.property('pending');
      expect(actions).to.have.property('success');
      expect(actions).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('actions');
      const { sagas } = result;
      expect(sagas).to.have.property('makeRequest');
      expect(sagas).to.have.property('watchForRequest');
    });
  });

  describe('flattened exports', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { flattenExports: true });
    });

    it('should export constants', () => {
      expect(result).to.have.property('REQUEST');
      expect(result).to.have.property('PENDING');
      expect(result).to.have.property('SUCCESS');
      expect(result).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('request');
      expect(result).to.have.property('pending');
      expect(result).to.have.property('success');
      expect(result).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('makeRequest');
      expect(result).to.have.property('watchForRequest');
    });
  });

  describe('flattened namespaced exports', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { namespace: 'namespace', flattenExports: true });
    });

    it('should export constants', () => {
      expect(result).to.have.property('REQUEST');
      expect(result).to.have.property('PENDING');
      expect(result).to.have.property('SUCCESS');
      expect(result).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('request');
      expect(result).to.have.property('pending');
      expect(result).to.have.property('success');
      expect(result).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('makeRequest');
      expect(result).to.have.property('watchForRequest');
    });
  });
});
<commit_msg>requestWrapper: Test for named exports<commit_after>import td from 'testdouble';
import { expect } from 'chai';

describe('requestWrapper', () => {
  let constantsBuilder;
  let actionsBuilder;
  let sagasBuilder;
  let requestWrapper;

  let request;
  let constantCreator;

  beforeEach(() => {
    constantsBuilder = td.replace('../constantsBuilder.js').constantsBuilder;
    actionsBuilder = td.replace('../actionsBuilder.js').actionsBuilder;
    sagasBuilder = td.replace('../sagasBuilder.js').sagasBuilder;
    requestWrapper = require('../requestWrapper.js').requestWrapper;

    request = td.function();
    constantCreator = {
      createChild: td.function(),
      createConstant: td.function(),
    };

    const constants = {
      REQUEST: 'REQUEST',
      PENDING: 'PENDING',
      SUCCESS: 'SUCCESS',
      FAILURE: 'FAILURE',
    };
    td.when(constantsBuilder(td.matchers.anything())).thenReturn(constants);

    const actions = {
      request: td.function(),
      pending: td.function(),
      success: td.function(),
      failure: td.function(),
    };
    td.when(actionsBuilder(td.matchers.anything())).thenReturn(actions);

    td.when(sagasBuilder(request, constants.REQUEST, actions, { throwErrors: false })).thenReturn({
      makeRequest: td.function(),
      watchForRequest: td.function(),
    });
  });

  afterEach(() => {
    td.reset();
  });

  it('should be a function', () => {
    expect(requestWrapper).to.be.a('function');
  });

  describe('default', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator);
    });

    it('should export constants', () => {
      expect(result).to.have.property('constants');
      const { constants } = result;
      expect(constants).to.have.property('REQUEST');
      expect(constants).to.have.property('PENDING');
      expect(constants).to.have.property('SUCCESS');
      expect(constants).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('actions');
      const { actions } = result;
      expect(actions).to.have.property('request');
      expect(actions).to.have.property('pending');
      expect(actions).to.have.property('success');
      expect(actions).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('sagas');
      const { sagas } = result;
      expect(sagas).to.have.property('makeRequest');
      expect(sagas).to.have.property('watchForRequest');
    });
  });

  describe('namespaced', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { namespace: 'namespace' });
    });

    it('should export constants', () => {
      expect(result).to.have.property('constants');
      const { constants } = result;
      expect(constants).to.have.property('REQUEST');
      expect(constants).to.have.property('PENDING');
      expect(constants).to.have.property('SUCCESS');
      expect(constants).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.have.property('actions');
      const { actions } = result;
      expect(actions).to.have.property('request');
      expect(actions).to.have.property('pending');
      expect(actions).to.have.property('success');
      expect(actions).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.have.property('sagas');
      const { sagas } = result;
      expect(sagas).to.have.property('makeRequest');
      expect(sagas).to.have.property('watchForRequest');
    });
  });

  describe('named exports', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { namedExports: true, namespace: 'namespace' });
    });

    it('should export constants', () => {
      const { constants } = result;
      expect(constants).to.have.property('NAMESPACE_REQUEST');
      expect(constants).to.have.property('NAMESPACE_PENDING');
      expect(constants).to.have.property('NAMESPACE_SUCCESS');
      expect(constants).to.have.property('NAMESPACE_FAILURE');
    });

    it('should export actions', () => {
      const { actions } = result;
      expect(actions).to.have.property('namespaceRequest');
      expect(actions).to.have.property('namespacePending');
      expect(actions).to.have.property('namespaceSuccess');
      expect(actions).to.have.property('namespaceFailure');
    });

    it('should export sagas', () => {
      const { sagas } = result;
      expect(sagas).to.have.property('makeNamespaceRequest');
      expect(sagas).to.have.property('watchForNamespaceRequest');
    });
  });

  describe('flattened exports', () => {
    let result;

    beforeEach(() => {
      result = requestWrapper(request, constantCreator, { flattenExports: true });
    });

    it('should export constants', () => {
      expect(result).to.not.have.property('constants');
      expect(result).to.have.property('REQUEST');
      expect(result).to.have.property('PENDING');
      expect(result).to.have.property('SUCCESS');
      expect(result).to.have.property('FAILURE');
    });

    it('should export actions', () => {
      expect(result).to.not.have.property('actions');
      expect(result).to.have.property('request');
      expect(result).to.have.property('pending');
      expect(result).to.have.property('success');
      expect(result).to.have.property('failure');
    });

    it('should export sagas', () => {
      expect(result).to.not.have.property('sagas');
      expect(result).to.have.property('makeRequest');
      expect(result).to.have.property('watchForRequest');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
const request = require('request');
const core = require('./../core/core.js');

/**
 * CREDENTIALS
 **/
const VALIDATION_TOKEN = process.env.FACEBOOK_VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.FACEBOOK_PAGE_ACCESS_TOKEN;

/*
* Fonction appelé par Facbook pour checker le serveur
*/
function webhook(req, res) {
    return req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN;
}

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(req, res) {
    var data = req.body;
    if (data.object === 'page') {
        //Message reçu de Facebook
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    console.log("Event received : ", JSON.stringify(event));
                    extractMessage(event);
                }
            });
        });
    } else {
        //Pour tester via CURL
        extractMessage(req.body);
    }
}
/*
* Fonction qui permet de traiter un message reçu
*/
function extractMessage(event) {
    console.log(JSON.stringify(event));
    var senderID = event.sender.id;
    request({
        uri: 'https://graph.facebook.com/' + senderID,
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'GET'
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Received message from Facebook for user %d at %d with message:",
            senderID, timeOfMessage);
            var recipientID = event.recipient.id;
            var timeOfMessage = event.timestamp;
            var message = event.message;
            console.log(JSON.stringify(message));

            var messageText = message.text;
            var messageAttachments = message.attachments;

            var message = {
                channel: "Facebook",
                senderID: senderID,
                timestamp: timeOfMessage,
                text: messageText,
                first_name: body.first_name,
                last_name: body.last_name
            };
            /*
            *   Coordonnées
            */
            if(messageAttachments != undefined && messageAttachments.payload != undefined && messageAttachments.payload.coordinates != undefined) {
                message["location"] = coordinates;
            }

            core.receivedMessage(message);
        } else {
            console.error("Unable to get name of user.");
            console.error(response);
            console.error(error);
        }
    });
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text,
                quick_replies: []
            }
        };
        for(var i=0;i<message.choices.length;i++) {
            var quickreply = {
                content_type: "text",
                title: message.choices[i],
                payload: message.choices[i]
            };
            messageData.message.quick_replies.push(quickreply);
        }
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui appel l'API messages de Facebook
*/
function callSendAPI(messageData) {
    console.log("Messages sended via API : ", JSON.stringify(messageData));
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'POST',
        json: messageData
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

exports.webhook = webhook
exports.receivedMessage = receivedMessage
exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<commit_msg>Accept JSON dans l'API Facebook<commit_after>'use strict';
const request = require('request');
const core = require('./../core/core.js');

/**
 * CREDENTIALS
 **/
const VALIDATION_TOKEN = process.env.FACEBOOK_VALIDATION_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.FACEBOOK_PAGE_ACCESS_TOKEN;

/*
* Fonction appelé par Facbook pour checker le serveur
*/
function webhook(req, res) {
    return req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN;
}

/*
* Fonction appelé par les routes lors de la reception d'un message
*/
function receivedMessage(req, res) {
    var data = req.body;
    if (data.object === 'page') {
        //Message reçu de Facebook
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    console.log("Event received : ", JSON.stringify(event));
                    extractMessage(event);
                }
            });
        });
    } else {
        //Pour tester via CURL
        extractMessage(req.body);
    }
}
/*
* Fonction qui permet de traiter un message reçu
*/
function extractMessage(event) {
    console.log(JSON.stringify(event));
    var senderID = event.sender.id;
    request({
        uri: 'https://graph.facebook.com/' + senderID,
        qs: { access_token: PAGE_ACCESS_TOKEN },
        headers: { 'Content-Type': 'application/json' },
        method: 'GET'
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Received message from Facebook for user %d at %d with message:",
            senderID, timeOfMessage);
            var recipientID = event.recipient.id;
            var timeOfMessage = event.timestamp;
            var message = event.message;
            console.log(JSON.stringify(message));

            var messageText = message.text;
            var messageAttachments = message.attachments;

            var message = {
                channel: "Facebook",
                senderID: senderID,
                timestamp: timeOfMessage,
                text: messageText,
                first_name: body.first_name,
                last_name: body.last_name
            };
            /*
            *   Coordonnées
            */
            if(messageAttachments != undefined && messageAttachments.payload != undefined && messageAttachments.payload.coordinates != undefined) {
                message["location"] = coordinates;
            }

            core.receivedMessage(message);
        } else {
            console.error("Unable to get name of user.");
            console.error(response);
            console.error(error);
        }
    });
}

/*
* Fonction appelé par le core pour envoyer un message sur la channel Facebook
*/
function sendMessage(message) {
    switch(message.type) {
        case "text":
            sendTextMessage(message);
        break;
        case "quickreply":
            sendQuickReplyMessage(message);
        break;
    }
}

/*
* Fonction appelé par le core pour envoyer des messages sur la channel Facebook
*/
function sendMessages(messages) {
    for(var i=0;i<messages.length;i++) {
        sendMessage(messages[i]);
    }
}

/*
* Fonction qui envoie un message de type text
*/
function sendTextMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message de type quickreply
*/
function sendQuickReplyMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                text: message.text,
                quick_replies: []
            }
        };
        for(var i=0;i<message.choices.length;i++) {
            var quickreply = {
                content_type: "text",
                title: message.choices[i],
                payload: message.choices[i]
            };
            messageData.message.quick_replies.push(quickreply);
        }
        callSendAPI(messageData);
    }
}

/*
* Fonction qui envoie un message audio/file/image/video
*/
function sendFileMessage(message) {
    console.log("Messages sended : ", JSON.stringify(message));
    if(message.senderID != undefined && message.text != undefined) {
        var messageData = {
            recipient: {
                id: message.senderID
            },
            message: {
                attachment:{
                    type: message.type,
                    payload: {
                        url: message.text
                    }
                }
            }
        };
        callSendAPI(messageData);
    }
}

/*
* Fonction qui appel l'API messages de Facebook
*/
function callSendAPI(messageData) {
    console.log("Messages sended via API : ", JSON.stringify(messageData));
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: PAGE_ACCESS_TOKEN },
        method: 'POST',
        json: messageData
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

exports.webhook = webhook
exports.receivedMessage = receivedMessage
exports.sendMessage = sendMessage
exports.sendMessages = sendMessages<|endoftext|>


<commit_before>(function(angular, undefined) {
  var app = angular.module('ct.ui.router.extras.future', [ 'ct.ui.router.extras.core' ]);

  _futureStateProvider.$inject = [ '$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', 'uirextras_coreProvider' ];
  function _futureStateProvider($stateProvider, $urlRouterProvider, $urlMatcherFactory, uirextras_coreProvider) {
    var core = uirextras_coreProvider;
    var internalStates = core.internalStates;
    var stateFactories = {}, futureStates = {};
    var lazyloadInProgress = false, resolveFunctions = [], initPromise, initDone = false;
    var provider = this;

    // This function registers a promiseFn, to be resolved before the url/state matching code
    // will reject a route.  The promiseFn is injected/executed using the runtime $injector.
    // The function should return a promise.
    // When all registered promises are resolved, then the route is re-sync'ed.

    // Example: function($http) {
    //  return $http.get('//server.com/api/DynamicFutureStates').then(function(data) {
    //    angular.forEach(data.futureStates, function(fstate) { $futureStateProvider.futureState(fstate); });
    //  };
    // }
    this.addResolve = function (promiseFn) {
      resolveFunctions.push(promiseFn);
    };

    // Register a state factory function for a particular future-state type.  This factory, given a future-state object,
    // should create a ui-router state.
    // The factory function is injected/executed using the runtime $injector.  The future-state is injected as 'futureState'.

    // Example:
    //    $futureStateProvider.stateFactory('test', function(futureState) {
    //      return {
    //        name: futureState.stateName,
    //        url: futureState.urlFragment,
    //        template: '
Future State Template
',
    //        controller: function() {
    //          console.log("Entered state " + futureState.stateName);
    //        }
    //      }
    //    });
    this.stateFactory = function (futureStateType, factory) {
      stateFactories[futureStateType] = factory;
    };

    this.futureState = function (futureState) {
      if (futureState.stateName)  // backwards compat for now
        futureState.name = futureState.stateName;
      if (futureState.urlPrefix)  // backwards compat for now
        futureState.url = "^" + futureState.urlPrefix;

      futureStates[futureState.name] = futureState;
      var parentMatcher,  parentName = futureState.name.split(/\./).slice(0, -1).join("."),
        realParent = findState(futureState.parent || parentName);
      if (realParent) {
        parentMatcher = realParent.url || realParent.navigable && realParent.navigable.url;
      } else if (parentName === "") {
        parentMatcher = $urlMatcherFactory.compile("");
      } else {
        var futureParent = findState((futureState.parent || parentName), true);
        if (!futureParent) throw new Error("Couldn't determine parent state of future state. FutureState:" + angular.toJson(futureState));
        var pattern = futureParent.urlMatcher.source.replace(/\*rest$/, "");
        parentMatcher = $urlMatcherFactory.compile(pattern);
        futureState.parentFutureState = futureParent;
      }
      if (futureState.url) {
        futureState.urlMatcher = futureState.url.charAt(0) === "^" ?
          $urlMatcherFactory.compile(futureState.url.substring(1) + "*rest") :
          parentMatcher.concat(futureState.url + "*rest");
      }
    };

    this.get = function () {
      return angular.extend({}, futureStates);
    };

    function findState(stateOrName, findFutureState) {
      var statename = angular.isObject(stateOrName) ? stateOrName.name : stateOrName;
      return !findFutureState ? internalStates[statename] : futureStates[statename];
    }

    /* options is an object with at least a name or url attribute */
    function findFutureState($state, options) {
      if (options.name) {
        var nameComponents = options.name.split(/\./);
        if (options.name.charAt(0) === '.')
          nameComponents[0] = $state.current.name;
        while (nameComponents.length) {
          var stateName = nameComponents.join(".");
          if ($state.get(stateName, { relative: $state.current }))
            return null; // State is already defined; nothing to do
          if (futureStates[stateName])
            return futureStates[stateName];
          nameComponents.pop();
        }
      }

      if (options.url) {
        var matches = [];
        for(var future in futureStates) {
          var matcher = futureStates[future].urlMatcher;
          if (matcher && matcher.exec(options.url)) {
            matches.push(futureStates[future]);
          }
        }
        // Find most specific by ignoring matching parents from matches
        var copy = matches.slice(0);
        for (var i = matches.length - 1; i >= 0; i--) {
          for (var j = 0; j < copy.length; j++) {
            if (matches[i] === copy[j].parentFutureState) matches.splice(i, 1);
          }
        }
        return matches[0];
      }
    }

    function lazyLoadState($injector, futureState) {
      lazyloadInProgress = true;
      var $q = $injector.get("$q");
      if (!futureState) {
        var deferred = $q.defer();
        deferred.reject("No lazyState passed in " + futureState);
        return deferred.promise;
      }

      var promise = $q.when([]), parentFuture = futureState.parentFutureState;
      if (parentFuture && futureStates[parentFuture.name]) {
        promise = lazyLoadState($injector, futureStates[parentFuture.name]);
      }

      var type = futureState.type;
      var factory = stateFactories[type];
      if (!factory) throw Error("No state factory for futureState.type: " + (futureState && futureState.type));
      return promise
        .then(function(array) {
          var injectorPromise = $injector.invoke(factory, factory, { futureState: futureState });
          return injectorPromise.then(function(fullState) {
            if (fullState) { array.push(fullState); } // Pass a chain of realized states back
            return array;
          });
        })
        ["finally"](function() { // IE8 hack
        delete(futureStates[futureState.name]);
      });
    }

    var otherwiseFunc = [ '$log', '$location',
      function otherwiseFunc($log, $location) {
        $log.debug("Unable to map " + $location.path());
      }];

    function futureState_otherwise($injector, $location) {
      var resyncing = false;

      var lazyLoadMissingState =
        ['$rootScope', '$urlRouter', '$state',
          function lazyLoadMissingState($rootScope, $urlRouter, $state) {
            function resync() {
              resyncing = true; $urlRouter.sync(); resyncing = false;
            }
            if (!initDone) {
              // Asynchronously load state definitions, then resync URL
              initPromise().then(resync);
              initDone = true;
              return;
            }

            var futureState = findFutureState($state, { url: $location.path() });
            if (!futureState) {
              return $injector.invoke(otherwiseFunc);
            }

            // Config loaded.  Asynchronously lazy-load state definition from URL fragment, if mapped.
            lazyLoadState($injector, futureState).then(function lazyLoadedStateCallback(states) {
              states.forEach(function (state) {
                if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
                  $stateProvider.state(state);
              });
              lazyloadInProgress = false;
              resync();
            }, function lazyLoadStateAborted() {
              lazyloadInProgress = false;
              resync();
            });
          }];
      if (lazyloadInProgress) return;

      var nextFn = resyncing ? otherwiseFunc : lazyLoadMissingState;
      return $injector.invoke(nextFn);
    }

    $urlRouterProvider.otherwise(futureState_otherwise);

    $urlRouterProvider.otherwise = function(rule) {
      if (angular.isString(rule)) {
        var redirect = rule;
        rule = function () { return redirect; };
      }
      else if (!angular.isFunction(rule)) throw new Error("'rule' must be a function");
      otherwiseFunc = ['$injector', '$location', rule];
      return $urlRouterProvider;
    };

    var serviceObject = {
      getResolvePromise: function () {
        return initPromise();
      }
    };

    // Used in .run() block to init
    this.$get = [ '$injector', '$state', '$q', '$rootScope', '$urlRouter', '$timeout', '$log',
      function futureStateProvider_get($injector, $state, $q, $rootScope, $urlRouter, $timeout, $log) {
        function init() {
          $rootScope.$on("$stateNotFound", function futureState_notFound(event, unfoundState, fromState, fromParams) {
            if (lazyloadInProgress) return;
            $log.debug("event, unfoundState, fromState, fromParams", event, unfoundState, fromState, fromParams);

            var futureState = findFutureState($state, { name: unfoundState.to });
            if (!futureState) return;

            event.preventDefault();
            var promise = lazyLoadState($injector, futureState);
            promise.then(function (states) {
              states.forEach(function (state) {
                if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
                  $stateProvider.state(state);
              });
              $state.go(unfoundState.to, unfoundState.toParams);
              lazyloadInProgress = false;
            }, function (error) {
              console.log("failed to lazy load state ", error);
              $state.go(fromState, fromParams);
              lazyloadInProgress = false;
            });
          });

          // Do this better.  Want to load remote config once, before everything else
          if (!initPromise) {
            var promises = [];
            angular.forEach(resolveFunctions, function (promiseFn) {
              promises.push($injector.invoke(promiseFn));
            });
            initPromise = function () {
              return $q.all(promises);
            };
          }

          // TODO: analyze this. I'm calling $urlRouter.sync() in two places for retry-initial-transition.
          // TODO: I should only need to do this once.  Pick the better place and remove the extra resync.
          initPromise().then(function retryInitialState() {
            $timeout(function () {
              if ($state.transition) {
                $state.transition.then($urlRouter.sync, $urlRouter.sync);
              } else {
                $urlRouter.sync();
              }
            });
          });
        }

        init();

        serviceObject.state = $stateProvider.state;
        serviceObject.futureState = provider.futureState;
        serviceObject.get = provider.get;

        return serviceObject;
      }
    ];
  }

  app.provider('$futureState', _futureStateProvider);

  var statesAddedQueue = {
    state: function(state) {
      if (statesAddedQueue.$rootScope)
        statesAddedQueue.$rootScope.$broadcast("$stateAdded", state);
    },
    itsNowRuntimeOhWhatAHappyDay: function($rootScope) {
      statesAddedQueue.$rootScope = $rootScope;
    },
    $rootScope: undefined
  };

  app.config([ '$stateProvider', function($stateProvider) {
    // decorate $stateProvider.state so we can broadcast when a real state was added
    var realStateFn = $stateProvider.state;
    $stateProvider.state = function state_announce() {
      var val = realStateFn.apply($stateProvider, arguments);

      var state = angular.isObject(arguments[0]) ? arguments[0] : arguments[1];
      statesAddedQueue.state(state);
      return val;
    };
  }]);

  // inject $futureState so the service gets initialized via $get();
  app.run(['$futureState', function ($futureState, $rootScope) {
    statesAddedQueue.itsNowRuntimeOhWhatAHappyDay($rootScope);
  } ]);

})(angular);
<commit_msg>fix(future): Fixed double-urlRouter.sync() because of future state retry Closes #138<commit_after>(function(angular, undefined) {
  var app = angular.module('ct.ui.router.extras.future', [ 'ct.ui.router.extras.core' ]);

  _futureStateProvider.$inject = [ '$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', 'uirextras_coreProvider' ];
  function _futureStateProvider($stateProvider, $urlRouterProvider, $urlMatcherFactory, uirextras_coreProvider) {
    var core = uirextras_coreProvider;
    var internalStates = core.internalStates;
    var stateFactories = {}, futureStates = {};
    var lazyloadInProgress = false, resolveFunctions = [], initPromise, initDone = false;
    var provider = this;

    // This function registers a promiseFn, to be resolved before the url/state matching code
    // will reject a route.  The promiseFn is injected/executed using the runtime $injector.
    // The function should return a promise.
    // When all registered promises are resolved, then the route is re-sync'ed.

    // Example: function($http) {
    //  return $http.get('//server.com/api/DynamicFutureStates').then(function(data) {
    //    angular.forEach(data.futureStates, function(fstate) { $futureStateProvider.futureState(fstate); });
    //  };
    // }
    this.addResolve = function (promiseFn) {
      resolveFunctions.push(promiseFn);
    };

    // Register a state factory function for a particular future-state type.  This factory, given a future-state object,
    // should create a ui-router state.
    // The factory function is injected/executed using the runtime $injector.  The future-state is injected as 'futureState'.

    // Example:
    //    $futureStateProvider.stateFactory('test', function(futureState) {
    //      return {
    //        name: futureState.stateName,
    //        url: futureState.urlFragment,
    //        template: '
Future State Template
',
    //        controller: function() {
    //          console.log("Entered state " + futureState.stateName);
    //        }
    //      }
    //    });
    this.stateFactory = function (futureStateType, factory) {
      stateFactories[futureStateType] = factory;
    };

    this.futureState = function (futureState) {
      if (futureState.stateName)  // backwards compat for now
        futureState.name = futureState.stateName;
      if (futureState.urlPrefix)  // backwards compat for now
        futureState.url = "^" + futureState.urlPrefix;

      futureStates[futureState.name] = futureState;
      var parentMatcher,  parentName = futureState.name.split(/\./).slice(0, -1).join("."),
        realParent = findState(futureState.parent || parentName);
      if (realParent) {
        parentMatcher = realParent.url || realParent.navigable && realParent.navigable.url;
      } else if (parentName === "") {
        parentMatcher = $urlMatcherFactory.compile("");
      } else {
        var futureParent = findState((futureState.parent || parentName), true);
        if (!futureParent) throw new Error("Couldn't determine parent state of future state. FutureState:" + angular.toJson(futureState));
        var pattern = futureParent.urlMatcher.source.replace(/\*rest$/, "");
        parentMatcher = $urlMatcherFactory.compile(pattern);
        futureState.parentFutureState = futureParent;
      }
      if (futureState.url) {
        futureState.urlMatcher = futureState.url.charAt(0) === "^" ?
          $urlMatcherFactory.compile(futureState.url.substring(1) + "*rest") :
          parentMatcher.concat(futureState.url + "*rest");
      }
    };

    this.get = function () {
      return angular.extend({}, futureStates);
    };

    function findState(stateOrName, findFutureState) {
      var statename = angular.isObject(stateOrName) ? stateOrName.name : stateOrName;
      return !findFutureState ? internalStates[statename] : futureStates[statename];
    }

    /* options is an object with at least a name or url attribute */
    function findFutureState($state, options) {
      if (options.name) {
        var nameComponents = options.name.split(/\./);
        if (options.name.charAt(0) === '.')
          nameComponents[0] = $state.current.name;
        while (nameComponents.length) {
          var stateName = nameComponents.join(".");
          if ($state.get(stateName, { relative: $state.current }))
            return null; // State is already defined; nothing to do
          if (futureStates[stateName])
            return futureStates[stateName];
          nameComponents.pop();
        }
      }

      if (options.url) {
        var matches = [];
        for(var future in futureStates) {
          var matcher = futureStates[future].urlMatcher;
          if (matcher && matcher.exec(options.url)) {
            matches.push(futureStates[future]);
          }
        }
        // Find most specific by ignoring matching parents from matches
        var copy = matches.slice(0);
        for (var i = matches.length - 1; i >= 0; i--) {
          for (var j = 0; j < copy.length; j++) {
            if (matches[i] === copy[j].parentFutureState) matches.splice(i, 1);
          }
        }
        return matches[0];
      }
    }

    function lazyLoadState($injector, futureState) {
      lazyloadInProgress = true;
      var $q = $injector.get("$q");
      if (!futureState) {
        var deferred = $q.defer();
        deferred.reject("No lazyState passed in " + futureState);
        return deferred.promise;
      }

      var promise = $q.when([]), parentFuture = futureState.parentFutureState;
      if (parentFuture && futureStates[parentFuture.name]) {
        promise = lazyLoadState($injector, futureStates[parentFuture.name]);
      }

      var type = futureState.type;
      var factory = stateFactories[type];
      if (!factory) throw Error("No state factory for futureState.type: " + (futureState && futureState.type));
      return promise
        .then(function(array) {
          var injectorPromise = $injector.invoke(factory, factory, { futureState: futureState });
          return injectorPromise.then(function(fullState) {
            if (fullState) { array.push(fullState); } // Pass a chain of realized states back
            return array;
          });
        })
        ["finally"](function() { // IE8 hack
        delete(futureStates[futureState.name]);
      });
    }

    var otherwiseFunc = [ '$log', '$location',
      function otherwiseFunc($log, $location) {
        $log.debug("Unable to map " + $location.path());
      }];

    function futureState_otherwise($injector, $location) {
      var resyncing = false;

      var lazyLoadMissingState =
        ['$rootScope', '$urlRouter', '$state',
          function lazyLoadMissingState($rootScope, $urlRouter, $state) {
            function resync() {
              resyncing = true; $urlRouter.sync(); resyncing = false;
            }
            if (!initDone) {
              // Asynchronously load state definitions, then resync URL
              initPromise().then(resync);
              initDone = true;
              return;
            }

            var futureState = findFutureState($state, { url: $location.path() });
            if (!futureState) {
              return $injector.invoke(otherwiseFunc);
            }

            // Config loaded.  Asynchronously lazy-load state definition from URL fragment, if mapped.
            lazyLoadState($injector, futureState).then(function lazyLoadedStateCallback(states) {
              states.forEach(function (state) {
                if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
                  $stateProvider.state(state);
              });
              lazyloadInProgress = false;
              resync();
            }, function lazyLoadStateAborted() {
              lazyloadInProgress = false;
              resync();
            });
          }];
      if (lazyloadInProgress) return;

      var nextFn = resyncing ? otherwiseFunc : lazyLoadMissingState;
      return $injector.invoke(nextFn);
    }

    $urlRouterProvider.otherwise(futureState_otherwise);

    $urlRouterProvider.otherwise = function(rule) {
      if (angular.isString(rule)) {
        var redirect = rule;
        rule = function () { return redirect; };
      }
      else if (!angular.isFunction(rule)) throw new Error("'rule' must be a function");
      otherwiseFunc = ['$injector', '$location', rule];
      return $urlRouterProvider;
    };

    var serviceObject = {
      getResolvePromise: function () {
        return initPromise();
      }
    };

    // Used in .run() block to init
    this.$get = [ '$injector', '$state', '$q', '$rootScope', '$urlRouter', '$timeout', '$log',
      function futureStateProvider_get($injector, $state, $q, $rootScope, $urlRouter, $timeout, $log) {
        function init() {
          $rootScope.$on("$stateNotFound", function futureState_notFound(event, unfoundState, fromState, fromParams) {
            if (lazyloadInProgress) return;
            $log.debug("event, unfoundState, fromState, fromParams", event, unfoundState, fromState, fromParams);

            var futureState = findFutureState($state, { name: unfoundState.to });
            if (!futureState) return;

            event.preventDefault();
            var promise = lazyLoadState($injector, futureState);
            promise.then(function (states) {
              states.forEach(function (state) {
                if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
                  $stateProvider.state(state);
              });
              $state.go(unfoundState.to, unfoundState.toParams);
              lazyloadInProgress = false;
            }, function (error) {
              console.log("failed to lazy load state ", error);
              $state.go(fromState, fromParams);
              lazyloadInProgress = false;
            });
          });

          // Do this better.  Want to load remote config once, before everything else
          if (!initPromise) {
            var promises = [];
            angular.forEach(resolveFunctions, function (promiseFn) {
              promises.push($injector.invoke(promiseFn));
            });
            initPromise = function () {
              return $q.all(promises);
            };
          }

          // TODO: analyze this. I'm calling $urlRouter.sync() in two places for retry-initial-transition.
          // TODO: I should only need to do this once.  Pick the better place and remove the extra resync.
          initPromise().then(function retryInitialState() {
            $timeout(function () {
              if ($state.transition) {
                $state.transition.then(retryInitialState, retryInitialState);
              } else {
                $urlRouter.sync();
              }
            });
          });
        }

        init();

        serviceObject.state = $stateProvider.state;
        serviceObject.futureState = provider.futureState;
        serviceObject.get = provider.get;

        return serviceObject;
      }
    ];
  }

  app.provider('$futureState', _futureStateProvider);

  var statesAddedQueue = {
    state: function(state) {
      if (statesAddedQueue.$rootScope)
        statesAddedQueue.$rootScope.$broadcast("$stateAdded", state);
    },
    itsNowRuntimeOhWhatAHappyDay: function($rootScope) {
      statesAddedQueue.$rootScope = $rootScope;
    },
    $rootScope: undefined
  };

  app.config([ '$stateProvider', function($stateProvider) {
    // decorate $stateProvider.state so we can broadcast when a real state was added
    var realStateFn = $stateProvider.state;
    $stateProvider.state = function state_announce() {
      var val = realStateFn.apply($stateProvider, arguments);

      var state = angular.isObject(arguments[0]) ? arguments[0] : arguments[1];
      statesAddedQueue.state(state);
      return val;
    };
  }]);

  // inject $futureState so the service gets initialized via $get();
  app.run(['$futureState', function ($futureState, $rootScope) {
    statesAddedQueue.itsNowRuntimeOhWhatAHappyDay($rootScope);
  } ]);

})(angular);
<|endoftext|>


<commit_before>// SET UNIT NUMBERS HERE
var builders_wanted = 2;
var harvesters_wanted = 2;
var haulers_wanted = 6;
var healers_wanted = 0;
var upgraders_wanted = 3;

// BUILDERS
module.exports.builders = function() {
	var builder_count = _.filter(Game.creeps, (creep) =>
												(creep.memory.role == 'builder'));
	if (builder_count.length < builders_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'builder', harvesting: 'true' });

		console.log('Spawning new Builder: ' + newName);
	}
}

// HARVESTERS
module.exports.harvesters = function() {
	var harvester_count = _.filter(Game.creeps, (creep) =>
													(creep.memory.role == 'harvester'));
	if (harvester_count.length < harvesters_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE],
			undefined,
			{ role: 'harvester', harvesting: 'true' });

		console.log('Spawning new Harvester: ' + newName);
	}
}

// HAULERS
module.exports.haulers = function() {
	var hauler_count = _.filter(Game.creeps, (creep) =>
											 (creep.memory.role == 'hauler'));
	if (hauler_count.length < haulers_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'hauler', harvesting: 'true' });

		console.log('Spawning new Hauler: ' + newName);
	}
}

// HEALERS
module.exports.healers = function() {
	var healer_count = _.filter(Game.creeps, (creep) =>
											 (creep.memory.role == 'healer'));
	if (healer_count.length < healers_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'healer', harvesting: 'true' });

		console.log('Spawning new Healer: ' + newName);
	}
}

// UPGRADERS
module.exports.upgraders = function() {
	var upgrader_count = _.filter(Game.creeps, (creep) =>
												 (creep.memory.role == 'upgrader'));
	if (upgrader_count.length < upgraders_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'upgrader', harvesting: 'true' });

		console.log('Spawning new Upgrader: ' + newName);
	}
}<commit_msg>Minor changes<commit_after>// SET UNIT NUMBERS HERE
var builders_wanted = 2;
var harvesters_wanted = 2;
var haulers_wanted = 4;
var healers_wanted = 0;
var upgraders_wanted = 3;

// BUILDERS
module.exports.builders = function() {
	var builder_count = _.filter(Game.creeps, (creep) =>
												(creep.memory.role == 'builder'));
	if (builder_count.length < builders_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'builder', harvesting: 'true' });

		console.log('Spawning new Builder: ' + newName);
	}
}

// HARVESTERS
module.exports.harvesters = function() {
	var harvester_count = _.filter(Game.creeps, (creep) =>
													(creep.memory.role == 'harvester'));
	if (harvester_count.length < harvesters_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE],
			undefined,
			{ role: 'harvester', harvesting: 'true' });

		console.log('Spawning new Harvester: ' + newName);
	}
}

// HAULERS
module.exports.haulers = function() {
	var hauler_count = _.filter(Game.creeps, (creep) =>
											 (creep.memory.role == 'hauler'));
	if (hauler_count.length < haulers_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'hauler', harvesting: 'true' });

		console.log('Spawning new Hauler: ' + newName);
	}
}

// HEALERS
module.exports.healers = function() {
	var healer_count = _.filter(Game.creeps, (creep) =>
											 (creep.memory.role == 'healer'));
	if (healer_count.length < healers_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'healer', harvesting: 'true' });

		console.log('Spawning new Healer: ' + newName);
	}
}

// UPGRADERS
module.exports.upgraders = function() {
	var upgrader_count = _.filter(Game.creeps, (creep) =>
												 (creep.memory.role == 'upgrader'));
	if (upgrader_count.length < upgraders_wanted) {
		var newName = Game.spawns['Spawn1'].createCreep(
			[WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE],
			undefined,
			{ role: 'upgrader', harvesting: 'true' });

		console.log('Spawning new Upgrader: ' + newName);
	}
}<|endoftext|>


<commit_before>/* @flow */
/**
 * @jsx React.DOM
 */
'use strict';

var React                   = require('react');

var CheckBoxEditor = React.createClass({

  PropTypes : {
    value : React.PropTypes.bool.isRequired,
    rowIdx : React.PropTypes.number.isRequired
  },

  render(): ?ReactElement{
    return (<input className="react-grid-CheckBox" type="checkbox" checked={this.props.value} onChange={this.handleChange} />);
  },

  handleChange(e: Event){
    this.props.column.onRowSelect(this.props.rowIdx)
  },

  shouldComponentUpdate(nextProps: any, nextState: any): boolean{
    return this.props.value != nextProps.value;
  }

});

module.exports = CheckBoxEditor;
<commit_msg>replace onChange with onClick<commit_after>/* @flow */
/**
 * @jsx React.DOM
 */
'use strict';

var React                   = require('react');

var CheckBoxEditor = React.createClass({

  PropTypes : {
    value : React.PropTypes.bool.isRequired,
    rowIdx : React.PropTypes.number.isRequired
  },

  render(): ?ReactElement{
    var checked = this.props.value != null ? this.props.value : false;
    return (<input className="react-grid-CheckBox" type="checkbox" checked={checked} onClick={this.handleChange} />);
  },

  handleChange(e: Event){
    e.stopPropagation();
    this.props.column.onRowSelect(this.props.rowIdx)
  }
});

module.exports = CheckBoxEditor;
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var gbk2utf8 = require("./gbk2utf8");
var map = {};
var reg_set = /^\s*@?\s*(?:set|setx)\s+(.*?)\s*=\s*(['"`]?)([\s\S]*)\2$/im
var reg_call = /^\s*@?\s*call\s+(["]?)(.*?)\1([\s\S]*)$/i;
var reg_for = /^\s*@?\s*for\s+([%\w]+)\s+in\s*\((.*?)\)\s*do\s+(.*?)$/i
var env = process.env;
var call = function (file, args = []) {
    if (!fs.existsSync(file)) {
        var _file;
        var _path = path.parse(file);
        var _dir = _path.dir;
        var _name = _path.name;
        if (!fs.existsSync(_dir) || !fs.statSync(_dir).isDirectory()) {
            return;
        }
        fs.readdirSync(_dir).forEach(function (name) {
            if (!_file) {
                if (name.startsWith(_name) && /\.(bat|cmd)$/i.test(name)) {
                    _file = path.join(_dir, name);
                }
            }
        });
        if (!_file) {
            return;
        }
        file = _file;
    }
    gbk2utf8(
            fs.readFileSync(file)
        )
        .replace(/%(\d)/g, function (match, i) {
            return args[i];
        })
        .replace(/%~dp\d/ig, path.join(path.resolve(path.parse(file).dir), "./"))
        .trim()
        .split(/[\r\n]+\s*/g)
        .forEach(get);
};
var get = function (text) {
    match = text.match(reg_for)
    if (match) {
        var variable = match[1];
        var set = get(match[2]).split(/[,]/);
        var function_body = match[3];
        for (var cx = 0, dx = set.length; cx < dx; cx++) {
            var executer = function_body.replace(new RegExp(variable, "ig"), set[cx]);
            get(executer);
        }
    }
    text = text
        .replace(/%(.*?)%/ig, function (match, env_name) {
            if (!env_name) return "%";
            return env[env_name];
        })
    var match = text.match(reg_set);
    if (match) {
        var k = match[1],
            v = match[3];
        return env[k] = v;
    }
    var match = text.match(reg_call);
    if (match) {
        call(match[2], match[3].split(/\s+/));
    }
    return text;
};
call("./_envs/setup.bat");
if (!env.PAGE) env.PAGE = env.APP;
var cache = {};
module.exports = function (appname) {
    appname = appname.replace(/^[\/\\]*(.*?)[\/\\]*$/g, "$1");
    if (cache[appname]) return cache[appname];
    else env = {};
    call("./_envs/app=" + appname + ".bat");
    cache[appname] = env;
    if (!env.PAGE) env.PAGE = appname;
    return env;
};
process.env.IN_DEBUG_MODE = process.argv.findIndex(e => /--debug-brk=/i.test(e)) > 0 ? 1 : 0<commit_msg>支持if语法<commit_after>var fs = require("fs");
var path = require("path");
var gbk2utf8 = require("./gbk2utf8");
var map = {};
var reg_set = /^\s*@?\s*(?:set|setx)\s+(.*?)\s*=\s*(['"`]?)([\s\S]*)\2$/im
var reg_call = /^\s*@?\s*call\s+(["]?)(.*?)\1([\s\S]*)$/i;
var reg_for = /^\s*@?\s*for\s+([%\w]+)\s+in\s*\((.*?)\)\s*do\s+(.*?)$/i;
var reg_if = /^\s*@?\s*if\s+(\/i\s+)?(not\s+)?(?:(cmdextversion|errorlevel)\s+(.+?)|(.+?)\s*(==|equ|neq|lss|leq|gtr|geq)\s*(.+?)|exist\s+(.+?)|defined\s+(.+?))\s+([\s\S]*?)$/i;
var if_conditions = {
    "==": (a, b) => a == b,
    "equ": (a, b) => a == b,
    "neq": (a, b) => a != b,
    "lss": (a, b) => a < b,
    "leq": (a, b) => a <= b,
    "gtr": (a, b) => a > b,
    "geq": (a, b) => a >= b
};
var env = process.env;
var call = function (file, args = []) {
    if (!fs.existsSync(file)) {
        var _file;
        var _path = path.parse(file);
        var _dir = _path.dir;
        var _name = _path.name;
        if (!fs.existsSync(_dir) || !fs.statSync(_dir).isDirectory()) {
            return;
        }
        fs.readdirSync(_dir).forEach(function (name) {
            if (!_file) {
                if (name.startsWith(_name) && /\.(bat|cmd)$/i.test(name)) {
                    _file = path.join(_dir, name);
                }
            }
        });
        if (!_file) {
            return;
        }
        file = _file;
    }
    gbk2utf8(
            fs.readFileSync(file)
        )
        .replace(/%(\d)/g, function (match, i) {
            return args[i];
        })
        .replace(/%~dp\d/ig, path.join(path.resolve(path.parse(file).dir), "./"))
        .trim()
        .split(/[\r\n]+\s*/g)
        .forEach(get);
};
var get = function (text) {
    match = text.match(reg_for)
    if (match) {
        var variable = match[1];
        var set = get(match[2]).split(/[,]/);
        var function_body = match[3];
        for (var cx = 0, dx = set.length; cx < dx; cx++) {
            var executer = function_body.replace(new RegExp(variable, "ig"), set[cx]);
            get(executer);
        }
    }
    text = text
        .replace(/%(.*?)%/ig, function (match, env_name) {
            if (!env_name) return "%";
            return env[env_name];
        });
    var match = text.match(reg_if);
    if (match) {
        var [matched_text, ignorecase, not, label, level, condition_left, condition_symbol, condition_right, exist, defined, command] = match;
        if (!!not ^ (
                level && env[label] == level ||
                condition_left && if_conditions[condition_symbol.toLowerCase()](
                    ignorecase ? condition_left.toUpperCase() : condition_left,
                    ignorecase ? condition_right.toUpperCase() : condition_right
                ) ||
                exist && fs.existsSync(exist) ||
                defined && defined in env
            )) get(command);
    }
    var match = text.match(reg_set);
    if (match) {
        var k = match[1],
            v = match[3];
        if (v)
            return env[k] = v;
        else
            return delete env[k]
    }
    var match = text.match(reg_call);
    if (match) {
        call(match[2], match[3].split(/\s+/));
    }
    return text;
};
call("./_envs/setup.bat");
if (!env.PAGE) env.PAGE = env.APP;
var cache = {};
module.exports = function (appname) {
    appname = appname.replace(/^[\/\\]*(.*?)[\/\\]*$/g, "$1");
    if (cache[appname]) return cache[appname];
    else env = {};
    call("./_envs/app=" + appname + ".bat");
    cache[appname] = env;
    if (!env.PAGE) env.PAGE = appname;
    return env;
};
process.env.IN_DEBUG_MODE = process.argv.findIndex(e => /--debug-brk=/i.test(e)) > 0 ? 1 : 0<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('app')
        .service('tokenService', [
            '$rootScope',
            '$http',
            '$q',
            function($rootScope, $http, $q, $location) {

                // Uncomment as per usage
                //
                // before building to pushing to Beta Server
                // var serviceBase = '/api/public/';
                //
                // before building to pushing to Main Server
                // var serviceBase = 'api/public/';
                //
                //
                // To test locally from main API
                 var serviceBase = 'https://campusbox.org/dist/api/public/';
                //
                // USE THIS AT MOST TIMES
                //
                // To test locally from BETA API
                //var serviceBase = 'http://beta.campusbox.org/api/public/';

                $rootScope.config = function() {
                    return {
                        headers: {
                            'Authorization': 'Bearer ' + $rootScope.token,
                        }
                    };
                };
                var obj = {};

                obj.get = function(q) {
                    return $http.get(serviceBase + q, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.post = function(q, object) {
                    return $http.post(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.put = function(q, object) {
                    return $http.put(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.patch = function(q, object) {
                    return $http.patch(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.delete = function(q) {
                    return $http.delete(serviceBase + q, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                return obj;
            }
        ]);
})();
<commit_msg>Fixed serviceBase url for beta server<commit_after>(function() {
    'use strict';

    angular.module('app')
        .service('tokenService', [
            '$rootScope',
            '$http',
            '$q',
            function($rootScope, $http, $q, $location) {

                // Uncomment as per usage
                //
                // before building to pushing to Beta Server
                // var serviceBase = '/dist/api/public/';
                //
                // before building to pushing to Main Server
                // var serviceBase = 'api/public/';
                //
                //
                // To test locally from main API
                 var serviceBase = 'https://campusbox.org/dist/api/public/';
                //
                // USE THIS AT MOST TIMES
                //
                // To test locally from BETA API
                // var serviceBase = 'http://beta.campusbox.org/dist/api/public/';

                $rootScope.config = function() {
                    return {
                        headers: {
                            'Authorization': 'Bearer ' + $rootScope.token,
                        }
                    };
                };
                var obj = {};

                obj.get = function(q) {
                    return $http.get(serviceBase + q, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.post = function(q, object) {
                    return $http.post(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.put = function(q, object) {
                    return $http.put(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.patch = function(q, object) {
                    return $http.patch(serviceBase + q, object, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                obj.delete = function(q) {
                    return $http.delete(serviceBase + q, $rootScope.config()).then(function(results) {
                        return results.data;
                    });
                };
                return obj;
            }
        ]);
})();
<|endoftext|>


<commit_before>const amiy = [
	"went to find people to flop on."
];

const bidoofftw = [
	"was forced onto bed by Kingdom of Tea."
];

const ctfrm = [
	"is better than Christos."
];

const christs = [
	"is everyone's favourite moderator."
];

const darklight1999 = [
	"returns back to darkness."
];

const kingdomoftea = [
	"retreats to get more tea."
];

const wolf = [
	"howls to the moon.",
	"runs off into a forest."
];

exports.commands = {
	dc: 'poof',
	disconnect: 'poof',
	disconnected: 'poof',
	cpoof: 'poof',
	poof: function (target, room, user) {
		if (Config.poofOff) return this.sendReply("Poof is currently disabled.");
		if (target && !this.can('broadcast')) return false;
		if (!this.canTalk(message)) return false;
		if (user.name === 'wolf') {
			var message = target || wolf[Math.floor(Math.random() * wolf.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Amiŧy') {
			var message = target || amiy[Math.floor(Math.random() * amiy.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Bidoof FTW') {
			var message = target || bidoofftw[Math.floor(Math.random() * bidoofftw.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Cаѕtfоrm') {
			var message = target || ctfrm[Math.floor(Math.random() * ctfrm.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Christοs') {
			var message = target || christs[Math.floor(Math.random() * christs.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Dark Light1999') {
			var message = target || darklight1999[Math.floor(Math.random() * darklight1999.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Kingdom of Tea') {
			var message = target || kingdomoftea[Math.floor(Math.random() * kingdomoftea.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else {
			user.leaveRoom(room);
		}
	},

	poofoff: 'nopoof',
	nopoof: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = true;
		return this.sendReply("Poof is now disabled.");
	},

	poofon: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = false;
		return this.sendReply("Poof is now enabled.");
	}
};
<commit_msg>Update poof.js<commit_after>const absol98sk = [
	"If you're a trainer, talk with Pokemon!!"
];

const amiy = [
	"went to find people to flop on.",
	"got swallowed whole by a Snorlax."
];

const bidoofftw = [
	"was forced onto bed by Kingdom of Tea."
];

const ctfrm = [
	"is better than Christos."
];

const christs = [
	"is everyone's favourite moderator."
];

const darklight1999 = [
	"returns back to darkness."
];

const hannumikkola = [
	"is stealing your food now."
];

const kingdomoftea = [
	"retreats to get more tea."
];

const wolf = [
	"howls to the moon.",
	"runs off into a forest."
];

exports.commands = {
	dc: 'poof',
	disconnect: 'poof',
	disconnected: 'poof',
	cpoof: 'poof',
	poof: function (target, room, user) {
		if (Config.poofOff) return this.sendReply("Poof is currently disabled.");
		if (target && !this.can('broadcast')) return false;
		if (!this.canTalk(message)) return false;
		if (user.name === 'wolf') {
			var message = target || wolf[Math.floor(Math.random() * wolf.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Absol98SK') {
			var message = target || absol98sk[Math.floor(Math.random() * absol98sk.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Amiŧy' || user.name === 'Kimisumi') {
			var message = target || amiy[Math.floor(Math.random() * amiy.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Bidoof FTW') {
			var message = target || bidoofftw[Math.floor(Math.random() * bidoofftw.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Cаѕtfоrm') {
			var message = target || ctfrm[Math.floor(Math.random() * ctfrm.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Christοs') {
			var message = target || christs[Math.floor(Math.random() * christs.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Dark Light1999') {
			var message = target || darklight1999[Math.floor(Math.random() * darklight1999.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Hannu Mikkola') {
			var message = target || hannumikkola[Math.floor(Math.random() * hannumikkola.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else if (user.name === 'Kingdom of Tea') {
			var message = target || kingdomoftea[Math.floor(Math.random() * kingdomoftea.length)];
			if (message.indexOf('{{user}}') < 0)
				message = '{{user}} ' + message;
			message = message.replace(/{{user}}/g, user.name);

			room.addRaw(Tools.escapeHTML(message));
			user.leaveRoom(room);
		} else {
			user.leaveRoom(room);
		}
	},

	poofoff: 'nopoof',
	nopoof: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = true;
		return this.sendReply("Poof is now disabled.");
	},

	poofon: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = false;
		return this.sendReply("Poof is now enabled.");
	}
};
<|endoftext|>


<commit_before>/**
* @class   AppFilesmanagerModel
* @extends GuiPanelModel
*/
var AppFilesmanagerModel = GuiPanelModel.extend(
{
    /**
    * Panel target id.
    *
    * @protected
    * @property target
    * @type     {String}
    * @default  'columnOne'
    */
    target: 'columnOne',

    /**
    * Panel position index.
    *
    * @protected
    * @property index
    * @type     {Integer}
    * @default  0
    */
    index: 0,

    /**
    * Model setup.
    *
    * Called by GuiModule, immediately after Module create().
    *
    * @method setup
    * @return {Mixed}
    */
    setup: function() {
        this.color('blue');
        this.icon('files-o');

        this.files = ko.observableArray();
    },

    /**
    * Called after template is rendered.
    *
    * @event afterRender
    * @param {Array}     elements
    * @param {GuiModule} self
    */
    loadFile: function(elements, self) {

    },

    /**
    * Called after template is rendered.
    *
    * @event afterRender
    * @param {Array}     elements
    * @param {GuiModule} self
    */
    afterRender: function(elements, self) {

    }
});
<commit_msg>use fileinput model<commit_after>/**
* @class   AppFilesmanagerModel
* @extends GuiPanelModel
*/
var AppFilesmanagerModel = GuiPanelModel.extend(
{
    /**
    * Panel target id.
    *
    * @protected
    * @property target
    * @type     {String}
    * @default  'columnOne'
    */
    target: 'columnOne',

    /**
    * Panel position index.
    *
    * @protected
    * @property index
    * @type     {Integer}
    * @default  0
    */
    index: 0,

    /**
    * Model setup.
    *
    * Called by GuiModule, immediately after Module create().
    *
    * @method setup
    * @return {Mixed}
    */
    setup: function() {
        this.color('blue');
        this.icon('files-o');

        this.files     = ko.observableArray();
        this.fileInput = this.module.getModel('GuiFileinput');

        this.fileInput.onChange = function(files) {
            console.log(files);
        }
    },

    /**
    * Called after template is rendered.
    *
    * @event afterRender
    * @param {Array}     elements
    * @param {GuiModule} self
    */
    afterRender: function(elements, self) {

    }
});
<|endoftext|>