<commit_before>'use strict';

// Request body defination
// {
//   articles: {
//     method: 'muse.articles.index',
//     params: 'any',
//     dependencies: [
//       'create'
//     ]
//   },
//   create: {
//     method: 'muse.articles.index',
//     params: 'any',
//     dependencies: []
//   }
// }

const _ = require('lodash');
const assert = require('assert');
const mm = require('micromatch');
const semver = require('semver');

// Constant
const DEFAULT_GATEWAY_METHOD_NAME = '__gateway__';
const DEFAULT_GATEWAY_ROUTE_PATH = 'gateway';
const DEFAULT_GATEWAY_HTTP_METHOD = 'post';

// Create custom error with statusCode
function createError(statusCode, message) {
  let err = new Error(message);
  err.statusCode = err.status = statusCode == null ? 500 : statusCode;

  err.toJSON = function() {
    return {
      statusCode: err.statusCode,
      status: err.status,
      message: err.message
    };
  };

  return err;
}

// Cast val to array
function castToArray(val) {
  val = val || [];
  val = Array.isArray(val) ? val : (val == null ? [] : [val]);
  return val;
}

// allowedAPIs: Whitelist api list, support unix glob pattern
// forbiddenAPIs: Blacklist api list, support unix glob pattern
// max: Maximum requests for once

/**
 * Baiji Gateway Plugin
 *
 * @param {Application} app baiji Application instance
 * @param {Object} options
 * @param {Array} options.allowedAPIs Whitelist api list, support unix glob pattern
 * @param {Array} options.forbiddenAPIs Blacklist api list, support unix glob pattern
 * @param {Number} options.max Maximum requests for once
 * @param {String} options.name Custom gateway method name
 * @param {String} options.path Custom gateway route path
 * @param {String} options.verb Custom gateway http method
 *
 * @public
 */
module.exports = function baijiGatewayPlugin(app, options) {

  // Check baiji version
  assert(
    semver.satisfies(app.constructor.VERSION, '>= 0.8.14'),
    'baiji-gateway plugin require baiji version larger than 0.8.14'
  );

  options = Object.assign({}, options);
  options.max = options.max || 50;
  options.allowedAPIs = castToArray(options.allowedAPIs);
  options.forbiddenAPIs = castToArray(options.forbiddenAPIs);
  options.name = options.name || DEFAULT_GATEWAY_METHOD_NAME;
  options.path = options.path || DEFAULT_GATEWAY_ROUTE_PATH;
  options.verb = options.verb || DEFAULT_GATEWAY_HTTP_METHOD;

  if (options.onError) {
    assert(
      typeof options.onError === 'function',
      '`options.onError` must be a valid function'
    );
  }

  // Cache all methods
  const ALL_METHODS = filterAllowedMethods();

  // Filter all methods according to `allowedAPIs` and `forbiddenAPIs` option
  function filterAllowedMethods() {
    let allMethods = {};
    let allMethodNames = [];

    app.composedMethods().map(method => {
      // Ignore gateway method
      if (method.name === options.name) return;

      let methodName = method.fullName();

      allMethodNames.push(methodName);

      allMethods[methodName] = method;
    });

    // Filter all methods
    let filteredMethods = _.difference(allMethodNames, mm(allMethodNames, options.forbiddenAPIs));
    filteredMethods = mm(filteredMethods, options.allowedAPIs);

    return _.pick(allMethods, filteredMethods);
  }

  // Invoke method by name
  function invokeApiByName(name, ctx, args) {
    let method = ALL_METHODS[name];

    let mockCtx = ctx.adapter.Context.create(
      ctx.request,
      ctx.response,
      method,
      ctx.options
    );

    mockCtx.setArgs(args || {});
    mockCtx._isMock = true;

    return new Promise(function(resolve, reject) {
      mockCtx.on('error', function(res) {
        reject(res.error);
      });

      mockCtx.on('finish', function(res) {
        resolve(res.result);
      });

      // Invoke method with mocked context
      method.invoke(mockCtx);
    });
  }

  // Execute apis by specific orders
  // [promise0, [promise1, promise2], promise3, promise4]
  function execStack(stack) {
    stack = castToArray(stack);

    let next = stack.shift();
    let promise = Promise.resolve();

    if (next) {
      if (Array.isArray(next)) {
        promise = Promise.all(next.map(fn => fn()));
      } else {
        promise = next();
      }

      return promise.then(() => {
        return execStack(stack);
      });
    } else {
      return promise;
    }
  }

  // Execute all api requests according to definitions
  function executeApis(schema, ctx) {
    schema = schema || {};

    let result = {};

    let stack = _(schema)

    // Convert all api dependencies to array
    .map(function(api, name) {
      api = api || {};
      api.dependencies = castToArray(api.dependencies);
      return { name, api };
    })

    // Compare api priority by dependencies
    .tap(function(res) {
      return res.sort(function(a, b) {
        let a_dep = a.api.dependencies;
        let b_dep = b.api.dependencies;

        if (b_dep.indexOf(a.name) > -1) return -1;
        if (a_dep.indexOf(b.name) > -1) return 1;

        if (a_dep.length === 0 && b_dep.length !== 0) return -1;
        if (b_dep.length === 0 && a_dep.length !== 0) return 1;

        if (a_dep.length < b_dep.length) return -1;
        if (a_dep.length > b_dep.length) return 1;

        if (a.name > b.name) return -1;
        if (a.name < b.name) return 1;

        return 0;
      });
    })

    // Group apis by dependencies
    .tap(function(res) {
      let group = [];
      let order = [];
      res.map(item => {
        let key = item.api.dependencies.map(String).join('.');
        if (order.indexOf(key) === -1) order.push(key);
        let index = order.indexOf(key);
        if (!group[index]) group[index] = [];
        group[index].push(item);
      });
      return group;
    })

    // Convert to executeable stack
    .map(function(item) {
      item = castToArray(item);
      return item.map(i => {
        return function apiInvoker() {
          return invokeApiByName(i.api.method, ctx, i.api.params)
            .then(res => {
              result[i.name] = res;
            }).catch(err => {
              result[i.name] = err;
            });
        };
      });
    }).value();

    return execStack(stack).then(() => result);
  }

  // Validate schema and return proper error
  function validateSchema(schema) {
    schema = schema || {};

    let forbiddenAPIs = options.forbiddenAPIs;
    let allowedAPIs = options.allowedAPIs;

    let forbidden = false;

    let hasError;
    let apis = _.map(schema, val => {
      if (!val.method) hasError = true;
      return val.method;
    });
    let apisCount = apis.length;

    // Check whether the apis count is within tolerable range
    if (apisCount === 0 || hasError) return createError(422, 'Invalid Request Body');
    if (apisCount > options.max) return createError(406, 'Max Requests Exceeded');

    // Check whether the apis are within whitelist or without blacklist
    // Blacklist has heigher priority
    if (forbiddenAPIs.length && mm(apis, forbiddenAPIs).length) forbidden = true;
    if (allowedAPIs.length && mm(apis, allowedAPIs).length !== apis.length) forbidden = true;

    if (forbidden) return createError(403, 'Forbidden Request');
  }

  function buildNotes() {
    let title = 'Baiji gateway plugin method';
    let maxLength = 0;
    _.map(ALL_METHODS, (method, name) => {
      let length = name.length;
      if (maxLength < length) maxLength = length;
    });

    let notes = _.map(ALL_METHODS, (method, name) => {
      let paddedName = _.padEnd(`${name}`, maxLength, ' ');
      return `${paddedName} => ${method.description}`;
    }).join('\n');

    return `## ${title}\n\n### Support Methods:\n\`\`\`\n${notes} \n\`\`\``;
  }

  // Define Gateway main method
  app.define(options.name, {
    description: 'Baiji gateway plugin method',
    notes: buildNotes(),
    route: { path: options.path, verb: options.verb }
  }, function(ctx, next) {
    let schema = ctx.body || {};
    let error = validateSchema(schema);
    if (error) {
      if (options.onError) {
        return options.onError(error, ctx, next);
      } else {
        ctx.status(error.status);
        return ctx.done(error, next);
      }
    } else {
      return executeApis(ctx.body, ctx).then(res => {
        ctx.done(res, next);
      }).catch(err => {
        if (err && options.onError) {
          return options.onError(err, ctx, next);
        }
        ctx.status(err.status);
        return ctx.done(err, next);
      });
    }
  });
};
<commit_msg>add version check<commit_after>'use strict';

// Request body defination
// {
//   articles: {
//     method: 'muse.articles.index',
//     params: 'any',
//     dependencies: [
//       'create'
//     ]
//   },
//   create: {
//     method: 'muse.articles.index',
//     params: 'any',
//     dependencies: []
//   }
// }

const _ = require('lodash');
const assert = require('assert');
const mm = require('micromatch');
const semver = require('semver');

// Constant
const DEFAULT_GATEWAY_METHOD_NAME = '__gateway__';
const DEFAULT_GATEWAY_ROUTE_PATH = 'gateway';
const DEFAULT_GATEWAY_HTTP_METHOD = 'post';
const MINIMAL_VERSION_REQUIRED = '0.8.15';

// Create custom error with statusCode
function createError(statusCode, message) {
  let err = new Error(message);
  err.statusCode = err.status = statusCode == null ? 500 : statusCode;

  err.toJSON = function() {
    return {
      statusCode: err.statusCode,
      status: err.status,
      message: err.message
    };
  };

  return err;
}

// Cast val to array
function castToArray(val) {
  val = val || [];
  val = Array.isArray(val) ? val : (val == null ? [] : [val]);
  return val;
}

// allowedAPIs: Whitelist api list, support unix glob pattern
// forbiddenAPIs: Blacklist api list, support unix glob pattern
// max: Maximum requests for once

/**
 * Baiji Gateway Plugin
 *
 * @param {Application} app baiji Application instance
 * @param {Object} options
 * @param {Array} options.allowedAPIs Whitelist api list, support unix glob pattern
 * @param {Array} options.forbiddenAPIs Blacklist api list, support unix glob pattern
 * @param {Number} options.max Maximum requests for once
 * @param {String} options.name Custom gateway method name
 * @param {String} options.path Custom gateway route path
 * @param {String} options.verb Custom gateway http method
 *
 * @public
 */
