<commit_before>import _ from 'lodash';
import Debug from 'debug';
import decide from './decide';
import DEFAULTS from './defaults';
import jwtDecode from 'jwt-decode';
import request from './request';
import Time from './time';
import { CraftAiBadRequestError, CraftAiCredentialsError } from './errors';

let debug = Debug('craft-ai:client');

export default function createClient(tokenOrCfg) {
  let cfg = _.defaults(
    {},
    _.isString(tokenOrCfg) ? { token: tokenOrCfg } : tokenOrCfg,
    DEFAULTS
  );

  // Initialization check
  if (!_.has(cfg, 'token') || !_.isString(cfg.token)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid token provided.');
  }
  try {
    const { owner, project, platform } = jwtDecode(cfg.token);

    // Keep the provided values
    cfg.owner = cfg.owner || owner;
    cfg.project = cfg.project || project;
    cfg.url = cfg.url || platform;
  }
  catch (e) {
    throw new CraftAiCredentialsError();
  }
  if (!_.has(cfg, 'url') || !_.isString(cfg.url)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid url provided.');
  }
  if (!_.has(cfg, 'project') || !_.isString(cfg.project)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid project provided.');
  }
  else {
    const splittedProject = cfg.project.split('/');
    if (splittedProject.length >= 2) {
      cfg.owner = splittedProject[0];
      cfg.project = splittedProject[1];
    }
  }
  if (!_.has(cfg, 'owner') || !_.isString(cfg.owner)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid owner provided.');
  }

  debug(`Creating a client instance for project '${cfg.owner}/${cfg.project}' on '${cfg.url}'.`);

  // The cache of operations to send.
  let agentsOperations = {};

  // The promise that actually flush the context operations for one agent.
  let flushAgentContextOperationsPromise = agentId => {
    // Extract the operations to flush
    const operationsToFlush = agentsOperations[agentId] || [];
    agentsOperations[agentId] = [];

    if (operationsToFlush.length === 0) {
      // Nothing to flush
      return new Promise(resolve => resolve());
    }
    else {
      // Something to flush, in chunks !
      return _(operationsToFlush)
      .orderBy('timestamp')
      .chunk(cfg.operationsChunksSize)
      .reduce((p, chunk) => p.then(
          () => request({
            method: 'POST',
            path: '/agents/' + agentId + '/context',
            body: chunk
          }, cfg)
        ),
        new Promise(resolve => resolve())
      )
      .then(() => {
        debug(`Successfully added ${operationsToFlush.length} operations to the agent ${cfg.owner}/${cfg.project}/${agentId} context.`);
      });
    }
  };

  // This is the only flush operation that will occur in this client, ever.
  let currentFlushOperation = new Promise(resolve => resolve());

  // To execute when an immediate flush is needed.
  let flushAgentContextOperations = agentId => {
    currentFlushOperation = currentFlushOperation
      .then(() => flushAgentContextOperationsPromise(agentId));
    return currentFlushOperation
      .catch(err => {
        // If an error is caught during this immediate flush, we break the
        // Promise chain to avoid 'contaminating' future flush operations.
        currentFlushOperation = new Promise(resolve => resolve());
        return Promise.reject(err);
      });
  };

  // To execute when an eventual flush is needed.
  let throttledFlushAgentContextOperations = _.throttle(
    agentId => {
      currentFlushOperation = currentFlushOperation
        .then(() => flushAgentContextOperationsPromise(agentId));
      return currentFlushOperation;
    },
    cfg.operationsAdditionWait * 1000,
    {
      leading: true
    }
  );

  // 'Public' attributes & methods
  let instance = _.defaults(_.clone(cfg), DEFAULTS, {
    cfg: cfg,
    createAgent: function(configuration, id = undefined) {
      if (_.isUndefined(configuration) || !_.isObject(configuration)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to create an agent with no or invalid configuration provided.'));
      }

      return request({
        method: 'POST',
        path: '/agents',
        body: {
          id: id,
          configuration: configuration
        }
      }, this)
      .then(agent => {
        debug(`Agent '${agent.id}' created.`);
        return agent;
      });
    },
    getAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent with no agentId provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId
      }, this));
    },
    listAgents: function(agentId) {
      return request({
        method: 'GET',
        path: '/agents'
      }, this)
      .then(result => result.agentsList);
    },
    deleteAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to delete an agent with no agentId provided.'));
      }

      agentsOperations[agentId] = [];

      return request({
        method: 'DELETE',
        path: '/agents/' + agentId
      }, this)
      .then(agent => {
        debug(`Agent '${agentId}' deleted`);
        return agent;
      });
    },
    destroyAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to delete an agent with no agentId provided.'));
      }

      agentsOperations[agentId] = [];

      return request({
        method: 'DELETE',
        path: '/agents/' + agentId
      }, this)
      .then(agent => {
        console.warn('This function is deprecated. It will be removed in the future, use \'deleteAgent\' instead.');
        debug(`Agent '${agentId}' deleted`);
        return agent;
      });
    },
    getAgentContext: function(agentId, t = undefined) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent context with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent context with an invalid timestamp provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/context/state',
        query: {
          t: posixTimestamp
        }
      }, this));
    },
    addAgentContextOperations: function(agentId, operations, flush = false) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to add agent context operations with no agentId provided.'));
      }
      if (!_.isArray(operations)) {
        // Only one given operation
        operations = [operations];
      }
      operations = _.compact(operations);
      if (operations === []) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to add agent context operations with no or invalid operations provided.'));
      }

      agentsOperations[agentId] = (agentsOperations[agentId] || []).concat(
        _.map(operations, o => _.extend(o, {
          timestamp: Time(o.timestamp).timestamp
        }))
      );
      if (flush) {
        return flushAgentContextOperations(agentId);
      }
      else {
        throttledFlushAgentContextOperations(agentId);
        return new Promise(resolve => resolve());
      }
    },
    getAgentContextOperations: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get agent context operations with no agentId provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/context'
      }, this));
    },
    getAgentInspectorUrl: function(agentId, t = undefined) {
      console.warn('This function is deprecated. It will be removed in the future, use \'sharedAgentInspectorUrl\' instead.');
      return this.getSharedAgentInspectorUrl(agentId, t);
    },
    getSharedAgentInspectorUrl: function(agentId, t = undefined) {
      return request({
        method: 'GET',
        path: `/agents/${agentId}/shared`
      }, this)
      .then((url) => {
        if (_.isUndefined(t)) {
          return url.shortUrl;
        }
        else {
          let posixTimestamp = Time(t).timestamp;
          return `${url.shortUrl}?t=${posixTimestamp}`;
        }
      });
    },
    deleteSharedAgentInspectorUrl: function(agentId) {
      return request({
        method: 'DELETE',
        path: `/agents/${agentId}/shared`
      }, this)
      .then(() => {
        debug(`Delete shared inspector link for agent "${agentId}".`);
        return true;
      });
    },
    getAgentDecisionTree: function(agentId, t = undefined) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to retrieve an agent decision tree with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to retrieve an agent decision tree with an invalid timestamp provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/decision/tree',
        query: {
          t: posixTimestamp
        }
      }, this));
    },
    computeAgentDecision: function(agentId, t, ...contexts) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no or invalid timestamp provided.'));
      }
      if (_.isUndefined(contexts) || _.size(contexts) === 0) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no context provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/decision/tree',
        query: {
          t: posixTimestamp
        }
      }, this))
      .then(tree => {
        let decision = decide(tree, ...contexts);
        decision.timestamp = posixTimestamp;
        return decision;
      });
    }
  });

  return instance;
}
<commit_msg>Update deprecation warnings<commit_after>import _ from 'lodash';
import Debug from 'debug';
import decide from './decide';
import DEFAULTS from './defaults';
import jwtDecode from 'jwt-decode';
import request from './request';
import Time from './time';
import { CraftAiBadRequestError, CraftAiCredentialsError } from './errors';

let debug = Debug('craft-ai:client');