module.exports = function baijiGatewayPlugin(app, options) {

  // Check baiji version
  assert(
    semver.satisfies(app.constructor.VERSION, `>= ${MINIMAL_VERSION_REQUIRED}`),
    `baiji-gateway plugin require baiji version larger than ${MINIMAL_VERSION_REQUIRED}`
  );

  options = Object.assign({}, options);
  options.max = options.max || 50;
  options.allowedAPIs = castToArray(options.allowedAPIs);
  options.forbiddenAPIs = castToArray(options.forbiddenAPIs);
  options.name = options.name || DEFAULT_GATEWAY_METHOD_NAME;
  options.path = options.path || DEFAULT_GATEWAY_ROUTE_PATH;
  options.verb = options.verb || DEFAULT_GATEWAY_HTTP_METHOD;

  if (options.onError) {
    assert(
      typeof options.onError === 'function',
      '`options.onError` must be a valid function'
    );
  }

  // Cache all methods
  const ALL_METHODS = filterAllowedMethods();

  // Filter all methods according to `allowedAPIs` and `forbiddenAPIs` option
  function filterAllowedMethods() {
    let allMethods = {};
    let allMethodNames = [];

    app.composedMethods().map(method => {
      // Ignore gateway method
      if (method.name === options.name) return;

      let methodName = method.fullName();

      allMethodNames.push(methodName);

      allMethods[methodName] = method;
    });

    // Filter all methods
    let filteredMethods = _.difference(allMethodNames, mm(allMethodNames, options.forbiddenAPIs));
    filteredMethods = mm(filteredMethods, options.allowedAPIs);

    return _.pick(allMethods, filteredMethods);
  }

  // Invoke method by name
  function invokeApiByName(name, ctx, args) {
    let method = ALL_METHODS[name];

    let mockCtx = ctx.adapter.Context.create(
      ctx.request,
      ctx.response,
      method,
      ctx.options
    );

    mockCtx.setArgs(args || {});
    mockCtx._isMock = true;

    return new Promise(function(resolve, reject) {
      mockCtx.on('error', function(res) {
        reject(res.error);
      });

      mockCtx.on('finish', function(res) {
        resolve(res.result);
      });

      // Invoke method with mocked context
      method.invoke(mockCtx);
    });
  }

  // Execute apis by specific orders
  // [promise0, [promise1, promise2], promise3, promise4]
  function execStack(stack) {
    stack = castToArray(stack);

    let next = stack.shift();
    let promise = Promise.resolve();

    if (next) {
      if (Array.isArray(next)) {
        promise = Promise.all(next.map(fn => fn()));
      } else {
        promise = next();
      }

      return promise.then(() => {
        return execStack(stack);
      });
    } else {
      return promise;
    }
  }

  // Execute all api requests according to definitions
  function executeApis(schema, ctx) {
    schema = schema || {};

    let result = {};

    let stack = _(schema)

    // Convert all api dependencies to array
    .map(function(api, name) {
      api = api || {};
      api.dependencies = castToArray(api.dependencies);
      return { name, api };
    })

    // Compare api priority by dependencies
    .tap(function(res) {
      return res.sort(function(a, b) {
        let a_dep = a.api.dependencies;
        let b_dep = b.api.dependencies;

        if (b_dep.indexOf(a.name) > -1) return -1;
        if (a_dep.indexOf(b.name) > -1) return 1;

        if (a_dep.length === 0 && b_dep.length !== 0) return -1;
        if (b_dep.length === 0 && a_dep.length !== 0) return 1;

        if (a_dep.length < b_dep.length) return -1;
        if (a_dep.length > b_dep.length) return 1;

        if (a.name > b.name) return -1;
        if (a.name < b.name) return 1;

        return 0;
      });
    })

    // Group apis by dependencies
    .tap(function(res) {
      let group = [];
      let order = [];
      res.map(item => {
        let key = item.api.dependencies.map(String).join('.');
        if (order.indexOf(key) === -1) order.push(key);
        let index = order.indexOf(key);
        if (!group[index]) group[index] = [];
        group[index].push(item);
      });
      return group;
    })

    // Convert to executeable stack
    .map(function(item) {
      item = castToArray(item);
      return item.map(i => {
        return function apiInvoker() {
          return invokeApiByName(i.api.method, ctx, i.api.params)
            .then(res => {
              result[i.name] = res;
            }).catch(err => {
              result[i.name] = err;
            });
        };
      });
    }).value();

    return execStack(stack).then(() => result);
  }

  // Validate schema and return proper error
  function validateSchema(schema) {
    schema = schema || {};

    let forbiddenAPIs = options.forbiddenAPIs;
    let allowedAPIs = options.allowedAPIs;

    let forbidden = false;

    let hasError;
    let apis = _.map(schema, val => {
      if (!val.method) hasError = true;
      return val.method;
    });
    let apisCount = apis.length;

    // Check whether the apis count is within tolerable range
    if (apisCount === 0 || hasError) return createError(422, 'Invalid Request Body');
    if (apisCount > options.max) return createError(406, 'Max Requests Exceeded');

    // Check whether the apis are within whitelist or without blacklist
    // Blacklist has heigher priority
    if (forbiddenAPIs.length && mm(apis, forbiddenAPIs).length) forbidden = true;
    if (allowedAPIs.length && mm(apis, allowedAPIs).length !== apis.length) forbidden = true;

    if (forbidden) return createError(403, 'Forbidden Request');
  }

  function buildNotes() {
    let title = 'Baiji gateway plugin method';
    let maxLength = 0;
    _.map(ALL_METHODS, (method, name) => {
      let length = name.length;
      if (maxLength < length) maxLength = length;
    });

    let notes = _.map(ALL_METHODS, (method, name) => {
      let paddedName = _.padEnd(`${name}`, maxLength, ' ');
      return `${paddedName} => ${method.description}`;
    }).join('\n');

    return `## ${title}\n\n### Support Methods:\n\`\`\`\n${notes} \n\`\`\``;
  }

  // Define Gateway main method
  app.define(options.name, {
    description: 'Baiji gateway plugin method',
    notes: buildNotes(),
    route: { path: options.path, verb: options.verb }
  }, function(ctx, next) {
    let schema = ctx.body || {};
    let error = validateSchema(schema);
    if (error) {
      if (options.onError) {
        return options.onError(error, ctx, next);
      } else {
        ctx.status(error.status);
        return ctx.done(error, next);
      }
    } else {
      return executeApis(ctx.body, ctx).then(res => {
        ctx.done(res, next);
      }).catch(err => {
        if (err && options.onError) {
          return options.onError(err, ctx, next);
        }
        ctx.status(err.status);
        return ctx.done(err, next);
      });
    }
  });
};
<|endoftext|>


<commit_before>'use strict';

var util = require('runtime/lib/utils');
var runtime = require('runtime').get('gulp');

var env = runtime.config('env');
var whichGulp = runtime.config('which');

runtime.set(['-v', '--version'], function version(){

  //
  // always lazy
  // though it makes no sense here
  // since gulp itself its requiring them
  //
  var semver = require('semver');
  var chalk = util.colors;

  var cliPackage = env.cliPackage;
  var modulePackage = env.modulePackage;

  if( process.argv.indexOf(whichGulp) < 0 ){

    util.log('Working locally. Local gulp is ', modulePackage.version );

  } else if ( semver.gt(cliPackage.version, modulePackage.version) ) {

    util.log(chalk.red('Warning: gulp version mismatch:'));
    util.log(chalk.red('Global gulp is', cliPackage.version));
    util.log(chalk.red('Local gulp is', modulePackage.version));

  } else {
    util.log('CLI version', cliPackage.version);
    util.log('Local version', modulePackage.version);
  }

  runtime.prompt();
});
<commit_msg>save env fo version checks<commit_after>'use strict';

var util = require('runtime/lib/utils');
var runtime = require('runtime').get('gulp');

//
// ## save `env` before anyone can touch it
//
var env = runtime.config('env');

runtime.set(['-v', '--version'], function version(){

  //
  // always lazy
  // though it makes no sense here
  // since gulp itself its requiring them
  //
  var semver = require('semver');
  var chalk = util.colors;

  var cliPackage = env.cliPackage;
  var modulePackage = env.modulePackage;

  if( env.cliPackage === null ){

    util.log('Working locally. Local gulp is ', modulePackage.version );

  } else if ( semver.gt(cliPackage.version, modulePackage.version) ) {

    util.log(chalk.red('Warning: gulp version mismatch:'));
    util.log(chalk.red('Global gulp is', cliPackage.version));
    util.log(chalk.red('Local gulp is', modulePackage.version));

  } else {
    util.log('CLI version', cliPackage.version);
    util.log('Local version', modulePackage.version);
  }

  runtime.prompt();
});
<|endoftext|>


<commit_before>sc.views.Node.define('text', {

  className: 'content-node text',

  // This should be moved into a separate module
  events: {
    'click .annotation-tools .toggle': 'toggleAnnotation'
  },

  toggleAnnotation: function(e) {
    var type = $(e.currentTarget).attr('data-type');

    // Check for existing annotation
    var sel = this.surface.selection();
    var a = this.surface.getAnnotations(sel, [type])[0];

    // Overlap
    if (a) {
      if (_.isEqual(sel, a.pos)) {
        // Full overlap
        this.surface.deleteAnnotation(a.id);
      } else {
        // Partial overlap, update annotation
        // For now do nothing
      }
    } else {
      // Insert new annotation
      this.annotate(type);
    }

    // this.removeToggles();
    this.renderToggles(sel);
    return false;
  },

  focus: function () {
    $(this.textEl).click();
  },

  select: function () {
    sc.views.Node.prototype.select.apply(this);
  },

  deselect: function () {
    sc.views.Node.prototype.deselect.apply(this);
  },

  // Deal with incoming update
  update: function() {
    // this.editor.setValue(this.model.content);
  },

  // Make this a toggling bitch
  annotate: function(type) {
    var id = "annotation:"+Math.uuid();
    this.surface.insertAnnotation({ id: id, type: type, pos: this.surface.selection() });
    choreographer.trigger('comment-scope:selected', id, this.model.id, id);
  },

  initSurface: function() {
    var that = this;

    var annotations = app.view.model.document.annotations(this.model.id);

    this.surface = new Substance.Surface({
      el: this.$('.content')[0],
      content: this.model.content,
      annotations: annotations,
      types: {
        "em": {
          "inclusive": true,
          "visibility" : 'both'
        },
        "str": {
          "inclusive": true,
          "visibility" : 'both'
        },
        "idea": {
          "inclusive": false,
          "visibility" : 'both'
        },
        "blur": {
          "inclusive": false,
          "visibility" : 'both'
        },
        "doubt": {
          "inclusive": false,
          "visibility" : 'both'
        }
      }
    });

    // Events
    // ------

    // Hackish way to prevent node selection to be triggered two times
    this.$('.content').click(function() {
      return false;
    });

    this.surface.on('surface:active', function(sel) {
      that.session.select([that.model.id], {edit: true});
    });

    function selectionChanged(sel) {
      var marker = that.surface.getAnnotations(sel, ["idea", "blur", "doubt"])[0];
      if (marker) {
        choreographer.trigger('comment-scope:selected', marker.id, that.model.id, marker.id);
        that.surface.highlight(marker.id);
      } else {
        choreographer.trigger('comment-scope:selected', 'node_comments', that.model.id, null);
        that.surface.highlight(null);
      }

      sel[1] > 0 ? that.renderToggles(sel) : that.removeToggles();
    }

    // Update comments panel according to marker context
    this.surface.off('selection:changed', selectionChanged);
    this.surface.on('selection:changed', selectionChanged);

    // This gets fired a lot on every keystroke but no longer for adding annotations
    this.surface.on('changed', function() {
      // that.session.comments.updateAnnotations(that.surface.getContent(), that.surface.annotations);
    });

    this.$('.content').bind('blur', function() {
      console.log('surface deactivated');
      // that.removeToggles();
    });

    this.surface.on('annotations:changed', function() {
      that.session.comments.updateAnnotations(that.surface.getContent(), that.surface.annotations);
    });

    // Changes are confirmed.
    this.surface.on('content:changed', function(content, prevContent, ops) {

      var delta = _.extractOperation(prevContent, content);

      // console.log('Partial text update', delta);

      // Update content incrementally
      if (content !== prevContent) {
        var op = ["update", {id: that.model.id, "data": delta}];
        that.document.apply(op);
      }

      // console.log('annotation ops', ops);

      // Applying annotation ops...
      _.each(ops, function(op) {
        op[0] += "_annotation"; // should be done on the surface level?
        op[1].node = that.model.id;
        that.document.apply(op, {user: "michael"});
      });
    });
  },

  removeToggles: function() {
    this.$('.annotation-tools').empty();
  },

  renderToggles: function(sel) {
    var that = this;

    // Find last char
    var lastChar = this.$('.content').children()[sel[0]+sel[1]-1];

    // Calculate active states
    // Full overlap = active
    // Partial overlap = active
    var annotations = [
      {"type": "em", "active": false },
      {"type": "str", "active": false },
      {"type": "idea", "active": false },
      {"type": "blur", "active": false },
      {"type": "doubt", "active": false }
    ];

    _.each(annotations, function(a) {
      var anns = that.surface.getAnnotations(sel, [a.type]);
      if (anns.length > 0) a.active = true;
    });

    // Render tools
    this.$('.annotation-tools').html(_.tpl('annotation_toggles', {
      "annotations": annotations
    }));

    // Position dem
    var pos = this.$(lastChar).position();
    pos.left += 10;
    this.$('.annotation-tools').css(pos);
  },

  render: function() {
    sc.views.Node.prototype.render.apply(this, arguments);
    this.initSurface();
    return this;
  }
});<commit_msg>Improved annotation bizniz.<commit_after>sc.views.Node.define('text', {

  className: 'content-node text',

  // This should be moved into a separate module
  events: {
    'click .annotation-tools .toggle': 'toggleAnnotation'
  },

  toggleAnnotation: function(e) {
    var type = $(e.currentTarget).attr('data-type');

    // Check for existing annotation
    var sel = this.surface.selection();
    var a = this.surface.getAnnotations(sel, [type])[0];

    // Overlap
    if (a) {
      var start = sel[0];
      var end = start + sel[1];
      var aStart = a.pos[0];
      var aEnd = aStart + a.pos[1];

      if (start <= aStart && end >= aEnd) {
        // Full overlap
        this.surface.deleteAnnotation(a.id);
      } else {
        if (start < aStart) {
          // Partial overlap left-hand side
          this.surface.updateAnnotation({
            id: a.id,
            pos: [end, a.pos[1] - (end - a.pos[0])]
          });

        } else if (start < aEnd && end > aEnd) {
          // Partial overlap right-hand side
          this.surface.updateAnnotation({
            id: a.id,
            pos: [a.pos[0], start - aStart]
          });
        } else {
          this.surface.deleteAnnotation(a.id);
        }
      }
    } else {
      // Insert new annotation
      this.annotate(type);
    }

    // this.removeToggles();
    this.renderToggles(sel);
    return false;
  },

  focus: function () {
    $(this.textEl).click();
  },

  select: function () {
    sc.views.Node.prototype.select.apply(this);
  },

  deselect: function () {
    sc.views.Node.prototype.deselect.apply(this);
  },

  // Deal with incoming update
  update: function() {
    // this.editor.setValue(this.model.content);
  },

  // Make this a toggling bitch
  annotate: function(type) {
    var id = "annotation:"+Math.uuid();
    this.surface.insertAnnotation({ id: id, type: type, pos: this.surface.selection() });
    choreographer.trigger('comment-scope:selected', id, this.model.id, id);
  },

  initSurface: function() {
    var that = this;

    var annotations = app.view.model.document.annotations(this.model.id);

    this.surface = new Substance.Surface({
      el: this.$('.content')[0],
      content: this.model.content,
      annotations: annotations,
      types: {
        "em": {
          "inclusive": true,
          "visibility" : 'both'
        },
        "str": {
          "inclusive": true,
          "visibility" : 'both'
        },
        "idea": {
          "inclusive": false,
          "visibility" : 'both'
        },
        "blur": {
          "inclusive": false,
          "visibility" : 'both'
        },
        "doubt": {
          "inclusive": false,
          "visibility" : 'both'
        }
      }
    });

    // Events
    // ------

    // Hackish way to prevent node selection to be triggered two times
    this.$('.content').click(function() {
      return false;
    });

    this.surface.on('surface:active', function(sel) {
      that.session.select([that.model.id], {edit: true});
    });

    function selectionChanged(sel) {
      var marker = that.surface.getAnnotations(sel, ["idea", "blur", "doubt"])[0];
      if (marker) {
        choreographer.trigger('comment-scope:selected', marker.id, that.model.id, marker.id);
        that.surface.highlight(marker.id);
      } else {
        choreographer.trigger('comment-scope:selected', 'node_comments', that.model.id, null);
        that.surface.highlight(null);
      }

      sel[1] > 0 ? that.renderToggles(sel) : that.removeToggles();
    }

    // Update comments panel according to marker context
    this.surface.off('selection:changed', selectionChanged);
    this.surface.on('selection:changed', selectionChanged);

    // This gets fired a lot on every keystroke but no longer for adding annotations
    this.surface.on('changed', function() {
      // that.session.comments.updateAnnotations(that.surface.content, that.surface.annotations);
    });

    this.$('.content').bind('blur', function() {
      console.log('surface deactivated');
      // that.removeToggles();
    });

    this.surface.on('annotations:changed', function() {
      that.session.comments.updateAnnotations(that.surface.content, that.surface.annotations);
    });

    // Changes are confirmed.
    this.surface.on('content:changed', function(content, prevContent, ops) {

      var delta = _.extractOperation(prevContent, content);

      // console.log('Partial text update', delta);

      // Update content incrementally
      if (content !== prevContent) {
        var op = ["update", {id: that.model.id, "data": delta}];
        that.document.apply(op);
      }

      // console.log('annotation ops', ops);

      // Applying annotation ops...
      _.each(ops, function(op) {
        op[0] += "_annotation"; // should be done on the surface level?
        op[1].node = that.model.id;
        that.document.apply(op, {user: "michael"});
      });
    });
  },

  removeToggles: function() {
    this.$('.annotation-tools').empty();
  },

  renderToggles: function(sel) {
    var that = this;

    // Find last char
    var lastChar = this.$('.content').children()[sel[0]+sel[1]-1];

    // Calculate active states
    // Full overlap = active
    // Partial overlap = active
    var annotations = [
      {"type": "em", "active": false },
      {"type": "str", "active": false },
      {"type": "idea", "active": false },
      {"type": "blur", "active": false },
      {"type": "doubt", "active": false }
    ];

    _.each(annotations, function(a) {
      var anns = that.surface.getAnnotations(sel, [a.type]);
      if (anns.length > 0) a.active = true;
    });

    // Render tools
    this.$('.annotation-tools').html(_.tpl('annotation_toggles', {
      "annotations": annotations
    }));

    // Position dem
    var pos = this.$(lastChar).position();
    pos.left += 10;
    this.$('.annotation-tools').css(pos);
  },

  render: function() {
    sc.views.Node.prototype.render.apply(this, arguments);
    this.initSurface();
    return this;
  }
});<|endoftext|>


<commit_before>var path = require("path");
var ProcessPool = require("./proc/pool");

function LoaderProcClient(options) {
  this.options = Object.assign({}, options);
  this.cache = {};
  this.pending = {};
  this.pool = createPool(this, options.multiprocess);
}

LoaderProcClient.prototype.fetch = function(names, referrer) {
  var deferred = Array.isArray(names) ? this._fetchMany(names, referrer) : this._fetchOne(names, referrer);

  return deferred
    .then(result => {
      this.pool.procs.map(proc => this.pool.send("clear", null, proc));
      return result;
    })
    .catch(err => {
      this.pool.procs.map(proc => this.pool.send("clear", null, proc));
      throw err;
    });
};

LoaderProcClient.prototype.setModule = function(mod) {
  this.cache[mod.id] = mod;
};

LoaderProcClient.prototype.getModule = function(id) {
  return this.cache[id];
};

LoaderProcClient.prototype.deleteModule = function(mod) {
  delete this.cache[mod.id];
};

LoaderProcClient.prototype.getCache = function() {
  return this.cache;
};

LoaderProcClient.prototype._fetchMany = function(names, referrer) {
  return Promise.all(names.map(name => this._fetchOne(name, referrer)));
};

LoaderProcClient.prototype._fetchOne = function(name, referrer) {
  return resolve(this, name, referrer).then((modulePath) => {
    if (this.cache[modulePath]) {
      return this.cache[modulePath];
    }
    else if (this.pending[modulePath]) {
      return this.pending[modulePath];
    }

    var pending = fetch(this, name, referrer);
    this.pending[modulePath] = pending;

    return pending.then(mod => {
      delete this.pending[mod.path];
      this.setModule(mod);

      if (!mod.deps.length) {
        return mod;
      }

      // console.log("deps", mod.name, mod.deps);

      return this._fetchMany(mod.deps, mod).then(deps => {
        mod.deps = deps.map(dep => Object.assign({}, dep, { deps: [] }));
        return mod;
      });
    });
  });
};

function resolve(loader, name, referrer) {
  return loader.pool.send("resolve", {
    name: name,
    referrer: referrer
  });
}

function fetch(loader, name, referrer) {
  return loader.pool.send("fetchShallow", {
    name: name,
    referrer: referrer
  });
}

function createPool(loader, size) {
  var pool = new ProcessPool(path.join(__dirname, "./loaderProcServer.js"), { size: size });

  pool.procs.forEach((proc) => {
    proc.handle.stdout.pipe(process.stdout);
    proc.handle.stderr.pipe(process.stderr);
    pool.send("init", loader.options, proc);
  });

  return pool;
}

module.exports = LoaderProcClient;
<commit_msg>converted loaderProcClient to use classes<commit_after>'use strict';

var path = require("path");
var ProcessPool = require("./proc/pool");

class LoaderProcClient {
  constructor(options) {
    this.options = Object.assign({}, options);
    this.cache = {};
    this.pending = {};
    this.pool = createPool(this, options.multiprocess);
  }

  fetch(names, referrer) {
    var deferred = Array.isArray(names) ? this._fetchMany(names, referrer) : this._fetchOne(names, referrer);

    return deferred
      .then(result => {
        this.pool.procs.map(proc => this.pool.send("clear", null, proc));
        return result;
      })
      .catch(err => {
        this.pool.procs.map(proc => this.pool.send("clear", null, proc));
        throw err;
      });
  }

  setModule(mod) {
    this.cache[mod.id] = mod;
  }

  getModule(id) {
    return this.cache[id];
  }

  deleteModule(mod) {
    delete this.cache[mod.id];
  }

  getCache() {
    return this.cache;
  }