export default function createClient(tokenOrCfg) {
  let cfg = _.defaults(
    {},
    _.isString(tokenOrCfg) ? { token: tokenOrCfg } : tokenOrCfg,
    DEFAULTS
  );

  // Initialization check
  if (!_.has(cfg, 'token') || !_.isString(cfg.token)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid token provided.');
  }
  try {
    const { owner, project, platform } = jwtDecode(cfg.token);

    // Keep the provided values
    cfg.owner = cfg.owner || owner;
    cfg.project = cfg.project || project;
    cfg.url = cfg.url || platform;
  }
  catch (e) {
    throw new CraftAiCredentialsError();
  }
  if (!_.has(cfg, 'url') || !_.isString(cfg.url)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid url provided.');
  }
  if (!_.has(cfg, 'project') || !_.isString(cfg.project)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid project provided.');
  }
  else {
    const splittedProject = cfg.project.split('/');
    if (splittedProject.length >= 2) {
      cfg.owner = splittedProject[0];
      cfg.project = splittedProject[1];
    }
  }
  if (!_.has(cfg, 'owner') || !_.isString(cfg.owner)) {
    throw new CraftAiBadRequestError('Bad Request, unable to create a client with no or invalid owner provided.');
  }

  debug(`Creating a client instance for project '${cfg.owner}/${cfg.project}' on '${cfg.url}'.`);

  // The cache of operations to send.
  let agentsOperations = {};

  // The promise that actually flush the context operations for one agent.
  let flushAgentContextOperationsPromise = agentId => {
    // Extract the operations to flush
    const operationsToFlush = agentsOperations[agentId] || [];
    agentsOperations[agentId] = [];

    if (operationsToFlush.length === 0) {
      // Nothing to flush
      return new Promise(resolve => resolve());
    }
    else {
      // Something to flush, in chunks !
      return _(operationsToFlush)
      .orderBy('timestamp')
      .chunk(cfg.operationsChunksSize)
      .reduce((p, chunk) => p.then(
          () => request({
            method: 'POST',
            path: '/agents/' + agentId + '/context',
            body: chunk
          }, cfg)
        ),
        new Promise(resolve => resolve())
      )
      .then(() => {
        debug(`Successfully added ${operationsToFlush.length} operations to the agent ${cfg.owner}/${cfg.project}/${agentId} context.`);
      });
    }
  };

  // This is the only flush operation that will occur in this client, ever.
  let currentFlushOperation = new Promise(resolve => resolve());

  // To execute when an immediate flush is needed.
  let flushAgentContextOperations = agentId => {
    currentFlushOperation = currentFlushOperation
      .then(() => flushAgentContextOperationsPromise(agentId));
    return currentFlushOperation
      .catch(err => {
        // If an error is caught during this immediate flush, we break the
        // Promise chain to avoid 'contaminating' future flush operations.
        currentFlushOperation = new Promise(resolve => resolve());
        return Promise.reject(err);
      });
  };

  // To execute when an eventual flush is needed.
  let throttledFlushAgentContextOperations = _.throttle(
    agentId => {
      currentFlushOperation = currentFlushOperation
        .then(() => flushAgentContextOperationsPromise(agentId));
      return currentFlushOperation;
    },
    cfg.operationsAdditionWait * 1000,
    {
      leading: true
    }
  );

  // 'Public' attributes & methods
  let instance = _.defaults(_.clone(cfg), DEFAULTS, {
    cfg: cfg,
    createAgent: function(configuration, id = undefined) {
      if (_.isUndefined(configuration) || !_.isObject(configuration)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to create an agent with no or invalid configuration provided.'));
      }

      return request({
        method: 'POST',
        path: '/agents',
        body: {
          id: id,
          configuration: configuration
        }
      }, this)
      .then(agent => {
        debug(`Agent '${agent.id}' created.`);
        return agent;
      });
    },
    getAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent with no agentId provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId
      }, this));
    },
    listAgents: function(agentId) {
      return request({
        method: 'GET',
        path: '/agents'
      }, this)
      .then(result => result.agentsList);
    },
    deleteAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to delete an agent with no agentId provided.'));
      }

      agentsOperations[agentId] = [];

      return request({
        method: 'DELETE',
        path: '/agents/' + agentId
      }, this)
      .then(agent => {
        debug(`Agent '${agentId}' deleted`);
        return agent;
      });
    },
    destroyAgent: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to delete an agent with no agentId provided.'));
      }

      agentsOperations[agentId] = [];

      return request({
        method: 'DELETE',
        path: '/agents/' + agentId
      }, this)
      .then(agent => {
        console.warn('WARNING: \'destroyAgent\' method of craft ai client is deprecated. It will be removed in the future, use \'deleteAgent\' instead. Refer to https://beta.craft.ai/doc/js.');
        debug(`Agent '${agentId}' deleted`);
        return agent;
      });
    },
    getAgentContext: function(agentId, t = undefined) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent context with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get the agent context with an invalid timestamp provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/context/state',
        query: {
          t: posixTimestamp
        }
      }, this));
    },
    addAgentContextOperations: function(agentId, operations, flush = false) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to add agent context operations with no agentId provided.'));
      }
      if (!_.isArray(operations)) {
        // Only one given operation
        operations = [operations];
      }
      operations = _.compact(operations);
      if (operations === []) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to add agent context operations with no or invalid operations provided.'));
      }

      agentsOperations[agentId] = (agentsOperations[agentId] || []).concat(
        _.map(operations, o => _.extend(o, {
          timestamp: Time(o.timestamp).timestamp
        }))
      );
      if (flush) {
        return flushAgentContextOperations(agentId);
      }
      else {
        throttledFlushAgentContextOperations(agentId);
        return new Promise(resolve => resolve());
      }
    },
    getAgentContextOperations: function(agentId) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to get agent context operations with no agentId provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/context'
      }, this));
    },
    getAgentInspectorUrl: function(agentId, t = undefined) {
      console.warn('WARNING: \'getAgentInspectorUrl\' method of craft ai client is deprecated. It will be removed in the future, use \'getSharedAgentInspectorUrl\' instead. Refer to https://beta.craft.ai/doc/js.');
      return this.getSharedAgentInspectorUrl(agentId, t);
    },
    getSharedAgentInspectorUrl: function(agentId, t = undefined) {
      return request({
        method: 'GET',
        path: `/agents/${agentId}/shared`
      }, this)
      .then((url) => {
        if (_.isUndefined(t)) {
          return url.shortUrl;
        }
        else {
          let posixTimestamp = Time(t).timestamp;
          return `${url.shortUrl}?t=${posixTimestamp}`;
        }
      });
    },
    deleteSharedAgentInspectorUrl: function(agentId) {
      return request({
        method: 'DELETE',
        path: `/agents/${agentId}/shared`
      }, this)
      .then(() => {
        debug(`Delete shared inspector link for agent "${agentId}".`);
        return true;
      });
    },
    getAgentDecisionTree: function(agentId, t = undefined) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to retrieve an agent decision tree with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to retrieve an agent decision tree with an invalid timestamp provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/decision/tree',
        query: {
          t: posixTimestamp
        }
      }, this));
    },
    computeAgentDecision: function(agentId, t, ...contexts) {
      if (_.isUndefined(agentId)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no agentId provided.'));
      }
      let posixTimestamp = Time(t).timestamp;
      if (_.isUndefined(posixTimestamp)) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no or invalid timestamp provided.'));
      }
      if (_.isUndefined(contexts) || _.size(contexts) === 0) {
        return Promise.reject(new CraftAiBadRequestError('Bad Request, unable to compute an agent decision with no context provided.'));
      }

      return flushAgentContextOperations(agentId)
      .then(() => request({
        method: 'GET',
        path: '/agents/' + agentId + '/decision/tree',
        query: {
          t: posixTimestamp
        }
      }, this))
      .then(tree => {
        let decision = decide(tree, ...contexts);
        decision.timestamp = posixTimestamp;
        return decision;
      });
    }
  });

  return instance;
}
<|endoftext|>


<commit_before>'use strict';

var sock = require('../stuff/conf/sock');
var Fist = require('../../Fist');
var Fs = require('fs');
var Path = require('path');
var asker = require('asker');
var routes = require('../stuff/conf/router0');
var Promise = require('fist.util.promise');

var STATUS_CODES = require('http').STATUS_CODES;