  _fetchMany(names, referrer) {
    return Promise.all(names.map(name => this._fetchOne(name, referrer)));
  }

  _fetchOne(name, referrer) {
    return resolve(this, name, referrer).then((modulePath) => {
      if (this.cache[modulePath]) {
        return this.cache[modulePath];
      }
      else if (this.pending[modulePath]) {
        return this.pending[modulePath];
      }

      var pending = fetch(this, name, referrer);
      this.pending[modulePath] = pending;

      return pending.then(mod => {
        delete this.pending[mod.path];
        this.setModule(mod);

        if (!mod.deps.length) {
          return mod;
        }

        // console.log("deps", mod.name, mod.deps);

        return this._fetchMany(mod.deps, mod).then(deps => {
          mod.deps = deps.map(dep => Object.assign({}, dep, { deps: [] }));
          return mod;
        });
      });
    });
  }
}

function resolve(loader, name, referrer) {
  return loader.pool.send("resolve", {
    name: name,
    referrer: referrer
  });
}

function fetch(loader, name, referrer) {
  return loader.pool.send("fetchShallow", {
    name: name,
    referrer: referrer
  });
}

function createPool(loader, size) {
  var pool = new ProcessPool(path.join(__dirname, "./loaderProcServer.js"), { size: size });

  pool.procs.forEach((proc) => {
    proc.handle.stdout.pipe(process.stdout);
    proc.handle.stderr.pipe(process.stderr);
    pool.send("init", loader.options, proc);
  });

  return pool;
}

module.exports = LoaderProcClient;
<|endoftext|>


<commit_before>/**
 *  @fileOverview Uses Gulpjs to clone a pattern
 *
 *  @author       Scott Nath
 *
 *  @requires  ./lib/utility
 *  @requires  ./lib/clone-pattern
 *  @requires  ./lib/get-options
 */
var utility = require('../utility');
var mergeOptions = require('../get-options').mergeOptions;
var minimist = require('minimist');

/**
 * Function to get default options for an implementation of a clone-pattern task
 *
 * @return {Object}  options  an object of default gulp-gh-pages options
 */
var getDefaultOptions = function () {
  'use strict';

  // default options for ghPages gulp task
  var options = {
    config: {},
    taskName: 'clone-pattern',
    dependencies: [] // gulp tasks which should be run before this task

  };

  return options;
};

var checkForClassArguments = function (args) {
  'use strict';

  if (!args.pattern) {
    console.log('To clone, you must include a pattern flag. example: "--pattern /path/to/pattern/directory"');
    return false;
  }

  if (typeof args.pattern !== 'string') {
    console.log('The path to the pattern-to-clone must be a string.');
    return false;
  }

  return args;

};

/**
 * Gulp task that clones a pattern-library pattern
 *
 * @example
 * // include in gulpfile.js
 * require('pattern-library-utilities').gulpClonePattern(require('gulp'),cloneOptions);
 *
 * @param {Object}  gulp  including file should inject the gulp module
 * @param {Object}  projectOptions  object of options
 *
 */
exports.gulpClonePattern = function (gulp, projectOptions) {
  'use strict';

  var options = mergeOptions(getDefaultOptions(), projectOptions);

  gulp.task(options.taskName, options.dependencies, function () {

    var args = checkForClassArguments(minimist(process.argv.slice(2)));

    if (!args) {
      console.log('Exiting without cloning.');
      return;
    }

    var patternDataFile = utility.testIfSinglePattern(args.pattern);

    if (!patternDataFile) {
      console.log('No patternDataFile, exiting without cloning.');
      return;
    }

    return gulp.src(patternDataFile)
    .pipe(utility.patternCloner(options.config));

  });

};

<commit_msg>example usage<commit_after>/**
 *  @fileOverview Uses Gulpjs to clone a pattern
 *
 *  @author       Scott Nath
 *
 *  @requires  ./lib/utility
 *  @requires  ./lib/clone-pattern
 *  @requires  ./lib/get-options
 */
var utility = require('../utility');
var mergeOptions = require('../get-options').mergeOptions;
var minimist = require('minimist');

/**
 * Function to get default options for an implementation of a clone-pattern task
 *
 * @return {Object}  options  an object of default gulp-gh-pages options
 */
var getDefaultOptions = function () {
  'use strict';

  // default options for ghPages gulp task
  var options = {
    config: {},
    taskName: 'clone-pattern',
    dependencies: [] // gulp tasks which should be run before this task

  };

  return options;
};

var checkForClassArguments = function (args) {
  'use strict';

  if (!args.pattern) {
    console.log('To clone, you must include a pattern flag. example: "--pattern /path/to/pattern/directory"');
    return false;
  }

  if (typeof args.pattern !== 'string') {
    console.log('The path to the pattern-to-clone must be a string.');
    return false;
  }

  return args;

};

/**
 * Gulp task that clones a pattern-library pattern
 *
 * @example
 * // include in gulpfile.js
 * require('pattern-library-utilities').gulpClonePattern(require('gulp'),cloneOptions);
 * // on the command line
 * `$ gulp clone-pattern --pattern node_modules/pattern-library/patterns/molecules/images/logo
 *
 * @param {Object}  gulp  including file should inject the gulp module
 * @param {Object}  projectOptions  object of options
 *
 */
exports.gulpClonePattern = function (gulp, projectOptions) {
  'use strict';

  var options = mergeOptions(getDefaultOptions(), projectOptions);

  gulp.task(options.taskName, options.dependencies, function () {

    var args = checkForClassArguments(minimist(process.argv.slice(2)));

    if (!args) {
      console.log('Exiting without cloning.');
      return;
    }

    var patternDataFile = utility.testIfSinglePattern(args.pattern);

    if (!patternDataFile) {
      console.log('No patternDataFile, exiting without cloning.');
      return;
    }

    return gulp.src(patternDataFile)
    .pipe(utility.patternCloner(options.config));

  });

};

<|endoftext|>


<commit_before>SpaceGame.Main = function(game){
  this._background = null;

  SpaceGame._fireButton = null;
  SpaceGame._brickButton = null;
  SpaceGame._missleButton = null;
  SpaceGame._cursors = null;

  SpaceGame._scoreText = null;
  SpaceGame._lifeGraph = null;
  SpaceGame._fireGraph = null;

  SpaceGame._shipTrail = null;
  SpaceGame._hearts = null;
  SpaceGame._shields = null;
  SpaceGame._bricks = null;
  SpaceGame._walls = null;
  SpaceGame._missles = null;
  SpaceGame._bullets = null;
  SpaceGame._bombs = null;

  SpaceGame._enemy_bullets = null;
  SpaceGame._ufos = null;
};
SpaceGame.Main.prototype = {
  create: function() {
    SpaceGame._newLevelStarted = false;

    game.audio.enemySndFire = game.add.audio('gulp', 2);
    game.audio.playerSndFire = game.add.audio('gunshot', 0.03);
    game.audio.toilSnd = game.add.audio('toil', 0.3);
    game.audio.smackSnd = game.add.audio('smack', 0.3);
    game.audio.laughSnd = game.add.audio('laugh', 0.8);
    game.audio.springSnd = game.add.audio('spring', 0.3);
    game.audio.kissSnd = game.add.audio('kiss', 0.3);
    game.audio.explosionSnd = game.add.audio('explosion', 0.2);
    game.audio.missleSnd = game.add.audio('missle', 0.1);
    game.audio.ufoSnd = [
      game.add.audio('scifi1', 0.6),
      game.add.audio('scifi2', 0.6),
      game.add.audio('scifi3', 0.6),
      game.add.audio('scifi4', 0.3),
      game.add.audio('scifi5', 0.3)
    ];
    game.audio.completedSnd = game.add.audio('completed', 1);

    this._background = game.add.tileSprite(0, 0, 1000, 600, 'background');
    this._background.alpha=0;
    game.add.tween(this._background).to({alpha: 1}, 20000,
      Phaser.Easing.Linear.In,
      true, //autostart?,
      0, //delay,
      false, //repeat?
      true //yoyo?
    );
    //

    SpaceGame._fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    SpaceGame._brickButton = game.input.keyboard.addKey(Phaser.Keyboard.B);
    SpaceGame._missleButton = game.input.keyboard.addKey(Phaser.Keyboard.M);

    /**
     * Init map
     */
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.physics.p2.applyGravity = true;
    game.physics.p2.gravity.x = 0;
    game.physics.p2.gravity.y = 300;

    /*
     * Tower
     */
    towers = game.add.group();
    game.physics.enable(towers, Phaser.Physics.P2JS, debug);
    game.physics.p2.setImpactEvents(true);
    game.camera.follow(towers);

    /*
     * Heart
     */
    SpaceGame._hearts = game.add.group();
    SpaceGame._hearts.createMultiple(1, 'heart');

    /*
     * Shield
     */
    SpaceGame._shields = game.add.group();
    SpaceGame._shields.createMultiple(1, 'shield');

    /*
     * Brick
     */
    SpaceGame._bricks = game.add.group();
    SpaceGame._bricks.createMultiple(1, 'brick');

    /*
     * Wall
     */
    SpaceGame._walls = game.add.group();
    SpaceGame._walls.createMultiple(1, 'wall');

    /*
     * Ufo
     */
    SpaceGame._ufos = game.add.group();
    SpaceGame._ufos.createMultiple(4, 'ufo');

    /*
     * Bombs
     */
    SpaceGame._bombs = game.add.group();
    SpaceGame._bombs.createMultiple(1, 'bomb');

    /*
     * Towers Bullets
     */
    SpaceGame._bullets = game.add.group();
    SpaceGame._bullets.enableBody = true;
    SpaceGame._bullets.physicsBodyType = Phaser.Physics.P2JS;
    SpaceGame._bullets.createMultiple(20, 'bullet');
    SpaceGame._bullets.setAll('checkWorldBounds', true);
    SpaceGame._bullets.setAll('outOfBoundsKill', true);
    SpaceGame._bullets.setAll('collideWorldBounds', false);
    SpaceGame._bullets.setAll('anchor.x', 0.5);
    SpaceGame._bullets.setAll('anchor.y', 1);

    /*
     * Enemy Bullets
     */
    SpaceGame._enemy_bullets = game.add.group();
    SpaceGame._enemy_bullets.enableBody = true;
    SpaceGame._enemy_bullets.physicsBodyType = Phaser.Physics.P2JS;

    SpaceGame._enemy_bullets.createMultiple(40, 'bullet');
    SpaceGame._enemy_bullets.setAll('checkWorldBounds', true);
    SpaceGame._enemy_bullets.setAll('outOfBoundsKill', true);
    SpaceGame._enemy_bullets.setAll('collideWorldBounds', false);
    SpaceGame._enemy_bullets.setAll('anchor.x', 0.5);
    SpaceGame._enemy_bullets.setAll('anchor.y', 1);

    /*
     * Missles
     */
    SpaceGame._missles = game.add.group();
    SpaceGame._missles.enableBody = true;
    SpaceGame._missles.physicsBodyType = Phaser.Physics.P2JS;

    SpaceGame._missles.createMultiple(10, 'missle');
    SpaceGame._missles.setAll('checkWorldBounds', true);
    SpaceGame._missles.setAll('outOfBoundsKill', true);
    SpaceGame._missles.setAll('collideWorldBounds', false);
    SpaceGame._missles.setAll('anchor.x', 0.5);
    SpaceGame._missles.setAll('anchor.y', 1);

    /*
     * Enemy
     */
    enemys = game.add.group();
    enemys.enableBody = true;
    enemys.physicsBodyType = Phaser.Physics.P2JS;
    game.physics.p2.enableBody(enemys, debug);
    game.physics.p2.setBoundsToWorld(true, true, true, true, false);

    nextLevel();

    score -= 10;
    updateScore();
    SpaceGame._cursors = game.input.keyboard.createCursorKeys();
  },

  update: function() {
    if (enemys.countLiving() == 0
      && SpaceGame._allEnemysAdded
      && !SpaceGame._newLevelStarted) {
      SpaceGame._newLevelStarted = true;
      updateScore();
      levelCompleted();
    }
    /*
     *  Enemy
     */
    enemys.forEach(function (enemy) {

      if (enemy && enemy.alive) {
         if (enemy.y > 660) {
          // bottom fall
          var style = {font: "20px Tahoma", fill: "#000000", align: "center"};
          var cRect = game.add.graphics(0, 0)
            .beginFill(0xff5a00)
            .drawCircle(towers.children[0].x, towers.children[0].y, 40);
          var health = game.add.text(towers.children[0].x-10, towers.children[0].y-15, '-' + enemy.health, style);
          var health_tween = game.add.tween(health);
          health_tween.to({opacity: 0.3}, 1000,
            Phaser.Easing.Cubic.NONE,
            true /*autostart?*/,
            100 /*delay*/,
            false /*yoyo?*/);
          //
          health_tween.onLoop.add(function () {
            health.destroy();
            cRect.destroy();
          }, this);

          game.audio.springSnd.play();
          if (towers.children[0].health > enemy.health) {
            towers.children[0].damage(enemy.health);
          }
          else {
            towers.children[0].damage(enemy.health - 1);
          }

          if (towers && towers.children[0]) {
            towers.children[0].fireTime += enemy.health;
          }
          enemy.kill();
          updateScoreText();
        }
      }
    });

    towers.forEachAlive(function (tower) {
      if (tower.alpha < 1) {
        return;
      }

      // Move tower
      tower.body.setZeroVelocity();
      var speed = 100 + game.height - tower.body.y / 1.9;

      if (SpaceGame._cursors.left.isDown) {
        tower.angle = -30;
        if (SpaceGame._cursors.up.isDown) {
          tower.angle = -60;
        }
        tower.body.velocity.x = -speed;
      }
      else if (SpaceGame._cursors.right.isDown) {
        tower.angle = 30;
        if (SpaceGame._cursors.up.isDown) {
          tower.angle = 60;
        }
        tower.body.velocity.x = speed;
      }
      else {
        tower.rotation = 0;
      }
      speed *= 2;
      if (SpaceGame._cursors.up.isDown) {
        tower.body.velocity.y = -speed;
      }
      else if (SpaceGame._cursors.down.isDown) {
        tower.body.velocity.y = speed;
      }
      if (this.game.input.activePointer.isDown) {
        if (this.game.input.activePointer.isMouse) {
          // @todo: In the case of a mouse, check mouse button status?
          if (this.game.input.activePointer.button == Phaser.Mouse.RIGHT_BUTTON) {

          }
        }
        else {
//        if (Math.floor(game.input.x/(game.width/2)) === 0) {
          if (game.input.x < tower.x) {
            tower.angle = -30;
            tower.body.velocity.x = -speed;
          }
//        if (Math.floor(game.input.x/(game.width/2)) === 1) {
          if (game.input.x > tower.x) {
            tower.angle = 30;
            tower.body.velocity.x = speed;
          }
//        if(Math.floor(game.input.y/(game.height/2)) === 0){
          if (game.input.y < tower.y) {
            tower.body.velocity.y = -speed;
          }
//        if(Math.floor(game.input.y/(game.height/2)) === 1){
          if (game.input.y > tower.y) {
            tower.body.velocity.y = speed;
          }
/*          if (game.input.y > 600) {
            Tower.prototype.fire(tower);
          }*/

          // Multiple touches/pointers
          /*if (this.game.input.pointer1.isDown && this.game.input.pointer2.isDown)
           alert(this.game.input.pointer2.isDown);*/
        }
      }
    });
  }
};
<commit_msg>Draw protecting wall when enemy close to fall.<commit_after>SpaceGame.Main = function(game){
  this._background = null;

  SpaceGame._fireButton = null;
  SpaceGame._brickButton = null;
  SpaceGame._missleButton = null;
  SpaceGame._cursors = null;

  SpaceGame._scoreText = null;
  SpaceGame._lifeGraph = null;
  SpaceGame._fireGraph = null;

  SpaceGame._shipTrail = null;
  SpaceGame._hearts = null;
  SpaceGame._shields = null;
  SpaceGame._bricks = null;
  SpaceGame._walls = null;
  SpaceGame._missles = null;
  SpaceGame._bullets = null;
  SpaceGame._bombs = null;

  SpaceGame._enemy_bullets = null;
  SpaceGame._ufos = null;
};
SpaceGame.Main.prototype = {
  create: function() {
    SpaceGame._newLevelStarted = false;

    game.audio.enemySndFire = game.add.audio('gulp', 2);
    game.audio.playerSndFire = game.add.audio('gunshot', 0.03);
    game.audio.toilSnd = game.add.audio('toil', 0.3);
    game.audio.smackSnd = game.add.audio('smack', 0.3);
    game.audio.laughSnd = game.add.audio('laugh', 0.8);
    game.audio.springSnd = game.add.audio('spring', 0.3);
    game.audio.kissSnd = game.add.audio('kiss', 0.3);
    game.audio.explosionSnd = game.add.audio('explosion', 0.2);
    game.audio.missleSnd = game.add.audio('missle', 0.1);
    game.audio.ufoSnd = [
      game.add.audio('scifi1', 0.6),
      game.add.audio('scifi2', 0.6),
      game.add.audio('scifi3', 0.6),
      game.add.audio('scifi4', 0.3),
      game.add.audio('scifi5', 0.3)
    ];
    game.audio.completedSnd = game.add.audio('completed', 1);

    this._background = game.add.tileSprite(0, 0, 1000, 600, 'background');
    this._background.alpha=0;
    game.add.tween(this._background).to({alpha: 1}, 20000,
      Phaser.Easing.Linear.In,
      true, //autostart?,
      0, //delay,
      false, //repeat?
      true //yoyo?
    );
    //

    SpaceGame._fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    SpaceGame._brickButton = game.input.keyboard.addKey(Phaser.Keyboard.B);
    SpaceGame._missleButton = game.input.keyboard.addKey(Phaser.Keyboard.M);

    /**
     * Init map
     */
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.physics.p2.applyGravity = true;
    game.physics.p2.gravity.x = 0;
    game.physics.p2.gravity.y = 300;

    /*
     * Tower
     */
    towers = game.add.group();
    game.physics.enable(towers, Phaser.Physics.P2JS, debug);
    game.physics.p2.setImpactEvents(true);
    game.camera.follow(towers);

    /*
     * Heart
     */
    SpaceGame._hearts = game.add.group();
    SpaceGame._hearts.createMultiple(1, 'heart');

    /*
     * Shield
     */
    SpaceGame._shields = game.add.group();
    SpaceGame._shields.createMultiple(1, 'shield');

    /*
     * Brick
     */
    SpaceGame._bricks = game.add.group();
    SpaceGame._bricks.createMultiple(1, 'brick');

    /*
     * Wall
     */
    SpaceGame._walls = game.add.group();
    SpaceGame._walls.createMultiple(1, 'wall');

    /*
     * Ufo
     */
    SpaceGame._ufos = game.add.group();
    SpaceGame._ufos.createMultiple(4, 'ufo');

    /*
     * Bombs
     */
    SpaceGame._bombs = game.add.group();
    SpaceGame._bombs.createMultiple(1, 'bomb');

    /*
     * Towers Bullets
     */
    SpaceGame._bullets = game.add.group();
    SpaceGame._bullets.enableBody = true;
    SpaceGame._bullets.physicsBodyType = Phaser.Physics.P2JS;
    SpaceGame._bullets.createMultiple(20, 'bullet');
    SpaceGame._bullets.setAll('checkWorldBounds', true);
    SpaceGame._bullets.setAll('outOfBoundsKill', true);
    SpaceGame._bullets.setAll('collideWorldBounds', false);
    SpaceGame._bullets.setAll('anchor.x', 0.5);
    SpaceGame._bullets.setAll('anchor.y', 1);

    /*
     * Enemy Bullets
     */
    SpaceGame._enemy_bullets = game.add.group();
    SpaceGame._enemy_bullets.enableBody = true;
    SpaceGame._enemy_bullets.physicsBodyType = Phaser.Physics.P2JS;

    SpaceGame._enemy_bullets.createMultiple(40, 'bullet');
    SpaceGame._enemy_bullets.setAll('checkWorldBounds', true);
    SpaceGame._enemy_bullets.setAll('outOfBoundsKill', true);
    SpaceGame._enemy_bullets.setAll('collideWorldBounds', false);
    SpaceGame._enemy_bullets.setAll('anchor.x', 0.5);
    SpaceGame._enemy_bullets.setAll('anchor.y', 1);

    /*
     * Missles
     */
    SpaceGame._missles = game.add.group();
    SpaceGame._missles.enableBody = true;
    SpaceGame._missles.physicsBodyType = Phaser.Physics.P2JS;

    SpaceGame._missles.createMultiple(10, 'missle');
    SpaceGame._missles.setAll('checkWorldBounds', true);
    SpaceGame._missles.setAll('outOfBoundsKill', true);
    SpaceGame._missles.setAll('collideWorldBounds', false);
    SpaceGame._missles.setAll('anchor.x', 0.5);
    SpaceGame._missles.setAll('anchor.y', 1);

    /*
     * Enemy
     */
    enemys = game.add.group();
    enemys.enableBody = true;
    enemys.physicsBodyType = Phaser.Physics.P2JS;
    game.physics.p2.enableBody(enemys, debug);
    game.physics.p2.setBoundsToWorld(true, true, true, true, false);

    nextLevel();

    score -= 10;
    updateScore();
    SpaceGame._cursors = game.input.keyboard.createCursorKeys();
  },

  update: function() {
    if (enemys.countLiving() == 0
      && SpaceGame._allEnemysAdded
      && !SpaceGame._newLevelStarted) {
      SpaceGame._newLevelStarted = true;
      updateScore();
      levelCompleted();
    }
    /*
     *  Enemy
     */
    enemys.forEach(function (enemy) {

      if (enemy && enemy.alive) {
        if (enemy.y > 500 && towers.children[0].countBricks > 0) {
          // protect with wall
          towers.children[0].countBricks--;
          new Wall(enemy.x, enemy.y+enemy.height);
          updateScoreText();
        }
         if (enemy.y > 660) {
          // bottom fall
          var style = {font: "20px Tahoma", fill: "#000000", align: "center"};
          var cRect = game.add.graphics(0, 0)
            .beginFill(0xff5a00)
            .drawCircle(towers.children[0].x, towers.children[0].y, 40);
          var health = game.add.text(towers.children[0].x-10, towers.children[0].y-15, '-' + enemy.health, style);
          var health_tween = game.add.tween(health);
          health_tween.to({opacity: 0.3}, 1000,
            Phaser.Easing.Cubic.NONE,
            true /*autostart?*/,
            100 /*delay*/,
            false /*yoyo?*/);
          //
          health_tween.onLoop.add(function () {
            health.destroy();
            cRect.destroy();
          }, this);

          game.audio.springSnd.play();
          if (towers.children[0].health > enemy.health) {
            towers.children[0].damage(enemy.health);
          }
          else {
            towers.children[0].damage(enemy.health - 1);
          }

          if (towers && towers.children[0]) {
            towers.children[0].fireTime += enemy.health;
          }
          enemy.kill();
          updateScoreText();
        }
      }
    });

    towers.forEachAlive(function (tower) {
      if (tower.alpha < 1) {
        return;
      }

      // Move tower
      tower.body.setZeroVelocity();
      var speed = 100 + game.height - tower.body.y / 1.9;

      if (SpaceGame._cursors.left.isDown) {
        tower.angle = -30;
        if (SpaceGame._cursors.up.isDown) {
          tower.angle = -60;
        }
        tower.body.velocity.x = -speed;
      }
      else if (SpaceGame._cursors.right.isDown) {
        tower.angle = 30;
        if (SpaceGame._cursors.up.isDown) {
          tower.angle = 60;
        }
        tower.body.velocity.x = speed;
      }
      else {
        tower.rotation = 0;
      }
      speed *= 2;
      if (SpaceGame._cursors.up.isDown) {
        tower.body.velocity.y = -speed;
      }
      else if (SpaceGame._cursors.down.isDown) {
        tower.body.velocity.y = speed;
      }
      if (this.game.input.activePointer.isDown) {
        if (this.game.input.activePointer.isMouse) {
          // @todo: In the case of a mouse, check mouse button status?
          if (this.game.input.activePointer.button == Phaser.Mouse.RIGHT_BUTTON) {

          }
        }
        else {
//        if (Math.floor(game.input.x/(game.width/2)) === 0) {
          if (game.input.x < tower.x) {
            tower.angle = -30;
            tower.body.velocity.x = -speed;
          }
//        if (Math.floor(game.input.x/(game.width/2)) === 1) {
          if (game.input.x > tower.x) {
            tower.angle = 30;
            tower.body.velocity.x = speed;
          }
//        if(Math.floor(game.input.y/(game.height/2)) === 0){
          if (game.input.y < tower.y) {
            tower.body.velocity.y = -speed;
          }
//        if(Math.floor(game.input.y/(game.height/2)) === 1){
          if (game.input.y > tower.y) {
            tower.body.velocity.y = speed;
          }
/*          if (game.input.y > 600) {
            Tower.prototype.fire(tower);
          }*/

          // Multiple touches/pointers
          /*if (this.game.input.pointer1.isDown && this.game.input.pointer2.isDown)
           alert(this.game.input.pointer2.isDown);*/
        }
      }
    });
  }
};
<|endoftext|>