module.exports = {

    Fist0: function (test) {

        var fist = new Fist({
            action: [
                Path.resolve('test/stuff/action/data0/*.js'),
                Path.resolve('test/stuff/action/data1/*.js')
            ],
            routes: routes
        });

        var spy = {
            rj: [],
            ac: [],
            rq: [],
            rs: [],
            mt: []
        };

        fist.on('accept', function (data) {
            spy.ac.push(data.path);
        });

        fist.on('reject', function (data) {
            spy.rj.push(data.path);
        });

        fist.on('request', function (data) {
            spy.rq.push(data.url.pathname);
        });

        fist.on('response', function (data) {
            spy.rs.push(data.url.pathname);
        });

        fist.on('match-done', function (data) {
            spy.mt.push(data.url.pathname);
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            timeout: 10000,
            socketPath: sock,
            path: '/'
        }, function (err, data) {

            test.strictEqual(data.data + '', JSON.stringify({
                result: {
                    className: 'by-stuff',
                    data: 100500,
                    knot: {
                        action: [
                            Path.resolve('test/stuff/action/data0/*.js'),
                            Path.resolve('test/stuff/action/data1/*.js')
                        ],
                        routes: routes
                    }
                },
                errors: {
                    error: 'error'
                }
            }));

            test.deepEqual(spy, {
                rq: ['/'],
                ac: ['abbr', 'className', 'data', 'knot'],
                rj: ['error'],
                rs: ['/'],
                mt: ['/']
            });

            test.done();
        });
    },

    Fist1: function (test) {

        var fist = new Fist({
            action: [
                Path.resolve('test/stuff/action/data0/*.js'),
                null
            ],
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            path: '/',
            socketPath: sock
        }, function (err) {
            test.ok(err);
            test.done();
        });
    },

    Fist2: function (test) {

        var fist = new Fist({
            action: [],
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '',
                require('http').STATUS_CODES[res.statusCode]);
            test.done();
        });
    },

    Fist3: function (test) {

        var fist = new Fist();

        fist.decl('john', Promise.resolve('john'));

        fist.decl('users', ['john'], function (track, result, errors, done) {

            setTimeout(function () {
                done(null, [result.john]);
            }, 0);

            return ['mike'];
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '["mike"]');
            test.done();
        });
    },

    Fist4: function (test) {

        var fist = new Fist();

        fist.decl('users', function (t, e, r, done) {

            var promise;

            setTimeout(function () {
                done(null, ['O_o']);
            }, 0);

            promise = new Promise();

            setTimeout(function () {
                promise.fulfill(['mike']);
            }, 100);

            return promise;
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '["mike"]');
            test.done();
        });
    },

    Fist5: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return {
                then: function () {
                    throw 0;
                }
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '0');
            test.done();
        });
    },

    Fist6: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return {
                then: function (onResolved, onRejected) {
                    onRejected(0);
                    onRejected(5);
                }
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '0');
            test.done();
        });
    },

    Fist7: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return function (done) {
                done(42);
                done(43);
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '42');
            test.done();
        });
    },

    Fist8: function (test) {

        var fist = new Fist();

        fist.decl('stream', function (track) {
            //  так в реальной жизни делать нельзя
            return track._req;
        });

        fist.route('POST', '/', 'stream');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'post',
            path: '/',
            body: ':)',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 200);
            test.strictEqual(res.data + '', ':)');
            test.done();
        });
    },

    Fist9: function (test) {

        var fist = new Fist();

        fist.decl('promise', function () {

            var x = {};

            Object.defineProperty(x, 'then', {
                get: function () {

                    throw 1;
                }
            });

            return x;
        });

        fist.route('GET', '/', 'promise');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '1');
            test.done();
        });
    },

    Fist10: function (test) {

        var fist = new Fist();

        fist.decl('primitive', function () {

            return 5;
        });

        fist.route('GET', '/', 'primitive');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 200);
            test.strictEqual(res.data + '', '5');
            test.done();
        });
    },

    Fist11: function (test) {

        var fist = new Fist({
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err) {
            test.ok(err);
            test.done();
        });
    },

    Fist12: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            done(null, 55);

            return 56;
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '55');
            test.done();
        });
    },

    Fist13: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            setTimeout(function () {
                done(null, 55);
            }, 0);
            return 56;
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '56');
            test.done();
        });
    },

    Fist14: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            done(null, new Error());
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '{}');
            test.done();
        });
    },

    Fist15: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('static', function (t, e, r, done) {
            test.strictEqual(t.url.path, '/static/js/index.js');
            done(null, t.url.path);
        });

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            path: '/static/js/index.js',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '/static/js/index.js');
            test.done();
        });

    },

    'Server-0': function (test) {

        var server = new Fist({
            staging: true
        });

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        server.decl('err', function (track, errors, result, done) {
            done(new Error());
        });

        server.route('GET', '/error/', 'err');

        server.listen(sock);

        asker({
            method: 'GET',
            path: '/error/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', STATUS_CODES[res.statusCode]);
            test.done();
        });
    },

    'Server-1': function (test) {

        var server = new Fist({
            staging: false
        });

        var er = new Error();

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        server.decl('err', function (track, errors, result, done) {
            done(er);
        });

        server.route('GET', '/error/', 'err');

        server.listen(sock);

        asker({
            method: 'GET',
            path: '/error/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', er.stack);
            test.done();
        });
    }

};
<commit_msg>v2.0.x: fix code style issues<commit_after>'use strict';

var sock = require('../stuff/conf/sock');
var Fist = require('../../Fist');
var Fs = require('fs');
var Path = require('path');
var asker = require('asker');
var routes = require('../stuff/conf/router0');
var Promise = require('fist.util.promise');

var STATUS_CODES = require('http').STATUS_CODES;