<commit_before>var logUtil = require('./logUtil');
var linesUtil = require('./linesUtil');
var config = require('./config');

var loggingFunctions = [];
Object.keys(config._logLevels).forEach(function(logLevel) {

	loggingFunctions.push({
		logFunction: logLevel === 'trace' ? logUtil.logTraceWithColor : logUtil.logWithColor,
		level: config._logLevels[logLevel].level,
		functionName: config._logLevels[logLevel].letter,
		color: config._types.log === 0 ? config.colors.logs[logLevel] : config.colors.lines[logLevel],
		type: config._types.log
	});
	loggingFunctions.push({
		logFunction: logLevel === 'trace' ? linesUtil.logLineWithTrace : linesUtil.logLine,
		level: config._logLevels[logLevel].level,
		functionName: config._logLevels[logLevel].letter + 'line',
		color: config._types.log === 0 ? config.colors.logs[logLevel] : config.colors.lines[logLevel],
		type: config._types.line
	});
});

//lines have an extra default function
loggingFunctions.push({
	logFunction: linesUtil.logLine,
	level: config._logLevels.default.level,
	functionName: 'line',
	color: config.colors.lines.default,
	type: config._types.line
});

module.exports = loggingFunctions;
<commit_msg>Fixing the bug with line colors<commit_after>var logUtil = require('./logUtil');
var linesUtil = require('./linesUtil');
var config = require('./config');

var loggingFunctions = [];
Object.keys(config._logLevels).forEach(function(logLevel) {

	loggingFunctions.push({
		logFunction: logLevel === 'trace' ? logUtil.logTraceWithColor : logUtil.logWithColor,
		level: config._logLevels[logLevel].level,
		functionName: config._logLevels[logLevel].letter,
		color: config.colors.logs[logLevel],
		type: config._types.log
	});
	loggingFunctions.push({
		logFunction: logLevel === 'trace' ? linesUtil.logLineWithTrace : linesUtil.logLine,
		level: config._logLevels[logLevel].level,
		functionName: config._logLevels[logLevel].letter + 'line',
		color: config.colors.lines[logLevel],
		type: config._types.line
	});
});

//lines have an extra default function
loggingFunctions.push({
	logFunction: linesUtil.logLine,
	level: config._logLevels.default.level,
	functionName: 'line',
	color: config.colors.lines.default,
	type: config._types.line
});

module.exports = loggingFunctions;
<|endoftext|>


<commit_before>var app = angular.module('nbaRoutes');

app.service('teamService', function($http, $q){

this.addNewGame = function(gameObj){
		var url = 'https://api.parse.com/1/classes/' + gameObj.homeTeam;

		parseInt(gameObj.homeTeamScore);
		parseInt(gameObj.opponentScore);

		if(gameObj.homeTeamScore > gameObj.opponentScore){
			gameObj.won = true;
		}else{
			gameObj.won = false;
		}
		$http.post('url', data)
			return data;
		}

this.getTeamData = function(team){
		var deferred = $q.defer()
		var url = 'https://api.parse.com/1/classes/' + team;
		$http.get('url')
		.then(function(data){
			var results = data.data.results
			var wins = 0;
			var losses = 0;
			results.forEach(input, function(){
				if(data.data.won === true){
					deferred.resolve(wins++);
				}else {
					deferred.reject(losses++);
				}
				results.wins = wins;
				results.losses = losses;
			})
		})
		return deferred.promise
	}
});
<commit_msg>Service adjustments<commit_after>var app = angular.module('nbaRoutes');

app.service('teamService', function($http, $q){

this.addNewGame = function(gameObj){
		var url = 'https://api.parse.com/1/classes/' + gameObj.homeTeam;

		parseInt(gameObj.homeTeamScore);
		parseInt(gameObj.opponentScore);

		if(gameObj.homeTeamScore > gameObj.opponentScore){
			gameObj.won = true;
		}else{
			gameObj.won = false;
		}
		$http.post('url', data)
			return data;
		}

this.getTeamData = function(team){
		var deferred = $q.defer()
		var url = 'https://api.parse.com/1/classes/' + team;
		$http.get('url')
		.then(function(data){
			var results = data.data.results
			var wins = 0;
			var losses = 0;
			results.forEach(input, function(){
				if(data.data.won === true){
					deferred.resolve(wins++);
				}else {
					deferred.reject(losses++);
				}
				results.wins = wins;
				results.losses = losses;
			})
		})
		console.log (this.getTeamData)
		return this.getTeamData
		return deferred.promise
	}

});
<|endoftext|>


<commit_before>'use strict';

module.exports = require('lib/Agito');
<commit_msg>fix: index.js wrapper<commit_after>'use strict';

module.exports = require('./lib/Agito');
<|endoftext|>


<commit_before>var Steam = require('../steam_client');
var SteamID = require('../steamID');

var EMsg = Steam.EMsg;
var schema = Steam.Internal;

var protoMask = 0x80000000;

// Methods

var prototype = Steam.SteamClient.prototype;

prototype.setPersonaName = function(name) {
  this._send(EMsg.ClientChangeStatus | protoMask, schema.CMsgClientChangeStatus.serialize({
    personaState: this._personaState,
    playerName: name
  }));
};

prototype.setPersonaState = function(state) {
  this._personaState = state;
  this._send(EMsg.ClientChangeStatus | protoMask, schema.CMsgClientChangeStatus.serialize({
    personaState: state
  }));
};

prototype.sendMessage = function(target, message, type) {
  target = new SteamID(target);
  type = type || Steam.EChatEntryType.ChatMsg;

  var payload = new Buffer(Buffer.byteLength(message) + 1);
  payload.writeCString(message);

  if (target.accountType == Steam.EAccountType.Individual || target.accountType == Steam.EAccountType.ConsoleUser) {
    this._send(EMsg.ClientFriendMsg | protoMask, schema.CMsgClientFriendMsg.serialize({
      steamid: target.toString(),
      message: payload,
      chatEntryType: type
    }));

  } else {
    // assume chat message
    var chatMsg = schema.MsgClientChatMsg.serialize({
      steamIdChatter: this.steamID,
      steamIdChatRoom: toChatID(target),
      chatMsgType: type
    });

    this._send(EMsg.ClientChatMsg, Buffer.concat([chatMsg, payload]));
  }
};

prototype.addFriend = function(steamID) {
  this._send(EMsg.ClientAddFriend | protoMask, schema.CMsgClientAddFriend.serialize({
    steamidToAdd: steamID
  }));
};

prototype.removeFriend = function(steamID) {
  this._send(EMsg.ClientRemoveFriend | protoMask, schema.CMsgClientRemoveFriend.serialize({
    friendid: steamID
  }));
};

prototype.joinChat = function(steamID) {
  this._send(EMsg.ClientJoinChat, schema.MsgClientJoinChat.serialize({
    steamIdChat: toChatID(steamID)
  }));
};

prototype.lockChat = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.LockChat
  }));
};

prototype.unlockChat = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.UnlockChat
  }));
};

prototype.setModerated = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.SetModerated
  }));
};

prototype.setUnmoderated = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.SetUnmoderated
  }));
};

prototype.kick = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.Kick
  }));
};

prototype.ban = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.Ban
  }));
};

prototype.unban = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.UnBan
  }));
};

// Handlers

var handlers = prototype._handlers;

handlers[EMsg.ClientPersonaState] = function(data) {
  var friend = schema.CMsgClientPersonaState.parse(data).friends[0];

  this.emit('personaState', friend);

  this.users[friend.friendid] = friend;
};

handlers[EMsg.ClientFriendsList] = function(data) {
  var list = schema.CMsgClientFriendsList.parse(data);

  if (!list.bincremental) {
    return; //TODO
  }

  this.emit('relationship', list.friends[0].ulfriendid, list.friends[0].efriendrelationship);
};

handlers[EMsg.ClientFriendMsgIncoming] = function(data) {
  var friendMsg = schema.CMsgClientFriendMsgIncoming.parse(data);

  // Steam cuts off after the first null
  var message = friendMsg.message.toString().split('\u0000')[0];

  this.emit('message', friendMsg.steamidFrom, message, friendMsg.chatEntryType);
  this.emit('friendMsg', friendMsg.steamidFrom, message, friendMsg.chatEntryType);
};

handlers[EMsg.ClientChatMsg] = function(data) {
  var chatMsg = schema.MsgClientChatMsg.parse(data);

  // Steam cuts off after the first null
  var message = data.slice(schema.MsgClientChatMsg.baseSize).toString().split('\u0000')[0];

  this.emit('message', toClanID(chatMsg.steamIdChatRoom), message, chatMsg.chatMsgType, chatMsg.steamIdChatter);
  this.emit('chatMsg', toClanID(chatMsg.steamIdChatRoom), message, chatMsg.chatMsgType, chatMsg.steamIdChatter);
};

handlers[EMsg.ClientChatEnter] = function(data) {
  var chatEnter = schema.MsgClientChatEnter.parse(data);
  var baseSize = schema.MsgClientChatEnter.baseSize;

  var numObj = data.readUInt32LE(baseSize);
  var chatName = data.readCString(baseSize + 4);
  data = data.slice(baseSize + 4 + Buffer.byteLength(chatName) + 1);

  var chatRoom = this.chatRooms[chatEnter.steamIdClan || chatEnter.steamIdChat] = {};
  while (numObj--) {
    var object = require('../VDF').parse(data).MessageObject;
    chatRoom[object.steamid] = {
      rank: object.Details,
      permissions: object.Permissions
    };
  }
};

handlers[EMsg.ClientChatMemberInfo] = function(data) {
  var membInfo = schema.MsgClientChatMemberInfo.parse(data);
  var clanID = toClanID(membInfo.steamIdChat);

  var payload = data.slice(schema.MsgClientChatMemberInfo.baseSize);

  if (membInfo.type == Steam.EChatInfoType.StateChange) {
    var chatterActedOn = payload.readUInt64LE(0);
    var stateChange = payload.readInt32LE(8);
    var chatterActedBy = payload.readUInt64LE(12);
    this.emit('chatStateChange', stateChange, chatterActedOn, clanID, chatterActedBy);
    payload = payload.slice(20);
  }

  if (membInfo.type == Steam.EChatInfoType.InfoUpdate || stateChange == Steam.EChatMemberStateChange.Entered) {
    var object = require('../VDF').parse(payload).MessageObject;
    this.chatRooms[clanID][object.steamid] = {
      rank: object.Details,
      permissions: object.Permissions
    };
  } else {
    delete this.chatRooms[clanID][chatterActedOn];
  }
};

handlers[EMsg.ClientChatInvite] = function(data) {
  var chatInvite = schema.CMsgClientChatInvite.parse(data);
  this.emit('chatInvite', toClanID(chatInvite.steamIdChat), chatInvite.chatName, chatInvite.steamIdPatron);
};

handlers[EMsg.ClientClanState] = function(data) {
  var clanState = schema.CMsgClientClanState.parse(data);
  if (clanState.announcements)
    this.emit('announcement', clanState.steamidClan, clanState.announcements[0].headline); // TODO: more data
};

// Private functions

function toChatID(steamID) {
  if (typeof steamID == 'string')
    steamID = new SteamID(steamID);

  if (steamID.accountType == Steam.EAccountType.Clan) {
    // this is a ClanID - convert to its respective ChatID
    steamID.accountInstance = SteamID.ChatInstanceFlags.Clan;
    steamID.accountType = Steam.EAccountType.Chat;
  }

  return steamID.toString();
}

function toClanID(steamID) {
  if (typeof steamID == 'string')
    steamID = new SteamID(steamID);

  if (steamID.accountInstance == SteamID.ChatInstanceFlags.Clan) {
    // not an anonymous chat - convert to its respective ClanID
    steamID.accountType = Steam.EAccountType.Clan;
    steamID.accountInstance = 0;
  }

  return steamID.toString();
}
<commit_msg>Support multiple friends in ClientPersonaState<commit_after>var Steam = require('../steam_client');
var SteamID = require('../steamID');

var EMsg = Steam.EMsg;
var schema = Steam.Internal;

var protoMask = 0x80000000;

// Methods

var prototype = Steam.SteamClient.prototype;

prototype.setPersonaName = function(name) {
  this._send(EMsg.ClientChangeStatus | protoMask, schema.CMsgClientChangeStatus.serialize({
    personaState: this._personaState,
    playerName: name
  }));
};

prototype.setPersonaState = function(state) {
  this._personaState = state;
  this._send(EMsg.ClientChangeStatus | protoMask, schema.CMsgClientChangeStatus.serialize({
    personaState: state
  }));
};

prototype.sendMessage = function(target, message, type) {
  target = new SteamID(target);
  type = type || Steam.EChatEntryType.ChatMsg;

  var payload = new Buffer(Buffer.byteLength(message) + 1);
  payload.writeCString(message);

  if (target.accountType == Steam.EAccountType.Individual || target.accountType == Steam.EAccountType.ConsoleUser) {
    this._send(EMsg.ClientFriendMsg | protoMask, schema.CMsgClientFriendMsg.serialize({
      steamid: target.toString(),
      message: payload,
      chatEntryType: type
    }));

  } else {
    // assume chat message
    var chatMsg = schema.MsgClientChatMsg.serialize({
      steamIdChatter: this.steamID,
      steamIdChatRoom: toChatID(target),
      chatMsgType: type
    });

    this._send(EMsg.ClientChatMsg, Buffer.concat([chatMsg, payload]));
  }
};

prototype.addFriend = function(steamID) {
  this._send(EMsg.ClientAddFriend | protoMask, schema.CMsgClientAddFriend.serialize({
    steamidToAdd: steamID
  }));
};

prototype.removeFriend = function(steamID) {
  this._send(EMsg.ClientRemoveFriend | protoMask, schema.CMsgClientRemoveFriend.serialize({
    friendid: steamID
  }));
};

prototype.joinChat = function(steamID) {
  this._send(EMsg.ClientJoinChat, schema.MsgClientJoinChat.serialize({
    steamIdChat: toChatID(steamID)
  }));
};

prototype.lockChat = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.LockChat
  }));
};

prototype.unlockChat = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.UnlockChat
  }));
};

prototype.setModerated = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.SetModerated
  }));
};

prototype.setUnmoderated = function(steamID) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamID),
    steamIdUserToActOn: toChatID(steamID),
    chatAction: Steam.EChatAction.SetUnmoderated
  }));
};

prototype.kick = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.Kick
  }));
};

prototype.ban = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.Ban
  }));
};

prototype.unban = function(steamIdChat, steamIdMember) {
  this._send(EMsg.ClientChatAction, schema.MsgClientChatAction.serialize({
    steamIdChat: toChatID(steamIdChat),
    steamIdUserToActOn: steamIdMember,
    chatAction: Steam.EChatAction.UnBan
  }));
};

// Handlers

var handlers = prototype._handlers;

handlers[EMsg.ClientPersonaState] = function(data) {
  schema.CMsgClientPersonaState.parse(data).friends.forEach(function(friend) {
    this.emit('personaState', friend);
    this.users[friend.friendid] = friend;
  }.bind(this));
};

handlers[EMsg.ClientFriendsList] = function(data) {
  var list = schema.CMsgClientFriendsList.parse(data);

  if (!list.bincremental) {
    return; //TODO
  }

  this.emit('relationship', list.friends[0].ulfriendid, list.friends[0].efriendrelationship);
};

handlers[EMsg.ClientFriendMsgIncoming] = function(data) {
  var friendMsg = schema.CMsgClientFriendMsgIncoming.parse(data);

  // Steam cuts off after the first null
  var message = friendMsg.message.toString().split('\u0000')[0];

  this.emit('message', friendMsg.steamidFrom, message, friendMsg.chatEntryType);
  this.emit('friendMsg', friendMsg.steamidFrom, message, friendMsg.chatEntryType);
};

handlers[EMsg.ClientChatMsg] = function(data) {
  var chatMsg = schema.MsgClientChatMsg.parse(data);

  // Steam cuts off after the first null
  var message = data.slice(schema.MsgClientChatMsg.baseSize).toString().split('\u0000')[0];

  this.emit('message', toClanID(chatMsg.steamIdChatRoom), message, chatMsg.chatMsgType, chatMsg.steamIdChatter);
  this.emit('chatMsg', toClanID(chatMsg.steamIdChatRoom), message, chatMsg.chatMsgType, chatMsg.steamIdChatter);
};

handlers[EMsg.ClientChatEnter] = function(data) {
  var chatEnter = schema.MsgClientChatEnter.parse(data);
  var baseSize = schema.MsgClientChatEnter.baseSize;

  var numObj = data.readUInt32LE(baseSize);
  var chatName = data.readCString(baseSize + 4);
  data = data.slice(baseSize + 4 + Buffer.byteLength(chatName) + 1);

  var chatRoom = this.chatRooms[chatEnter.steamIdClan || chatEnter.steamIdChat] = {};
  while (numObj--) {
    var object = require('../VDF').parse(data).MessageObject;
    chatRoom[object.steamid] = {
      rank: object.Details,
      permissions: object.Permissions
    };
  }
};

handlers[EMsg.ClientChatMemberInfo] = function(data) {
  var membInfo = schema.MsgClientChatMemberInfo.parse(data);
  var clanID = toClanID(membInfo.steamIdChat);

  var payload = data.slice(schema.MsgClientChatMemberInfo.baseSize);

  if (membInfo.type == Steam.EChatInfoType.StateChange) {
    var chatterActedOn = payload.readUInt64LE(0);
    var stateChange = payload.readInt32LE(8);
    var chatterActedBy = payload.readUInt64LE(12);
    this.emit('chatStateChange', stateChange, chatterActedOn, clanID, chatterActedBy);
    payload = payload.slice(20);
  }

  if (membInfo.type == Steam.EChatInfoType.InfoUpdate || stateChange == Steam.EChatMemberStateChange.Entered) {
    var object = require('../VDF').parse(payload).MessageObject;
    this.chatRooms[clanID][object.steamid] = {
      rank: object.Details,
      permissions: object.Permissions
    };
  } else {
    delete this.chatRooms[clanID][chatterActedOn];
  }
};

handlers[EMsg.ClientChatInvite] = function(data) {
  var chatInvite = schema.CMsgClientChatInvite.parse(data);
  this.emit('chatInvite', toClanID(chatInvite.steamIdChat), chatInvite.chatName, chatInvite.steamIdPatron);
};

handlers[EMsg.ClientClanState] = function(data) {
  var clanState = schema.CMsgClientClanState.parse(data);
  if (clanState.announcements)
    this.emit('announcement', clanState.steamidClan, clanState.announcements[0].headline); // TODO: more data
};

// Private functions