module.exports = {

    Fist0: function (test) {

        var fist = new Fist({
            action: [
                Path.resolve('test/stuff/action/data0/*.js'),
                Path.resolve('test/stuff/action/data1/*.js')
            ],
            routes: routes
        });

        var spy = {
            rj: [],
            ac: [],
            rq: [],
            rs: [],
            mt: []
        };

        fist.on('accept', function (data) {
            spy.ac.push(data.path);
        });

        fist.on('reject', function (data) {
            spy.rj.push(data.path);
        });

        fist.on('request', function (data) {
            spy.rq.push(data.url.pathname);
        });

        fist.on('response', function (data) {
            spy.rs.push(data.url.pathname);
        });

        fist.on('match-done', function (data) {
            spy.mt.push(data.url.pathname);
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            timeout: 10000,
            socketPath: sock,
            path: '/'
        }, function (err, data) {

            test.strictEqual(data.data + '', JSON.stringify({
                result: {
                    className: 'by-stuff',
                    data: 100500,
                    knot: {
                        action: [
                            Path.resolve('test/stuff/action/data0/*.js'),
                            Path.resolve('test/stuff/action/data1/*.js')
                        ],
                        routes: routes
                    }
                },
                errors: {
                    error: 'error'
                }
            }));

            test.deepEqual(spy, {
                rq: ['/'],
                ac: ['abbr', 'className', 'data', 'knot'],
                rj: ['error'],
                rs: ['/'],
                mt: ['/']
            });

            test.done();
        });
    },

    Fist1: function (test) {

        var fist = new Fist({
            action: [
                Path.resolve('test/stuff/action/data0/*.js'),
                null
            ],
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            path: '/',
            socketPath: sock
        }, function (err) {
            test.ok(err);
            test.done();
        });
    },

    Fist2: function (test) {

        var fist = new Fist({
            action: [],
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '',
                require('http').STATUS_CODES[res.statusCode]);
            test.done();
        });
    },

    Fist3: function (test) {

        var fist = new Fist();

        fist.decl('john', Promise.resolve('john'));

        fist.decl('users', ['john'], function (track, result, errors, done) {

            setTimeout(function () {
                done(null, [result.john]);
            }, 0);

            return ['mike'];
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '["mike"]');
            test.done();
        });
    },

    Fist4: function (test) {

        var fist = new Fist();

        fist.decl('users', function (t, e, r, done) {

            var promise;

            setTimeout(function () {
                done(null, ['O_o']);
            }, 0);

            promise = new Promise();

            setTimeout(function () {
                promise.fulfill(['mike']);
            }, 100);

            return promise;
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '["mike"]');
            test.done();
        });
    },

    Fist5: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return {
                then: function () {
                    throw 0;
                }
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '0');
            test.done();
        });
    },

    Fist6: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return {
                then: function (onResolved, onRejected) {
                    onRejected(0);
                    onRejected(5);
                }
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '0');
            test.done();
        });
    },

    Fist7: function (test) {

        var fist = new Fist();

        fist.decl('users', function () {

            return function (done) {
                done(42);
                done(43);
            };
        });

        fist.route('GET', '/', 'users');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '42');
            test.done();
        });
    },

    Fist8: function (test) {

        var fist = new Fist();

        fist.decl('stream', function (track) {
            //  так в реальной жизни делать нельзя
            return track._req;
        });

        fist.route('POST', '/', 'stream');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'post',
            path: '/',
            body: ':)',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 200);
            test.strictEqual(res.data + '', ':)');
            test.done();
        });
    },

    Fist9: function (test) {

        var fist = new Fist();

        fist.decl('promise', function () {

            var x = {};

            Object.defineProperty(x, 'then', {
                get: function () {

                    throw 1;
                }
            });

            return x;
        });

        fist.route('GET', '/', 'promise');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', '1');
            test.done();
        });
    },

    Fist10: function (test) {

        var fist = new Fist();

        fist.decl('primitive', function () {

            return 5;
        });

        fist.route('GET', '/', 'primitive');

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock,
            statusFilter: function () {

                return {
                    accept: true
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 200);
            test.strictEqual(res.data + '', '5');
            test.done();
        });
    },

    Fist11: function (test) {

        var fist = new Fist({
            routes: routes
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err) {
            test.ok(err);
            test.done();
        });
    },

    Fist12: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            done(null, 55);

            return 56;
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '55');
            test.done();
        });
    },

    Fist13: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            setTimeout(function () {
                done(null, 55);
            }, 0);
            return 56;
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '56');
            test.done();
        });
    },

    Fist14: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('index', function (t, e, r, done) {
            done(null, new Error());
        });

        try {
            Fs.unlinkSync(sock);
        } catch (err) {}

        fist.listen(sock);

        asker({
            method: 'get',
            path: '/',
            socketPath: sock
        }, function (err, res) {
            test.strictEqual(res.data + '', '{}');
            test.done();
        });
    },

    Fist15: function (test) {

        var fist = new Fist({
            routes: routes
        });

        fist.decl('static', function (t, e, r, done) {
            test.strictEqual(t.url.path, '/static/js/index.js');
            done(null, t.url.path);
        });

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        fist.listen(sock);

        asker({
            method: 'GET',
            path: '/static/js/index.js',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.data + '', '/static/js/index.js');
            test.done();
        });

    },

    'Server-0': function (test) {

        var server = new Fist({
            staging: true
        });

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        server.decl('err', function (track, errors, result, done) {
            done(new Error());
        });

        server.route('GET', '/error/', 'err');

        server.listen(sock);

        asker({
            method: 'GET',
            path: '/error/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', STATUS_CODES[res.statusCode]);
            test.done();
        });
    },

    'Server-1': function (test) {

        var server = new Fist({
            staging: false
        });

        var er = new Error();

        try {
            Fs.unlinkSync(sock);
        } catch (ex) {}

        server.decl('err', function (track, errors, result, done) {
            done(er);
        });

        server.route('GET', '/error/', 'err');

        server.listen(sock);

        asker({
            method: 'GET',
            path: '/error/',
            socketPath: sock,
            statusFilter: function () {
                return {
                    accept: true,
                    isRetryAllowed: false
                };
            }
        }, function (err, res) {
            test.strictEqual(res.statusCode, 500);
            test.strictEqual(res.data + '', er.stack);
            test.done();
        });
    }

};
<|endoftext|>


<commit_before>var Gu = require('gu');
/*var gu = new Gu('irc.rd.tandberg.com', 'curve', {
  userName: 'curver',
  realName: 'curvefever bot',
  debug: false,
  // doesn't make sense to have this bot on more than one chan
  // as per-channel-state is kept in this file
  channels: ['#mario', '#testor']
}, require('path').join(__dirname, 'bot'), ['query.js', 'signup.js']);
*/

var gu = new Gu('irc.quakenet.org', 'curveBot', {
  userName: 'curver',
  realName: 'curvefever bot',
  debug: false,
  // doesn't make sense to have this bot on more than one chan
  // as per-channel-state is kept in this file
  channels: ['#curveblah']
}, require('path').join(__dirname, 'bot'), ['query.js', 'signup.js']);
<commit_msg>take a confortable config too<commit_after>#!/usr/bin/env node
var cfgPath = require('confortable')('.curvestat.json', process.cwd());

if (!cfgPath) {
  throw new Error(
    "When loading curvefever-stats externally, a local config is required"
  );
}
var cfg = require(cfgPath);

require('gu')(cfg.server, cfg.name, {
  userName: 'curver',
  realName: 'curvefever bot',
  debug: false,
  // doesn't make sense to have this bot on more than one chan
  // as per-channel-state is kept in this file
  channels: [cfg.chan]
}, require('path').join(__dirname, 'bot'), ['query.js', 'signup.js']);
<|endoftext|>


<commit_before>/*! Swig v1.0.0-pre3 | https://paularmstrong.github.com/swig | https://github.com/paularmstrong/swig/blob/master/LICENSE */
/*! DateZ (c) 2011 Tomo Universalis | https://github.com/TomoUniversalis/DateZ/blob/master/LISENCE */
<commit_msg>ensure comments are preserved in minified source<commit_after>/*! Swig v1.0.0-pre3 | https://paularmstrong.github.com/swig | @license https://github.com/paularmstrong/swig/blob/master/LICENSE */
/*! DateZ (c) 2011 Tomo Universalis | @license https://github.com/TomoUniversalis/DateZ/blob/master/LISENCE */
<|endoftext|>


<commit_before>import './client.css';

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

import { Router, Route, Link } from 'react-router';

function getTussit() {
    return axios.get('/api/tussi').then((response) => {
        return response.data;
    });
}

const HelloWorld = React.createClass({
    render: function() {
        return (

                <Link to={`/hello/${this.props.name}`}>
                    Hello {this.props.name}
                </Link>

        );
    }
});

const HelloWorldApp = React.createClass({
    getInitialState: function() {
        return {
            count: 0,
            name: 'Pekkis',
            names: []
        };
    },

    componentDidMount: function() {
        getTussit().then((data) => {
            this.setState({
                names: data
            });
        });
    },

    render: function() {
        const names = this.state.names;

        return (

Lusso

                {names.map((name, i) =>
                    <HelloWorld key={i} name={name}/>
                )}

                <Counterizer
                    {...this.state}
                    onIncrementCounter={this.incrementCounter}/>

                <Counter count={this.state.count}/>

                {this.props.children}

        );
    },

    incrementCounter: function() {
        this.setState({
            count: this.state.count + 1
        });
    }
});

const Counterizer = React.createClass({
    render: function() {
        const { count, name, onIncrementCounter } = this.props;

        /*const count = this.props.count;
        const name = this.props.name;
        const onIncrementCounter = this.props.onIncrementCounter;*/

        return (

                {count}
                {name}

                <button
                    onClick={onIncrementCounter}>
                    MOAR!
                </button>

        );
    }
});

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

                {this.props.count}

        );
    }
};

const Greeter = React.createClass({
    render: function() {
        const { name } = this.props.params;

        return (

                Helloooo {name}

        );
    }
});

const routes = (
    <Router>
        <Route path="/" component={HelloWorldApp}>
            <Route path="/hello/:name" component={Greeter}></Route>
        </Route>
    </Router>
);

ReactDOM.render(
    routes,
    document.getElementById('app')
);
<commit_msg>Routing.<commit_after>import './client.css';

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

import { Router, Route, Link, IndexRoute } from 'react-router';

function getTussit() {
    return axios.get('/api/tussi').then((response) => {
        return response.data;
    });
}

const HelloWorld = React.createClass({
    render: function() {
        return (

                <Link to={`/hello/${this.props.name}`}>
                    Hello {this.props.name}
                </Link>

        );
    }
});

const HelloWorldApp = React.createClass({

    getInitialState: function() {
        return {
            count: 0,
            name: 'Pekkis',
            names: []
        };
    },

    componentDidMount: function() {
        getTussit().then((data) => {
            this.setState({
                names: data
            });
        });
    },

    render: function() {
        const names = this.state.names;

        return (

Lusso

                {this.props.children && React.cloneElement(
                    this.props.children,
                    {
                        names: this.state.names,
                        count: this.state.count,
                        onIncrementCounter: this.incrementCounter
                    }
                )}

        );
    },

    incrementCounter: function() {
        this.setState({
            count: this.state.count + 1
        });
    }
});

const Counterizer = React.createClass({
    render: function() {
        const { count, name, onIncrementCounter } = this.props;

        return (

                {count}
                {name}

                <button
                    onClick={onIncrementCounter}>
                    MOAR!
                </button>

        );
    }
});

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

                {this.props.count}

        );
    }
};

const Greeter = React.createClass({
    render: function() {
        const { name } = this.props.params;

        return (

                Helloooo {name}

        );
    }
});

const Index = React.createClass({

    render: function() {

        const { count, names, onIncrementCounter } = this.props;

        return (

                {names.map((name, i) =>
                    <HelloWorld key={i} name={name}/>
                )}

                <Counterizer
                    {...this.props}
                />

                <Counter count={count}/>

        );
    }

});

const routes = (
    <Router>
        <Route path="/" component={HelloWorldApp}>
            <IndexRoute component={Index} />
            <Route path="/hello/:name" component={Greeter}></Route>
        </Route>
    </Router>
);

ReactDOM.render(
    routes,
    document.getElementById('app')
);
<|endoftext|>


<commit_before>var config = {
    db: 'letschatbro', // Database
    templateRoot: 'template/', // Folder containing the templates
    cookie_secret: 'KeyBoard Cat', // Random secret string
    hostname: 'letschat', // The Hostname being used by the app
    media_path: 'media', // Location of the static files
    port: 5000 // Port to host on
}

module.exports = config
<commit_msg>Checked in my configuration by accident.<commit_after><|endoftext|>