function toChatID(steamID) {
  if (typeof steamID == 'string')
    steamID = new SteamID(steamID);

  if (steamID.accountType == Steam.EAccountType.Clan) {
    // this is a ClanID - convert to its respective ChatID
    steamID.accountInstance = SteamID.ChatInstanceFlags.Clan;
    steamID.accountType = Steam.EAccountType.Chat;
  }

  return steamID.toString();
}

function toClanID(steamID) {
  if (typeof steamID == 'string')
    steamID = new SteamID(steamID);

  if (steamID.accountInstance == SteamID.ChatInstanceFlags.Clan) {
    // not an anonymous chat - convert to its respective ClanID
    steamID.accountType = Steam.EAccountType.Clan;
    steamID.accountInstance = 0;
  }

  return steamID.toString();
}
<|endoftext|>


<commit_before>import server from './fakeServer';

/**
 * Fake XMLHttpRequest wrapper with a syntax similar to the much used request.js
 * @type {Object}
 */
var fakeRequest = {
  /**
   * Pretends to post to a remote server with fake network latency
   * @param  {string}    endpoint The endpoint of the server that should be contacted
   * @param  {?object}   data     The data that should be transferred to the server
   * @param  {?function} callback Called after the server successfully did it's thing
   */
  post(endpoint, data, callback) {
    // Delay the call by a random amount between 100ms and 2000ms
    // to simulate network latency
    setTimeout(() => {
      switch (endpoint) {
        case '/login':
          server.login(data.username, data.password, callback);
          break;
        case '/register':
          server.register(data.username, data.password, callback);
          break;
        case '/logout':
          server.logout(callback);
          break;
        default:
          break;
      }
    }, (Math.random() * 2000) + 100);
  }
}

module.exports = fakeRequest;
<commit_msg>Others#, remove timeout.<commit_after>import server from './fakeServer';

/**
 * Fake XMLHttpRequest wrapper with a syntax similar to the much used request.js
 * @type {Object}
 */
var fakeRequest = {
  /**
   * Pretends to post to a remote server with fake network latency
   * @param  {string}    endpoint The endpoint of the server that should be contacted
   * @param  {?object}   data     The data that should be transferred to the server
   * @param  {?function} callback Called after the server successfully did it's thing
   */
  post(endpoint, data, callback) {
    // to simulate network latency
    switch (endpoint) {
      case '/login':
        server.login(data.username, data.password, callback);
        break;
      case '/register':
        server.register(data.username, data.password, callback);
        break;
      case '/logout':
        server.logout(callback);
        break;
      default:
        break;
      }
  }
}

module.exports = fakeRequest;
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');

var url = 'http://marine.weather.gov/MapClick.php?zoneid=LSZ162';
var ifttt_key = 'XXXXXXXXXXXXXXXXXXXXX';

var score  = 0;
var thresh = 6;
var pWave = 0;
var windDirections = ['North', 'Northeast', 'East'];
var hasSent = fs.readFileSync('./email.txt', 'utf-8'); //store the email sender boolean...

//reenable the email boolean checker.
var now = new Date(); //stupid date thing.
if (now.getHours() == 23){
	//if 11pm then set to false....
	fs.writeFileSync('./email.txt','false');
	// process.exit(); //kill the script
}

request(url, function(error, resp, body){

$ = cheerio.load(body);

$('.row-forecast .forecast-text', $('#detailed-forecast-body')).each(function(i,element){

	var forecast = $(element).text();

	var parts = forecast.split(" "); //get the direction and windspeed parts
	var direction = parts[0];
	var lowSpeed = parts[2];
	var waves = forecast.match(/\d to \d feet/g);

	// console.log(direction,lowSpeed);

	if( windDirections.indexOf(direction) != -1){
		//its the right direction
		score ++;  //add one point

		if(lowSpeed >= 15){
			score++; // add 2 points
		}
		if( lowSpeed >= 20){
			score ++; //add 3 points
		}

		if(lowSpeed >= 25){
			score ++; //add 4 points
		}

		if( windDirections.indexOf(direction) == 1){
			//if wind is NE add another point
			score ++; // add 2 points
		}

		if(waves){
			for(var i = 0; i < waves.length; i++){
				var waveHeight = waves[i].split(" ")[0];

				//store the highest waveHeight to send in the email
				if(waveHeight > pWave){
					pWave = waveHeight;
				}

				if(waveHeight >= 3){
					score ++; // +1
				}

				if(waveHeight >= 5){
					score ++; // +2
				}

				if(waveHeight >= 7){
					score ++; // +3
				}

				if(waveHeight >= 10){
					score ++; // +4
				}

				if(waveHeight >= 15){
					score = 9999; //high score dude.
				}

			} //
		} //if waves

	}

});

console.log("score: "+score);
// console.log(hasSent);

if (score > thresh){
	if (hasSent == 'false'){
		//send email using ifttttttttttttt
		console.log("working?");
		request.post('https://maker.ifttt.com/trigger/surf/with/key/' + ifttt_key, {form:{ "value1" : url, "value2" : pWave, "value3" : score }}, function(error, response, body) {
      		console.log('Body response was ', body);
      		console.log('Error was ', error);

      		if(error == null){
      			//if there were no errors, the email sent, set the hasSent to true so we only get 1 email today.
						console.log("email was sent");
      			fs.writeFile('./email.txt','true');
      		}
   		});
	}

}else{
	console.log("score is not high enough to take action");
}

})

/*
//Example Forecast

Late This AfternoonNorthwest winds 10 to 20 knots. Waves 1 to 3 feet.
TonightNorthwest winds 10 to 20 knots becoming north 5 to 15 knots after midnight. Waves subsiding to calm to 2 feet.
TuesdayEast winds 5 to 15 knots becoming southeast 10 to 20 knots in the afternoon. Waves calm to 2 feet.
Tuesday NightSoutheast winds 15 to 25 knots veering south after midnight. Waves building to 2 to 4 feet.
WednesdaySouth winds 10 to 20 knots veering southwest in the afternoon. A slight chance of snow in the morning. A chance of rain. Waves subsiding to calm to 2 feet.
Wednesday NightNorthwest winds 10 to 20 knots becoming north 15 to 25 knots after midnight. A chance of rain...possibly mixed with snow. Waves calm to 2 feet.
ThursdayNorth winds 15 to 25 knots diminishing to 10 to 20 knots in the afternoon. Waves building to 1 to 3 feet...then subsiding to calm to 2 feet.
Thursday NightNorth winds 10 to 20 knots increasing to 15 to 25 knots after midnight. Waves building to 1 to 3 feet.
FridayNorth winds 10 to 20 knots backing west. Waves subsiding to calm to 2 feet.
SaturdayWest winds 15 to 25 knots diminishing to 10 to 20 knots. Waves building to 3 to 5 feet...then subsiding to 1 to 3 feet.

 */
<commit_msg>update header<commit_after>var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');

// var url = 'http://marine.weather.gov/MapClick.php?zoneid=LSZ162';
var ifttt_key = '';

var score  = 0;
var thresh = 6;
var pWave = 0;
var windDirections = ['North', 'Northeast', 'East'];
var hasSent = fs.readFileSync('./email.txt', 'utf-8'); //store the email sender boolean...

var options = {
  url: 'http://marine.weather.gov/MapClick.php?zoneid=LSZ162',
  headers: {
    'User-Agent': 'request'
  }
};

// //reenable the email boolean checker.
// var now = new Date(); //stupid date thing.
// if (now.getHours() == 23){
// 	//if 11pm then set to false....
// 	fs.writeFileSync('./email.txt','false');
// 	// process.exit(); //kill the script
// }

request(options, function(error, resp, body){

$ = cheerio.load(body);
// console.log(body)

$('.row-forecast .forecast-text', $('#detailed-forecast-body')).each(function(i,element){

	var forecast = $(element).text();

	var parts = forecast.split(" "); //get the direction and windspeed parts
	var direction = parts[0];
	var lowSpeed = parts[2];
	var waves = forecast.match(/\d to \d feet/g);

	// console.log(direction,lowSpeed);

	if( windDirections.indexOf(direction) != -1){
		//its the right direction
		score ++;  //add one point

		if(lowSpeed >= 15){
			score++; // add 2 points
		}
		if( lowSpeed >= 20){
			score ++; //add 3 points
		}

		if(lowSpeed >= 25){
			score ++; //add 4 points
		}

		if( windDirections.indexOf(direction) == 1){
			//if wind is NE add another point
			score ++; // add 2 points
		}

		if(waves){
			for(var i = 0; i < waves.length; i++){
				var waveHeight = waves[i].split(" ")[0];

				//store the highest waveHeight to send in the email
				if(waveHeight > pWave){
					pWave = waveHeight;
				}

				if(waveHeight >= 3){
					score ++; // +1
				}

				if(waveHeight >= 5){
					score ++; // +2
				}

				if(waveHeight >= 7){
					score ++; // +3
				}

				if(waveHeight >= 10){
					score ++; // +4
				}

				if(waveHeight >= 15){
					score = 9999; //high score dude.
				}

			} //
		} //if waves

	}

});

console.log("score: "+score);
// console.log(hasSent);

if (score > thresh){
	// if (hasSent == 'false'){
		//send email using ifttttttttttttt
		console.log("working?");
		request.post('https://maker.ifttt.com/trigger/surf/with/key/' + ifttt_key, {form:{ "value1" :"http://forecast.benmoren.com", "value2" : pWave, "value3" : score }}, function(error, response, body) {
      		console.log('Body response was ', body);
      		console.log('Error was ', error);

      		if(error == null){
      			//if there were no errors, the email sent, set the hasSent to true so we only get 1 email today.
						console.log("email was sent");
      			// fs.writeFile('./email.txt','true');
      		}
   		});
	// }

}else{
	console.log("score is not high enough to take action");
}

})

/*
//Example Forecast

Late This AfternoonNorthwest winds 10 to 20 knots. Waves 1 to 3 feet.
TonightNorthwest winds 10 to 20 knots becoming north 5 to 15 knots after midnight. Waves subsiding to calm to 2 feet.
TuesdayEast winds 5 to 15 knots becoming southeast 10 to 20 knots in the afternoon. Waves calm to 2 feet.
Tuesday NightSoutheast winds 15 to 25 knots veering south after midnight. Waves building to 2 to 4 feet.
WednesdaySouth winds 10 to 20 knots veering southwest in the afternoon. A slight chance of snow in the morning. A chance of rain. Waves subsiding to calm to 2 feet.
Wednesday NightNorthwest winds 10 to 20 knots becoming north 15 to 25 knots after midnight. A chance of rain...possibly mixed with snow. Waves calm to 2 feet.
ThursdayNorth winds 15 to 25 knots diminishing to 10 to 20 knots in the afternoon. Waves building to 1 to 3 feet...then subsiding to calm to 2 feet.
Thursday NightNorth winds 10 to 20 knots increasing to 15 to 25 knots after midnight. Waves building to 1 to 3 feet.
FridayNorth winds 10 to 20 knots backing west. Waves subsiding to calm to 2 feet.
SaturdayWest winds 15 to 25 knots diminishing to 10 to 20 knots. Waves building to 3 to 5 feet...then subsiding to 1 to 3 feet.

 */
<|endoftext|>