<commit_before>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.Libraries = new function () {
	this.exists = function (libraryID) {
		var sql = "SELECT COUNT(*) FROM libraries WHERE libraryID=?";
		return !!Zotero.DB.valueQuery(sql, [libraryID]);
	}

	this.add = function (libraryID, type) {
		switch (type) {
			case 'group':
				break;

			default:
				throw ("Invalid library type '" + type + "' in Zotero.Libraries.add()");
		}

		var sql = "INSERT INTO libraries (libraryID, libraryType) VALUES (?, ?)";
		Zotero.DB.query(sql, [libraryID, type]);
	}

	this.getName = function (libraryID) {
		if (!libraryID) {
			return Zotero.getString('pane.collections.library');
		}

		var type = this.getType(libraryID);
		switch (type) {
			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.name;

			default:
				throw ("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}

	this.getType = function (libraryID) {
		if (libraryID === 0) {
			return 'user';
		}
		var sql = "SELECT libraryType FROM libraries WHERE libraryID=?";
		var libraryType = Zotero.DB.valueQuery(sql, libraryID);
		if (!libraryType) {
			throw ("Library " + libraryID + " does not exist in Zotero.Libraries.getType()");
		}
		return libraryType;
	}

	this.isEditable = function (libraryID) {
		var type = this.getType(libraryID);
		switch (type) {
			case 'user':
				return true;

			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.editable;

			default:
				throw ("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}

	this.isFilesEditable = function (libraryID) {
		var type = this.getType(libraryID);
		switch (type) {
			case 'user':
				return true;

			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.filesEditable;

			default:
				throw ("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}
}
<commit_msg>Better debugging info for library errors<commit_after>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.Libraries = new function () {
	this.exists = function (libraryID) {
		var sql = "SELECT COUNT(*) FROM libraries WHERE libraryID=?";
		return !!Zotero.DB.valueQuery(sql, [libraryID]);
	}

	this.add = function (libraryID, type) {
		switch (type) {
			case 'group':
				break;

			default:
				throw new Error("Invalid library type '" + type + "' in Zotero.Libraries.add()");
		}

		var sql = "INSERT INTO libraries (libraryID, libraryType) VALUES (?, ?)";
		Zotero.DB.query(sql, [libraryID, type]);
	}

	this.getName = function (libraryID) {
		if (!libraryID) {
			return Zotero.getString('pane.collections.library');
		}

		var type = this.getType(libraryID);
		switch (type) {
			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.name;

			default:
				throw new Error("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}

	this.getType = function (libraryID) {
		if (libraryID === 0) {
			return 'user';
		}
		var sql = "SELECT libraryType FROM libraries WHERE libraryID=?";
		var libraryType = Zotero.DB.valueQuery(sql, libraryID);
		if (!libraryType) {
			throw new Error("Library " + libraryID + " does not exist in Zotero.Libraries.getType()");
		}
		return libraryType;
	}

	this.isEditable = function (libraryID) {
		var type = this.getType(libraryID);
		switch (type) {
			case 'user':
				return true;

			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.editable;

			default:
				throw new Error("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}

	this.isFilesEditable = function (libraryID) {
		var type = this.getType(libraryID);
		switch (type) {
			case 'user':
				return true;

			case 'group':
				var groupID = Zotero.Groups.getGroupIDFromLibraryID(libraryID);
				var group = Zotero.Groups.get(groupID);
				return group.filesEditable;

			default:
				throw new Error("Unsupported library type '" + type + "' in Zotero.Libraries.getName()");
		}
	}
}
<|endoftext|>


<commit_before>// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Refresh function for refresh button on sidebar
function refresh(reload)
{
    window.location.reload(true);
}

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

// Function to call footable for responsive table functionality
$(function () {
    setTimeout(function() {
        $('#dashletPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('#subPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('.footable').footable();
        $(".footable").find("th:first").attr("data-toggle","true");
    },2000);
});

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
    if ($(window).width() > 980) {
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// Button to toggle list view search
$('.showsearch').click(function() {
    $('.search_form').toggle();
});

// jQuery to toggle sidebar

$('#buttontoggle').click(function(){
    $('.sidebar').toggle();
    if ($('.sidebar').is(':visible')){
        $.cookie('sidebartoggle', 'expanded');
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
        $('#buttontoggle').css({
            'left' : "+=215px"
        });
    }
    if ($('.sidebar').is(':hidden')){
        $.cookie('sidebartoggle', 'collapsed');
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        $('#buttontoggle').css({
            'left' : "-=215px"
        });
    }
    console.log($.cookie('sidebartoggle'));
});
var sidebartoggle = $.cookie('sidebartoggle');
if (sidebartoggle == 'collapsed'){
    $('.sidebar').hide();
    $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
    $('#buttontoggle').css({
        'left' : "-=215px"
    });
}
if (sidebartoggle == 'expanded'){
    $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');

}

// End of custom jQuery<commit_msg>Fix for sidebar issues when switching between different resolutions.<commit_after>// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Refresh function for refresh button on sidebar
function refresh(reload)
{
    window.location.reload(true);
}

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

// Function to call footable for responsive table functionality
$(function () {
    setTimeout(function() {
        $('#dashletPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('#subPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('.footable').footable();
        $(".footable").find("th:first").attr("data-toggle","true");
    },2000);
});

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
    if ($(window).width() > 980 && $('.sidebar').is(':visible')) {
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// Button to toggle list view search
$('.showsearch').click(function() {
    $('.search_form').toggle();
});

// jQuery to toggle sidebar

$('#buttontoggle').click(function(){
    $('.sidebar').toggle();
    if ($('.sidebar').is(':visible')){
        $.cookie('sidebartoggle', 'expanded');
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
        $('#buttontoggle').css({
            'left' : "+=215px"
        });
    }
    if ($('.sidebar').is(':hidden')){
        $.cookie('sidebartoggle', 'collapsed');
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        $('#buttontoggle').css({
            'left' : "-=215px"
        });
    }
    console.log($.cookie('sidebartoggle'));
});
var sidebartoggle = $.cookie('sidebartoggle');
if (sidebartoggle == 'collapsed'){
    $('.sidebar').hide();
    $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
    $('#buttontoggle').css({
        'left' : "-=215px"
    });
}
if (sidebartoggle == 'expanded'){
    $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');

}

// End of custom jQuery<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import {Router} from "react-router";
import Transmit from "react-transmit";
import routes from "views/routes";
import {createHistory} from "history";

/**
 * Fire-up React Router.
 */
const reactRoot = window.document.getElementById("react-root");
Transmit.render(Router, {routes, history: createHistory()}, reactRoot);

/**
 * Detect whether the server-side render has been discarded due to an invalid checksum.
 */
if (process.env.NODE_ENV !== "production") {
  if (!reactRoot.firstChild || !reactRoot.firstChild.attributes ||
      !reactRoot.firstChild.attributes["data-react-checksum"]) {
    console.error("Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.");
  }
}

<commit_msg>fixed routes path<commit_after>import React from "react";
import ReactDOM from "react-dom";
import {Router} from "react-router";
import Transmit from "react-transmit";
import routes from "./views/routes";
import {createHistory} from "history";

/**
 * Fire-up React Router.
 */
const reactRoot = window.document.getElementById("react-root");
Transmit.render(Router, {routes, history: createHistory()}, reactRoot);

/**
 * Detect whether the server-side render has been discarded due to an invalid checksum.
 */
if (process.env.NODE_ENV !== "production") {
  if (!reactRoot.firstChild || !reactRoot.firstChild.attributes ||
      !reactRoot.firstChild.attributes["data-react-checksum"]) {
    console.error("Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.");
  }
}

<|endoftext|>


<commit_before>(function() {

var requestAnimFrame = (function(){
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

var ctx;
var WIDTH = 640, HEIGHT = 480;
var stats;

var objs = [];
var turns = [];
var camera;
var hero;

function init() {
  // Create a canvas
  var canvas = $('.game canvas')[0];
  canvas.width = WIDTH;
  canvas.height = HEIGHT;

  stats = new Stats();
  stats.setMode(0); // 0: fps, 1: ms
  $('body').append(stats.domElement);

  var cell;
  var opts;
  var x, y;
  var r;
  var image;

  ctx = canvas.getContext("2d");

  var level = game.level = cartographer.mazeRegions();
  objs = objs.concat(level.objs);

  r = utils.randChoice(level.regions);
  x = utils.rand(r.bounds.x, r.bounds.x + r.bounds.w) * 32;
  y = utils.rand(r.bounds.y, r.bounds.y + r.bounds.h) * 32;
  hero = new Hero({x: x, y: y});
  objs.push(hero);
  turns.push(hero);

  // Add two randoms to get a distribution that peaks in the middle.
  var gooCount = utils.rand(1, 2) + utils.rand(0, 2);
  var goo;
  for (i=0; i<gooCount; i++) {
    r = utils.randChoice(level.regions);
    x = utils.rand(r.bounds.x, r.bounds.x + r.bounds.w) * 32;
    y = utils.rand(r.bounds.y, r.bounds.y + r.bounds.h) * 32;
    goo = new Goo({x: x, y: y});
    objs.push(goo);
    turns.push(goo);
  }

  camera = new Camera({target: hero});

  tick();
  nextTurn();

  key.setScope('game');

  game.message('Welcome to Depth.');
  game.message('Find and kill the slimes.');
}

var currentTurn = 0;
function nextTurn() {
  if (turns.length === 0) return;
  while (turns[currentTurn].remove) {
    turns.splice(currentTurn, 1);
    currentTurn %= turns.length;
  }
  var actor = turns[currentTurn];
  var d = actor.turn();
  currentTurn = (currentTurn + 1) % turns.length;
  d.then(nextTurn);
}

var lastFrame = +new Date();
function tick() {
  stats.begin();

  var i, l;
  var thisFrame = +new Date();
  var dt = thisFrame - lastFrame;

  ctx.clearRect(0, 0, WIDTH, HEIGHT);

  ctx.save();
  camera.transform(ctx);

  for (i=0; i < objs.length; i++) {
    objs[i].tick(dt);
    objs[i].render(ctx);
  }

  for (i=objs.length - 1; i>=0; i--) {
    if (objs[i].remove) {
      objs.splice(i, 1);
    }
  }

  ctx.restore();

  if (game.countEnemies() === 0) {
    $('.win').show();
    key.setScope('gameover');
  }
  if (hero.health <= 0) {
    $('.lose').show();
    key.setScope('gameover');
  }

  requestAnimFrame(tick);

  lastFrame = thisFrame;
  stats.end();
}

$(init);

window.game = {
  WIDTH: WIDTH,
  HEIGHT: HEIGHT
};

window.game.walkable = function(x, y) {
  var i, tile = game.level.tiles[y][x];

  for (i=0; i<tile.occupants.length; i++) {
    if (!tile.occupants[i].walkable) {
      return false;
    }
  }

  return game.level.map[y][x] !== 1;
};

window.game.pixelToTile = function(x, y) {
  return [Math.floor(x / 32), Math.floor(y / 32)];
};

window.game.countEnemies = function() {
  var i, a, count = 0;
  for (i=0; i<turns.length; i++) {
    a = turns[i];
    if (!a.remove && a.name === 'goo') {
      count++;
    }
  }
  return count;
};

var $messageContainer = $('.game .messages');
window.game.message = function(msg, html_dict) {
  var $msg = $('<li/>').text(msg);

  if ('id' in html_dict) {
    $msg.attr('id', html_dict['id']);
  }

  if ('class' in html_dict) {
    $msg.addClass(html_dict['class']);
  }

  $messageContainer
    .append($msg)
    // XXX This is hack to scroll to bottom
    .scrollTop(99999999);
};

window.game.removeMessage = function(id) {
  $messageContainer.find('#' + id).remove();
};

})();
<commit_msg>Add default value for html_dict.<commit_after>(function() {

var requestAnimFrame = (function(){
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

var ctx;
var WIDTH = 640, HEIGHT = 480;
var stats;

var objs = [];
var turns = [];
var camera;
var hero;

function init() {
  // Create a canvas
  var canvas = $('.game canvas')[0];
  canvas.width = WIDTH;
  canvas.height = HEIGHT;

  stats = new Stats();
  stats.setMode(0); // 0: fps, 1: ms
  $('body').append(stats.domElement);

  var cell;
  var opts;
  var x, y;
  var r;
  var image;

  ctx = canvas.getContext("2d");

  var level = game.level = cartographer.mazeRegions();
  objs = objs.concat(level.objs);

  r = utils.randChoice(level.regions);
  x = utils.rand(r.bounds.x, r.bounds.x + r.bounds.w) * 32;
  y = utils.rand(r.bounds.y, r.bounds.y + r.bounds.h) * 32;
  hero = new Hero({x: x, y: y});
  objs.push(hero);
  turns.push(hero);

  // Add two randoms to get a distribution that peaks in the middle.
  var gooCount = utils.rand(1, 2) + utils.rand(0, 2);
  var goo;
  for (i=0; i<gooCount; i++) {
    r = utils.randChoice(level.regions);
    x = utils.rand(r.bounds.x, r.bounds.x + r.bounds.w) * 32;
    y = utils.rand(r.bounds.y, r.bounds.y + r.bounds.h) * 32;
    goo = new Goo({x: x, y: y});
    objs.push(goo);
    turns.push(goo);
  }

  camera = new Camera({target: hero});

  tick();
  nextTurn();

  key.setScope('game');

  game.message('Welcome to Depth.');
  game.message('Find and kill the slimes.');
}

var currentTurn = 0;
function nextTurn() {
  if (turns.length === 0) return;
  while (turns[currentTurn].remove) {
    turns.splice(currentTurn, 1);
    currentTurn %= turns.length;
  }
  var actor = turns[currentTurn];
  var d = actor.turn();
  currentTurn = (currentTurn + 1) % turns.length;
  d.then(nextTurn);
}

var lastFrame = +new Date();
function tick() {
  stats.begin();

  var i, l;
  var thisFrame = +new Date();
  var dt = thisFrame - lastFrame;

  ctx.clearRect(0, 0, WIDTH, HEIGHT);

  ctx.save();
  camera.transform(ctx);

  for (i=0; i < objs.length; i++) {
    objs[i].tick(dt);
    objs[i].render(ctx);
  }

  for (i=objs.length - 1; i>=0; i--) {
    if (objs[i].remove) {
      objs.splice(i, 1);
    }
  }

  ctx.restore();

  if (game.countEnemies() === 0) {
    $('.win').show();
    key.setScope('gameover');
  }
  if (hero.health <= 0) {
    $('.lose').show();
    key.setScope('gameover');
  }

  requestAnimFrame(tick);

  lastFrame = thisFrame;
  stats.end();
}

$(init);

window.game = {
  WIDTH: WIDTH,
  HEIGHT: HEIGHT
};

window.game.walkable = function(x, y) {
  var i, tile = game.level.tiles[y][x];

  for (i=0; i<tile.occupants.length; i++) {
    if (!tile.occupants[i].walkable) {
      return false;
    }
  }

  return game.level.map[y][x] !== 1;
};

window.game.pixelToTile = function(x, y) {
  return [Math.floor(x / 32), Math.floor(y / 32)];
};

window.game.countEnemies = function() {
  var i, a, count = 0;
  for (i=0; i<turns.length; i++) {
    a = turns[i];
    if (!a.remove && a.name === 'goo') {
      count++;
    }
  }
  return count;
};

var $messageContainer = $('.game .messages');
window.game.message = function(msg, html_dict) {
  if (html_dict === undefined) html_dict = {};

  var $msg = $('<li/>').text(msg);

  if ('id' in html_dict) {
    $msg.attr('id', html_dict['id']);
  }

  if ('class' in html_dict) {
    $msg.addClass(html_dict['class']);
  }

  $messageContainer
    .append($msg)
    // XXX This is hack to scroll to bottom
    .scrollTop(99999999);
};

window.game.removeMessage = function(id) {
  $messageContainer.find('#' + id).remove();
};

})();
<|endoftext|>


<commit_before>describe('satellizer.config', function() {

  beforeEach(function() {
    var self = this;
    module('satellizer', function($authProvider) {
      self.$authProvider = $authProvider;
    });
  });

  beforeEach(inject(['satellizer.config', function(config) {
    this.config = config;
  }]));

  it('should set logoutRedirect', function() {
    this.$authProvider.logoutRedirect = '/signout';
    expect(this.config.logoutRedirect).toEqual('/signout');
    expect(this.$authProvider.logoutRedirect).toEqual('/signout');
  });

  it('should set loginRedirect', function() {
    this.$authProvider.loginRedirect = '/signin';
    expect(this.config.loginRedirect).toEqual('/signin');
    expect(this.$authProvider.loginRedirect).toEqual('/signin');
  });

  it('should set signupRedirect', function() {
    this.$authProvider.signupRedirect = '/newurl';
    expect(this.config.signupRedirect).toEqual('/newurl');
    expect(this.$authProvider.signupRedirect).toEqual('/newurl');
  });

  it('should set loginUrl', function() {
    this.$authProvider.loginUrl = '/api/signin';
    expect(this.config.loginUrl).toEqual('/api/signin');
    expect(this.$authProvider.loginUrl).toEqual('/api/signin');
  });

  it('should set signupUrl', function() {
    this.$authProvider.signupUrl = '/api/signup';
    expect(this.config.signupUrl).toEqual('/api/signup');
    expect(this.$authProvider.signupUrl).toEqual('/api/signup');
  });

  it('should set loginRoute', function() {
    this.$authProvider.loginRoute = '/signin';
    expect(this.config.loginRoute).toEqual('/signin');
    expect(this.$authProvider.loginRoute).toEqual('/signin');
  });

  it('should set signupRoute', function() {
    this.$authProvider.signupRoute = '/register';
    expect(this.config.signupRoute).toEqual('/register');
    expect(this.$authProvider.signupRoute).toEqual('/register');
  });

  it('should set tokenName', function() {
    this.$authProvider.tokenName = 'access_token';
    expect(this.config.tokenName).toEqual('access_token');
    expect(this.$authProvider.tokenName).toEqual('access_token');
  });

  it('should set tokenPrefix', function() {
    this.$authProvider.tokenPrefix = 'myApp';
    expect(this.config.tokenPrefix).toEqual('myApp');
    expect(this.$authProvider.tokenPrefix).toEqual('myApp');
  });

  it('should set unlinkUrl', function() {
    this.$authProvider.unlinkUrl = '/disconnect/';
    expect(this.config.unlinkUrl).toEqual('/disconnect/');
    expect(this.$authProvider.unlinkUrl).toEqual('/disconnect/');
  });

  it('should update facebook with new params', function() {
    this.$authProvider.facebook({ clientId: '1234' });
    expect(this.config.providers.facebook.clientId).toBe('1234');
  });

  it('should update googlewith new params', function() {
    this.$authProvider.google({ state: 'secret' });
    expect(this.config.providers.google.state).toBe('secret');
  });

  it('should update github with new params', function() {
    this.$authProvider.github({ clientId: '1234' });
    expect(this.config.providers.github.clientId).toBe('1234');
  });

  it('should update linkedin with new params', function() {
    this.$authProvider.linkedin({ state: 'secret' });
    expect(this.config.providers.linkedin.state).toBe('secret');
  });

  it('should update twitter with new params', function() {
    this.$authProvider.twitter({ url: '/api/twitter' });
    expect(this.config.providers.twitter.url).toBe('/api/twitter');
  });

  it('should create new oauth2 provider', function() {
    this.$authProvider.oauth2({ name: 'instagram', url: '/auth/instagram' });
    expect(this.config.providers['instagram'].name).toBe('instagram');
    expect(this.config.providers['instagram'].url).toBe('/auth/instagram');
  });

  it('should add a new oauth1 provider', function() {
    this.$authProvider.oauth1({ name: 'goodreads', url: '/auth/goodreads' });
    expect(this.config.providers['goodreads'].url).toBe('/auth/goodreads');
  });

});

<commit_msg>added loginOnSignup unit test<commit_after>describe('satellizer.config', function() {

  beforeEach(function() {
    var self = this;
    module('satellizer', function($authProvider) {
      self.$authProvider = $authProvider;
    });
  });

  beforeEach(inject(['satellizer.config', function(config) {
    this.config = config;
  }]));

  it('should set logoutRedirect', function() {
    this.$authProvider.logoutRedirect = '/signout';
    expect(this.config.logoutRedirect).toEqual('/signout');
    expect(this.$authProvider.logoutRedirect).toEqual('/signout');
  });

  it('should set loginRedirect', function() {
    this.$authProvider.loginRedirect = '/signin';
    expect(this.config.loginRedirect).toEqual('/signin');
    expect(this.$authProvider.loginRedirect).toEqual('/signin');
  });

  it('should set signupRedirect', function() {
    this.$authProvider.signupRedirect = '/newurl';
    expect(this.config.signupRedirect).toEqual('/newurl');
    expect(this.$authProvider.signupRedirect).toEqual('/newurl');
  });

  it('should get loginOnSignup', function() {
    this.$authProvider.loginOnSignup = true;
    expect(this.config.loginOnSignup).toEqual(true);
    expect(this.$authProvider.loginOnSignup).toEqual(true);
  });

  it('should set loginUrl', function() {
    this.$authProvider.loginUrl = '/api/signin';
    expect(this.config.loginUrl).toEqual('/api/signin');
    expect(this.$authProvider.loginUrl).toEqual('/api/signin');
  });

  it('should set signupUrl', function() {
    this.$authProvider.signupUrl = '/api/signup';
    expect(this.config.signupUrl).toEqual('/api/signup');
    expect(this.$authProvider.signupUrl).toEqual('/api/signup');
  });

  it('should set loginRoute', function() {
    this.$authProvider.loginRoute = '/signin';
    expect(this.config.loginRoute).toEqual('/signin');
    expect(this.$authProvider.loginRoute).toEqual('/signin');
  });

  it('should set signupRoute', function() {
    this.$authProvider.signupRoute = '/register';
    expect(this.config.signupRoute).toEqual('/register');
    expect(this.$authProvider.signupRoute).toEqual('/register');
  });

  it('should set tokenName', function() {
    this.$authProvider.tokenName = 'access_token';
    expect(this.config.tokenName).toEqual('access_token');
    expect(this.$authProvider.tokenName).toEqual('access_token');
  });

  it('should set tokenPrefix', function() {
    this.$authProvider.tokenPrefix = 'myApp';
    expect(this.config.tokenPrefix).toEqual('myApp');
    expect(this.$authProvider.tokenPrefix).toEqual('myApp');
  });

  it('should set unlinkUrl', function() {
    this.$authProvider.unlinkUrl = '/disconnect/';
    expect(this.config.unlinkUrl).toEqual('/disconnect/');
    expect(this.$authProvider.unlinkUrl).toEqual('/disconnect/');
  });

  it('should update facebook with new params', function() {
    this.$authProvider.facebook({ clientId: '1234' });
    expect(this.config.providers.facebook.clientId).toBe('1234');
  });

  it('should update google with new params', function() {
    this.$authProvider.google({ state: 'secret' });
    expect(this.config.providers.google.state).toBe('secret');
  });

  it('should update github with new params', function() {
    this.$authProvider.github({ clientId: '1234' });
    expect(this.config.providers.github.clientId).toBe('1234');
  });

  it('should update linkedin with new params', function() {
    this.$authProvider.linkedin({ state: 'secret' });
    expect(this.config.providers.linkedin.state).toBe('secret');
  });

  it('should update twitter with new params', function() {
    this.$authProvider.twitter({ url: '/api/twitter' });
    expect(this.config.providers.twitter.url).toBe('/api/twitter');
  });

  it('should create new oauth2 provider', function() {
    this.$authProvider.oauth2({ name: 'instagram', url: '/auth/instagram' });
    expect(this.config.providers['instagram'].name).toBe('instagram');
    expect(this.config.providers['instagram'].url).toBe('/auth/instagram');
  });

  it('should add a new oauth1 provider', function() {
    this.$authProvider.oauth1({ name: 'goodreads', url: '/auth/goodreads' });
    expect(this.config.providers['goodreads'].url).toBe('/auth/goodreads');
  });

});

<|endoftext|>


<commit_before>// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Refresh function for refresh button on sidebar
function refresh(reload)
{
    window.location.reload(true);
}

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

// Function to call footable for responsive table functionality
$(function () {
    setTimeout(function() {
        $('#dashletPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('#subPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('.footable').footable();
        $(".footable").find("th:first").attr("data-toggle","true");
    },2000);
});

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
    if ($(window).width() > 980) {
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// Button to toggle list view search
$('.showsearch').click(function() {
    $('.search_form').toggle();
});

// jQuery to toggle sidebar

$('#buttontoggle').click(function(){
    $('.sidebar').toggle();
    if ($('.sidebar').is(':visible')){
        $.cookie('sidebartoggle', 'expanded');
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
        $('#buttontoggle').css({
            'left' : "+=215px"
        });
    }
    if ($('.sidebar').is(':hidden')){
        $.cookie('sidebartoggle', 'collapsed');
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        $('#buttontoggle').css({
            'left' : "-=215px"
        });
    }
    console.log($.cookie('sidebartoggle'));
});
var sidebartoggle = $.cookie('sidebartoggle');
if (sidebartoggle == 'collapsed'){
    $('.sidebar').hide();
    $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
    $('#buttontoggle').css({
        'left' : "-=215px"
    });
}
if (sidebartoggle == 'expanded'){
    $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');

}

// End of custom jQuery<commit_msg>Fix for sidebar bugs.<commit_after>// Custom jQuery for theme

// Script to toggle copyright popup
$( "button" ).click(function() {
    $( "#sugarcopy" ).toggle();

});

// Custom JavaScript for copyright pop-ups
$(function() {
    $( "#dialog, #dialog2" ).dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 100
        },
        hide: {
            effect: "fade",
            duration: 1000
        }
    });
    $( "#powered_by" ).click(function() {
        $( "#dialog" ).dialog( "open" );
        $("#overlay").show().css({"opacity": "0.5"});
    });
    $( "#admin_options" ).click(function() {
        $( "#dialog2" ).dialog( "open" );
    });
});

// Back to top animation
$('#backtotop').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop:0}, 500); // Scroll speed to the top
});

// Refresh function for refresh button on sidebar
function refresh(reload)
{
    window.location.reload(true);
}

// Tabs jQuery for Admin panel
$(function() {
    var tabs = $( "#tabs" ).tabs();
    tabs.find( ".ui-tabs-nav" ).sortable({
        axis: "x",
        stop: function() {
            tabs.tabs( "refresh" );
        }
    });
});

// Function to call footable for responsive table functionality
$(function () {
    setTimeout(function() {
        $('#dashletPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('#subPanel th:not(:first-child)').attr("data-hide","phone, tablet");
        $('.footable').footable();
        $(".footable").find("th:first").attr("data-toggle","true");
    },2000);
});

// JavaScript fix to remove unrequired classes on smaller screens where sidebar is obsolete
$(window).resize(function () {
    if ($(window).width() < 979) {
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main');
    }
});

// Button to toggle list view search
$('.showsearch').click(function() {
    $('.search_form').toggle();
});

// jQuery to toggle sidebar

$('#buttontoggle').click(function(){
    $('.sidebar').toggle();
    if ($('.sidebar').is(':visible')){
        $.cookie('sidebartoggle', 'expanded');
        $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');
        $('#buttontoggle').css({
            'left' : "+=215px"
        });
    }
    if ($('.sidebar').is(':hidden')){
        $.cookie('sidebartoggle', 'collapsed');
        $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
        $('#buttontoggle').css({
            'left' : "-=215px"
        });
    }
    console.log($.cookie('sidebartoggle'));
});
var sidebartoggle = $.cookie('sidebartoggle');
if (sidebartoggle == 'collapsed'){
    $('.sidebar').hide();
    $('#bootstrap-container').removeClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 col-sm-3 col-md-2 sidebar');
    $('#buttontoggle').css({
        'left' : "-=215px"
    });
}
if (sidebartoggle == 'expanded'){
    $('#bootstrap-container').addClass('col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2');

}

// End of custom jQuery<|endoftext|>


<commit_before>var m = require('mithril');
var h = require('highcharts');
var Graph = require('../models/Graph.js');

exports.controller = function () {
  var ctrl = this;
  ctrl.fetchAll = Graph.fetchAll().then(function(appData) {
    ctrl.graphOptions = graphOptions(appData);
  })
}

exports.plotter = function(ctrl) { // config class
  return function(elem , isin) {
    if(!isin) {
      ctrl.graphOptions.chart.renderTo = elem;
      var chart = new Highcharts.Chart(ctrl.graphOptions);
    }
  };
};

exports.view = function(ctrl) { // view
    return  m("html", [ m("body", [
        m("#plot[style=height:400px]", {config: exports.plotter(ctrl)}),
        m("p",console.log(JSON.stringify(ctrl.fetchAll))),
        ]),
    ])
};

function graphOptions (graphData) {
  return {
        chart: {
            type: 'funnel',
            marginRight: 100
        },
        credits: {
            enabled: false
        },
        title: {
            text: 'Job Search Tracker',
            x: -50
        },
        plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    format: '{point.name} ({point.y:,.0f})',
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
                    softConnector: true
                },
                neckWidth: '0%',
                neckHeight: '0%'
            }
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Students',
            data: [
                ['Applications Submitted',  graphData.submitted],
                ['Phones Screens',       graphData.phoneScreens],
                ['Onsite Interviews', graphData.interviews],
                ['Offers',    graphData.offers],
                ['Accepted Offers',    graphData.acceptedOffers]
            ]
        }],
    }
}
<commit_msg>furter fixes to outcomesGraph<commit_after>var m = require('mithril');
var h = require('highcharts');
var Graph = require('../models/Graph.js');

exports.controller = function () {
  var ctrl = this;
  ctrl.fetchAll = Graph.fetchAll().then(function(appData) {
    ctrl.graphOptions = graphOptions(appData);
  })
}

exports.plotter = function(ctrl) { // config class
  return function(elem , isin) {
    if(!isin) {
      ctrl.graphOptions.chart.renderTo = elem;
      var chart = new Highcharts.Chart(ctrl.graphOptions);
    }
  };
};

exports.view = function(ctrl) { // view
    return  m("html", [ m("body", [
        m("#plot[style=height:400px]", {config: exports.plotter(ctrl)}),
        ]),
    ])
};

function graphOptions (graphData) {
  return {
        chart: {
            type: 'funnel',
            marginRight: 100
        },
        credits: {
            enabled: false
        },
        title: {
            text: 'Job Search Tracker',
            x: -50
        },
        plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    format: '{point.name} ({point.y:,.0f})',
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
                    softConnector: true
                },
                neckWidth: '0%',
                neckHeight: '0%'
            }
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Students',
            data: [
                ['Applications Submitted',  graphData.submitted],
                ['Phones Screens',       graphData.phoneScreens],
                ['Onsite Interviews', graphData.interviews],
                ['Offers',    graphData.offers],
                ['Accepted Offers',    graphData.acceptedOffers]
            ]
        }],
    }
}
<|endoftext|>