<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var through = require('@nuintun/through');
var gutil = require('@nuintun/gulp-util');

var join = path.join;
var relative = path.relative;

/**
 * include
 *
 * @param options
 * @returns {Stream}
 */
module.exports = function(options) {
  var initialized = false;
  var configure = util.initOptions(options);

  // stream
  return through({ objectMode: true }, function(vinyl, encoding, next) {
    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(gutil.throwError('streaming not supported.'));
    }

    // hack old vinyl
    vinyl._isVinyl = true;
    // normalize vinyl base
    vinyl.base = relative(vinyl.cwd, vinyl.base);

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // when not initialized
    if (!initialized) {
      // debug
      util.debug('cwd: %p', gutil.normalize(gutil.cwd));

      var base = join(vinyl.cwd, vinyl.base);

      // base out of bound of wwwroot
      if (gutil.isOutBound(base, configure.wwwroot)) {
        gutil.throwError(
          'base: %s is out of bound of wwwroot: %s.',
          gutil.normalize(base),
          gutil.normalize(configure.wwwroot)
        );
      }

      // rewrite ignore
      configure.ignore = util.initIgnore(vinyl, configure);
      // initialized
      initialized = true;
    }

    // catch error
    try {
      // stream
      var stream = this;

      // clone options
      options = gutil.extend({}, configure);

      // lock wwwroot
      gutil.readonlyProperty(options, 'wwwroot');
      // lock plugins
      gutil.readonlyProperty(options, 'plugins');

      // transport
      util.transport(vinyl, options, function(vinyl, options) {
        var pool = {};
        var pkg = vinyl.package;
        var start = vinyl.clone();
        var end = vinyl.clone();
        var path = gutil.pathFromCwd(vinyl.path);

        // set start and end file status
        start.contents = gutil.BLANK_BUFFER;
        start.concat = gutil.CONCAT_STATUS.START;
        end.contents = gutil.BLANK_BUFFER;
        end.concat = gutil.CONCAT_STATUS.END;

        // clean vinyl
        delete start.package;
        delete end.package;

        // compute include
        options.include = gutil.isFunction(options.include)
          ? options.include(pkg.id || null, vinyl.path)
          : options.include;

        // debug
        util.debug('concat: %p start', path);
        // push start blank vinyl
        stream.push(start);
        // include dependencies files
        includeDeps.call(stream, vinyl, pool, options, function() {
          // push end blank vinyl
          stream.push(end);

          // free memory
          pool = null;

          // debug
          util.debug('concat: %p ...ok', path);
          next();
        });
      });
    } catch (error) {
      // show error message
      util.print(gutil.colors.reset.red.bold(error.stack) + '\x07');
      next();
    }
  });
}

/**
 * create a new vinyl
 *
 * @param path
 * @param cwd
 * @param base
 * @param done
 * @returns {void}
 */
function vinylFile(path, cwd, base, done) {
  if (!gutil.isString(path)
    || !gutil.isString(cwd)
    || !gutil.isString(base)) {
    return done(null);
  }

  // cache path
  var src = path;

  // print error
  function printError(error) {
    util.print(
      'file: %s is %s',
      gutil.colors.reset.yellow(gutil.pathFromCwd(src)),
      error.code
    );

    done(null);
  }

  // read file
  function readFile(path, stat) {
    fs.readFile(path, function(error, data) {
      if (error) return printError(error);

      done(new gutil.Vinyl({
        path: path,
        cwd: cwd,
        base: base,
        stat: stat,
        contents: data
      }));
    });
  }

  // read file use origin path
  fs.stat(path, function(error, stat) {
    if (error) {
      path = util.hideExt(path, true);

      // read file use hide extname path
      fs.stat(path, function(error, stat) {
        if (error) return printError(error);

        readFile(path, stat);
      });
    } else {
      readFile(path, stat);
    }
  });
}

/**
 * walk file
 *
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 * @returns {void}
 */
function walk(vinyl, pool, options, done) {
  var stream = this;
  var status = pool[vinyl.path];

  /**
   * transport dependence file
   * @param module
   * @param next
   */
  function transform(module, next) {
    var path = module.path;

    if (options.ignore[path]
      || pool[path]
      || (options.include === 'relative' && !gutil.isRelative(module.id))) {
      return next();
    }
    // create a vinyl file
    vinylFile(path, vinyl.cwd, vinyl.base, function(child) {
      // read file success
      if (child === null) return next();

      // debug
      util.debug('include: %r', child.path);
      // transport file
      util.transport(child, options, function(child, options) {
        // cache next
        status.next = next;
        // add cache status
        pool[child.path] = {
          next: null,
          parent: status,
          included: false
        };

        // walk
        walk.call(stream, child, pool, options, done);
      });
    });
  }

  /**
   * include current file and flush status
   *
   * @returns {void}
   */
  function flush() {
    // push file to stream
    if (!status.included) {
      stream.push(vinyl);

      // change cache status
      status.next = null;
      status.included = true;
    }

    var parent = status.parent;

    // all file include
    if (parent === null || parent.next === null) {
      done();
    } else {
      // run parent next dependencies
      parent.next();

      // clean parent
      delete status.parent;
    }
  }

  var pkg = vinyl.package;

  // bootstrap
  if (status.included || !pkg) {
    flush();
  } else {
    gutil.async.series(pkg.include, transform, flush);
  }
}

/**
 * include dependencies file
 *
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 * @returns {void}
 */
function includeDeps(vinyl, pool, options, done) {
  // return if include not equal 'all' and 'relative'
  if (options.include !== 'all' && options.include !== 'relative') {
    // push file to stream
    this.push(vinyl);

    // free memory
    pool = null;

    return done();
  }

  // set pool cache
  pool[vinyl.path] = {
    next: null,
    parent: null,
    included: false
  };

  // bootstrap
  walk.call(this, vinyl, pool, options, function() {
    // free memory
    pool = null;

    // callback
    done();
  });
}
<commit_msg>update files<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var through = require('@nuintun/through');
var gutil = require('@nuintun/gulp-util');

var join = path.join;
var relative = path.relative;

/**
 * include
 *
 * @param options
 * @returns {Stream}
 */
module.exports = function(options) {
  var initialized = false;
  var configure = util.initOptions(options);

  // stream
  return through({ objectMode: true }, function(vinyl, encoding, next) {
    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(gutil.throwError('streaming not supported.'));
    }

    // hack old vinyl
    vinyl._isVinyl = true;
    // normalize vinyl base
    vinyl.base = relative(vinyl.cwd, vinyl.base);

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // when not initialized
    if (!initialized) {
      // debug
      util.debug('cwd: %p', gutil.normalize(gutil.cwd));

      var base = join(vinyl.cwd, vinyl.base);

      // base out of bound of wwwroot
      if (gutil.isOutBound(base, configure.wwwroot)) {
        gutil.throwError(
          'base: %s is out of bound of wwwroot: %s.',
          gutil.normalize(base),
          gutil.normalize(configure.wwwroot)
        );
      }

      // rewrite ignore
      configure.ignore = util.initIgnore(vinyl, configure);
      // initialized
      initialized = true;
    }

    // catch error
    try {
      // stream
      var stream = this;
      var path = gutil.pathFromCwd(vinyl.path);

      // print process progress
      util.print('process: %s', gutil.colors.reset.green(path));

      // clone options
      options = gutil.extend({}, configure);

      // lock wwwroot
      gutil.readonlyProperty(options, 'wwwroot');
      // lock plugins
      gutil.readonlyProperty(options, 'plugins');

      // transport
      util.transport(vinyl, options, function(vinyl, options) {
        var pool = {};
        var pkg = vinyl.package;
        var start = vinyl.clone();
        var end = vinyl.clone();

        // set start and end file status
        start.contents = gutil.BLANK_BUFFER;
        start.concat = gutil.CONCAT_STATUS.START;
        end.contents = gutil.BLANK_BUFFER;
        end.concat = gutil.CONCAT_STATUS.END;

        // clean vinyl
        delete start.package;
        delete end.package;

        // compute include
        options.include = gutil.isFunction(options.include)
          ? options.include(pkg.id || null, vinyl.path)
          : options.include;

        // debug
        util.debug('concat: %p start', path);
        // push start blank vinyl
        stream.push(start);
        // include dependencies files
        includeDeps.call(stream, vinyl, pool, options, function() {
          // push end blank vinyl
          stream.push(end);

          // free memory
          pool = null;

          // debug
          util.debug('concat: %p ...ok', path);
          next();
        });
      });
    } catch (error) {
      // show error message
      util.print(gutil.colors.reset.red.bold(error.stack) + '\x07');
      next();
    }
  });
}

/**
 * create a new vinyl
 *
 * @param path
 * @param cwd
 * @param base
 * @param done
 * @returns {void}
 */
function vinylFile(path, cwd, base, done) {
  if (!gutil.isString(path)
    || !gutil.isString(cwd)
    || !gutil.isString(base)) {
    return done(null);
  }

  // cache path
  var src = path;

  // print error
  function printError(error) {
    util.print(
      'file: %s is %s',
      gutil.colors.reset.yellow(gutil.pathFromCwd(src)),
      error.code
    );

    done(null);
  }

  // read file
  function readFile(path, stat) {
    fs.readFile(path, function(error, data) {
      if (error) return printError(error);

      done(new gutil.Vinyl({
        path: path,
        cwd: cwd,
        base: base,
        stat: stat,
        contents: data
      }));
    });
  }

  // read file use origin path
  fs.stat(path, function(error, stat) {
    if (error) {
      path = util.hideExt(path, true);

      // read file use hide extname path
      fs.stat(path, function(error, stat) {
        if (error) return printError(error);

        readFile(path, stat);
      });
    } else {
      readFile(path, stat);
    }
  });
}

/**
 * walk file
 *
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 * @returns {void}
 */
function walk(vinyl, pool, options, done) {
  var stream = this;
  var status = pool[vinyl.path];

  /**
   * transport dependence file
   * @param module
   * @param next
   */
  function transform(module, next) {
    var path = module.path;

    if (options.ignore[path]
      || pool[path]
      || (options.include === 'relative' && !gutil.isRelative(module.id))) {
      return next();
    }
    // create a vinyl file
    vinylFile(path, vinyl.cwd, vinyl.base, function(child) {
      // read file success
      if (child === null) return next();

      // debug
      util.debug('include: %r', child.path);
      // transport file
      util.transport(child, options, function(child, options) {
        // cache next
        status.next = next;
        // add cache status
        pool[child.path] = {
          next: null,
          parent: status,
          included: false
        };

        // walk
        walk.call(stream, child, pool, options, done);
      });
    });
  }

  /**
   * include current file and flush status
   *
   * @returns {void}
   */
  function flush() {
    // push file to stream
    if (!status.included) {
      stream.push(vinyl);

      // change cache status
      status.next = null;
      status.included = true;
    }

    var parent = status.parent;

    // all file include
    if (parent === null || parent.next === null) {
      done();
    } else {
      // run parent next dependencies
      parent.next();

      // clean parent
      delete status.parent;
    }
  }

  var pkg = vinyl.package;

  // bootstrap
  if (status.included || !pkg) {
    flush();
  } else {
    gutil.async.series(pkg.include, transform, flush);
  }
}

/**
 * include dependencies file
 *
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 * @returns {void}
 */
function includeDeps(vinyl, pool, options, done) {
  // return if include not equal 'all' and 'relative'
  if (options.include !== 'all' && options.include !== 'relative') {
    // push file to stream
    this.push(vinyl);

    // free memory
    pool = null;

    return done();
  }

  // set pool cache
  pool[vinyl.path] = {
    next: null,
    parent: null,
    included: false
  };

  // bootstrap
  walk.call(this, vinyl, pool, options, function() {
    // free memory
    pool = null;

    // callback
    done();
  });
}
<|endoftext|>


<commit_before>import React from 'react';
import AppContainer from './containers/AppContainer';
import router from './routes/router';
import ipc from 'ipc';
import URLs from './constants/URLs';
import InitializeService from './services/InitializeService';
let injectTapEventPlugin = require('react-tap-event-plugin');

injectTapEventPlugin();

window.location.hash = '/';

URLs.setStaging();

if (document.getElementById('title-text').text === 'Kimochi Staging') {
  console.log('use staging');
  URLs.setStaging();
}

router.run(function (Handler) {
  React.render(<Handler />, document.getElementById('react-root'));
});

InitializeService.startup();
<commit_msg>removing forced use of staging<commit_after>import React from 'react';
import AppContainer from './containers/AppContainer';
import router from './routes/router';
import ipc from 'ipc';
import URLs from './constants/URLs';
import InitializeService from './services/InitializeService';
let injectTapEventPlugin = require('react-tap-event-plugin');

injectTapEventPlugin();

window.location.hash = '/';

if (document.getElementById('title-text').text === 'Kimochi Staging') {
  console.log('use staging');
  URLs.setStaging();
}

router.run(function (Handler) {
  React.render(<Handler />, document.getElementById('react-root'));
});

InitializeService.startup();
<|endoftext|>


<commit_before>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var DIRECTIVE = {
  SLOT: 'slot',
  LAYOUT: 'layout',
  INCLUDE: 'include',
  NONLAYOUT: '!layout'
};
var EVENTS = {
  END: 'end',
  DATA: 'data',
  SLOT: '__SLOT__'
};
var CWD = process.cwd();

var assert = {
  delimiter: function (options, defaults){
    Object.keys(options.delimiter).forEach(function (key){
      var def = defaults.delimiter[key];
      var delimiter = options.delimiter[key];

      if (!util.array(delimiter)) {
        options.delimiter[key] = def;
      } else {
        if (!util.string(delimiter[0])) {
          delimiter[0] = def[0];
        }

        if (!util.string(delimiter[1])) {
          delimiter[1] = def[1];
        }
      }
    });
  },
  data: function (options, defaults){
    Object.keys(options.data).forEach(function (key){
      var def = defaults.data[key];
      var data = options.data[key];

      if (util.fn(data)) {
        data = data(options.src);
      }

      if (!util.string(data)) {
        options.data[key] = def;
      }
    });
  }
};

/**
 * Transform
 * @param src
 * @param source
 * @param options
 * @constructor
 */
function Transform(src, source, options){
  if (!util.string(src)) {
    throw new TypeError('options.src must be a file path.');
  }

  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    layout: null,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: 'dirname',
      filename: 'filename'
    }
  };

  context.index = 0;
  context.slot = null;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix(defaults, options);

  assert.data(options, defaults);
  assert.delimiter(options, defaults);

  context.src = path.resolve(CWD, src);
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.root = path.resolve(CWD, util.string(options.root) ? options.root : CWD);
  context.layout = util.fn(options.layout) ? options.layout(context.src) : options.layout;
  context.layout = util.string(context.layout) ? context.resolve(context.layout) : null;

  var dataDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  var dataDirective = Object.keys(options.data).map(function (data){
    return util.str4regex(data);
  }).join('|');

  var directiveDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  context.regexp = {
    tranform: new RegExp(
      directiveDelimiter[0]
      + '\\s*('
      + util.str4regex(DIRECTIVE.INCLUDE)
      + '\\s+\\(\\s*(.+?)\\s*\\)|'
      + util.str4regex(DIRECTIVE.SLOT)
      + ')\\s*'
      + directiveDelimiter[1]
      + '|'
      + dataDelimiter[0]
      + '\\s*('
      + dataDirective
      + ')\\s*'
      + dataDelimiter[1],
      'img'
    ),
    layout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.LAYOUT)
      + '\\s+\\(\\s*(.+?)\\s*\\)\\s*'
      + directiveDelimiter[1]
    ),
    nonlayout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.NONLAYOUT)
      + '\\s*'
      + directiveDelimiter[1]
    )
  };

  context.readLayout();
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.readLayout = function (){
  var src;
  var context = this;
  var layout = context.regexp.layout.exec(context.source);
  var nonlayout = context.regexp.nonlayout.exec(context.source);

  if (layout && (!nonlayout || layout.index < nonlayout.index)) {
    src = context.resolve(layout[1]);
  }

  src = src || context.layout;

  if (src && src !== context.src) {
    fs.readFile(src, function (error, source){
      if (error) {
        return context.next();
      }

      var layout = new Transform(context.layout, source.toString(), context.options);

      layout.entry = context;

      layout.on(EVENTS.DATA, function (data){
        context.write(data);
      });

      context.once(EVENTS.SLOT, function (){
        layout.next();
      });

      layout.once(EVENTS.END, function (){
        context.end();
      });
    });
  } else {
    process.nextTick(function (){
      context.next();
    });
  }
};

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.tranform.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.write(context.source.substring(context.index, index));

  context.index = index + match.length;

  if (type === 'directive') {
    command = command.toLowerCase();

    switch (command) {
      case DIRECTIVE.SLOT:
        if (context.layout && !context.slot) {
          context.next();

          context.slot = true;
        }
        break;
      default:
        if (command.indexOf(DIRECTIVE.INCLUDE) === 0) {
          var entry = context.entry;

          while (entry instanceof Transform) {
            if (context.src === entry.src) {
              context.entry = null;

              return true;
            }

            entry = entry.entry;
          }

          var src = context.resolve(command);

          fs.readFile(src, function (error, source){
            if (error) {
              return context.next();
            }

            var child = new Transform(src, source.toString(), options);

            child.entry = context;

            child.on(EVENTS.DATA, function (data){
              entry.write(data);
            });

            child.once(EVENTS.END, function (){
              var entry = this.entry;

              if (this.entry instanceof Transform) {
                entry.next();
              }
            });
          });
        } else {
          context.write(match);
          context.next();
        }
        break;
    }
  } else {
    context.write(context.options.data[command] || match);
    context.next();
  }

  return true;
};

Transform.prototype.resolve = function (url){
  return path.resolve(this.dirname, url);
};

Transform.prototype.write = function (data){
  this.emit(EVENTS.DATA, data);

  return data;
};

Transform.prototype.end = function (data){
  if (data) {
    this.emit(EVENTS.DATA, data);
  }

  this.emit(EVENTS.END);

  return data;
};

Transform.prototype.next = function (){
  var context = this;

  console.log(context.layout, context.src);

  if (!context.exec()) {
    if (!context.layout) {
      context.end();
    } else {
      context.write(context.source.substring(context.index));
      context.emit(EVENTS.SLOT);
    }
  }
};

// exports
module.exports = Transform;
<commit_msg>update files<commit_after>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var DIRECTIVE = {
  SLOT: 'slot',
  LAYOUT: 'layout',
  INCLUDE: 'include',
  NONLAYOUT: '!layout'
};
var EVENTS = {
  END: 'end',
  DATA: 'data',
  SLOT: '__SLOT__'
};
var CWD = process.cwd();

var assert = {
  delimiter: function (options, defaults){
    Object.keys(options.delimiter).forEach(function (key){
      var def = defaults.delimiter[key];
      var delimiter = options.delimiter[key];

      if (!util.array(delimiter)) {
        options.delimiter[key] = def;
      } else {
        if (!util.string(delimiter[0])) {
          delimiter[0] = def[0];
        }

        if (!util.string(delimiter[1])) {
          delimiter[1] = def[1];
        }
      }
    });
  },
  data: function (options, defaults){
    Object.keys(options.data).forEach(function (key){
      var def = defaults.data[key];
      var data = options.data[key];

      if (util.fn(data)) {
        data = data(options.src);
      }

      if (!util.string(data)) {
        options.data[key] = def;
      }
    });
  }
};

/**
 * Transform
 * @param src
 * @param source
 * @param options
 * @constructor
 */
function Transform(src, source, options){
  if (!util.string(src)) {
    throw new TypeError('options.src must be a file path.');
  }

  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    layout: null,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: 'dirname',
      filename: 'filename'
    }
  };

  context.index = 0;
  context.slot = null;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix(defaults, options);

  assert.data(options, defaults);
  assert.delimiter(options, defaults);

  context.src = path.resolve(CWD, src);
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.root = path.resolve(CWD, util.string(options.root) ? options.root : CWD);
  context.layout = util.fn(options.layout) ? options.layout(context.src) : options.layout;
  context.layout = util.string(context.layout) ? context.resolve(context.layout) : null;
  context.isLayout = context.src === context.layout;

  var dataDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  var dataDirective = Object.keys(options.data).map(function (data){
    return util.str4regex(data);
  }).join('|');

  var directiveDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  context.regexp = {
    tranform: new RegExp(
      directiveDelimiter[0]
      + '\\s*('
      + util.str4regex(DIRECTIVE.INCLUDE)
      + '\\s+\\(\\s*(.+?)\\s*\\)|'
      + util.str4regex(DIRECTIVE.SLOT)
      + ')\\s*'
      + directiveDelimiter[1]
      + '|'
      + dataDelimiter[0]
      + '\\s*('
      + dataDirective
      + ')\\s*'
      + dataDelimiter[1],
      'img'
    ),
    layout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.LAYOUT)
      + '\\s+\\(\\s*(.+?)\\s*\\)\\s*'
      + directiveDelimiter[1]
    ),
    nonlayout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.NONLAYOUT)
      + '\\s*'
      + directiveDelimiter[1]
    )
  };

  context.readLayout();
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.readLayout = function (){
  var src;
  var context = this;
  var layout = context.regexp.layout.exec(context.source);
  var nonlayout = context.regexp.nonlayout.exec(context.source);

  if (layout && (!nonlayout || layout.index < nonlayout.index)) {
    src = context.resolve(layout[1]);
  }

  src = src || context.layout;

  if (src && src !== context.src) {
    fs.readFile(src, function (error, source){
      if (error) {
        return context.next();
      }

      var layout = new Transform(context.layout, source.toString(), context.options);

      layout.entry = context;
      layout.isLayout = true;

      layout.on(EVENTS.DATA, function (data){
        context.write(data);
      });

      context.once(EVENTS.SLOT, function (){
        layout.next();
      });

      layout.once(EVENTS.END, function (){
        context.end();
      });
    });
  } else {
    process.nextTick(function (){
      context.next();
    });
  }
};

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.tranform.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.write(context.source.substring(context.index, index));

  context.index = index + match.length;

  if (type === 'directive') {
    command = command.toLowerCase();

    switch (command) {
      case DIRECTIVE.SLOT:
        if (context.layout && !context.slot) {
          context.next();

          context.slot = true;
        }
        break;
      default:
        if (command.indexOf(DIRECTIVE.INCLUDE) === 0) {
          var entry = context.entry;

          while (entry instanceof Transform) {
            if (context.src === entry.src) {
              context.entry = null;

              return true;
            }

            entry = entry.entry;
          }

          var src = context.resolve(command);

          fs.readFile(src, function (error, source){
            if (error) {
              return context.next();
            }

            var child = new Transform(src, source.toString(), options);

            child.entry = context;

            child.on(EVENTS.DATA, function (data){
              entry.write(data);
            });

            child.once(EVENTS.END, function (){
              var entry = this.entry;

              if (this.entry instanceof Transform) {
                entry.next();
              }
            });
          });
        } else {
          context.write(match);
          context.next();
        }
        break;
    }
  } else {
    context.write(context.options.data[command] || match);
    context.next();
  }

  return true;
};

Transform.prototype.resolve = function (url){
  return path.resolve(this.dirname, url);
};

Transform.prototype.write = function (data){
  this.emit(EVENTS.DATA, data);

  return data;
};

Transform.prototype.end = function (data){
  if (data) {
    this.emit(EVENTS.DATA, data);
  }

  this.emit(EVENTS.END);

  return data;
};

Transform.prototype.next = function (){
  var context = this;

  if (!context.exec()) {
    if (context.isLayout) {
      context.write(context.source.substring(context.index));
      context.end();
    } else {
      if (context.layout) {
        context.write(context.source.substring(context.index));
        context.emit(EVENTS.SLOT);
      } else {
        context.end();
      }
    }
  }
};

// exports
module.exports = Transform;
<|endoftext|>


<commit_before>'use strict';

define(['States'],
    function (States) {
        var app = angular.module('app', [
            'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ngAnimate', 'mgcrea.ngStrap', 'chieffancypants.loadingBar'
        ]);

        app.config([
            '$stateProvider',
            '$urlRouterProvider',
            '$httpProvider',
            '$locationProvider',
            '$controllerProvider',
            '$compileProvider',
            '$filterProvider',
            '$provide',
            'cfpLoadingBarProvider',
            function (
                $stateProvider,
                $urlRouterProvider,
                $httpProvider,
                $locationProvider,
                $controllerProvider,
                $compileProvider,
                $filterProvider,
                $provide,
                cfpLoadingBarProvider
            ) {
                app.controller = $controllerProvider.register;
                app.directive = $compileProvider.directive;
                app.filter = $filterProvider.register;
                app.factory = $provide.factory;
                app.service = $provide.service;

                $locationProvider.html5Mode(true);
                cfpLoadingBarProvider.includeSpinner = false;

                var interceptor = ['$q', '$location', '$rootScope',
                    function ($q, $location, $rootScope) {
                        function success(response) {
                            return response;
                        }

                        function error(response) {
                            var status = response.status;
                            if (status == 401) {
                                $location.path('/login');
                            }
                            return $q.reject(response);
                        }

                        return function (promise) {
                            return promise.then(success, error);
                        }
                    }
                ];
                $httpProvider.responseInterceptors.push(interceptor);

                if (States.states !== undefined) {
                    angular.forEach(States.states, function (state) {
                        $stateProvider.state(state);
                    });
                }
                if (States.defaultStatePath !== undefined) {
                    $urlRouterProvider.otherwise(States.defaultStatePath);
                }
            }
        ]);

        app.run(function ($http, $state, $cookies, $rootScope, Auth) {
            $http.defaults.headers.common['x-csrf-token'] = $cookies._csrf;

            $rootScope.$on('$stateChangeStart', function (event, next) {
                if (next.authenticate && !Auth.isLoggedIn()) {
                    event.preventDefault();
                    $state.go('login');
                }
            });

        });

        return app;
    });<commit_msg>separate config per feature<commit_after>'use strict';

define(['States'],
    function (States) {
        var app = angular.module('app', [
            'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ngAnimate', 'mgcrea.ngStrap', 'chieffancypants.loadingBar'
        ]);

        app.config([
            '$controllerProvider',
            '$compileProvider',
            '$filterProvider',
            '$provide',
            'cfpLoadingBarProvider',
            function (
                $controllerProvider,
                $compileProvider,
                $filterProvider,
                $provide,
                cfpLoadingBarProvider
            ) {
                app.controller = $controllerProvider.register;
                app.directive = $compileProvider.directive;
                app.filter = $filterProvider.register;
                app.factory = $provide.factory;
                app.service = $provide.service;

                cfpLoadingBarProvider.includeSpinner = false;

            }
        ]);

        app.config([
            '$stateProvider',
            '$urlRouterProvider',
            '$httpProvider',
            '$locationProvider',
            '$provide',
            function (
                $stateProvider,
                $urlRouterProvider,
                $httpProvider,
                $locationProvider,
                $provide
            ) {
                $locationProvider.html5Mode(true);

                var interceptor = ['$q', '$location', '$rootScope',
                    function ($q, $location, $rootScope) {
                        function success(response) {
                            return response;
                        }

                        function error(response) {
                            var status = response.status;
                            if (status == 401) {
                                $location.path('/login');
                            }
                            return $q.reject(response);
                        }

                        return function (promise) {
                            return promise.then(success, error);
                        }
                    }
                ];

                $httpProvider.responseInterceptors.push(interceptor);

                if (States.states !== undefined) {
                    angular.forEach(States.states, function (state) {
                        $stateProvider.state(state);
                    });
                }
                if (States.defaultStatePath !== undefined) {
                    $urlRouterProvider.otherwise(States.defaultStatePath);
                }
            }

        ]);

        app.run(function ($http, $state, $cookies, $rootScope, Auth) {
            $http.defaults.headers.common['x-csrf-token'] = $cookies._csrf;

            $rootScope.$on('$stateChangeStart', function (event, next) {
                if (next.authenticate && !Auth.isLoggedIn()) {
                    event.preventDefault();
                    $state.go('login');
                }
            });

        });

        return app;
    });<|endoftext|>


<commit_before>var B = 3975;
var mraa = require("mraa");

//GROVE Kit A0 Connector --> Aio(0)
var myAnalogPin = new mraa.Aio(0);

/*
 Function: startSensorWatch(socket)
 Parameters: socket - client communication channel
 Description: Read Temperature Sensor and send temperature in degrees of Fahrenheit every 4 seconds
 */
function startSensorWatch(res) {
    'use strict';
    var a = myAnalogPin.read();
    console.log("Analog Pin (A0) Output: " + a);
    //console.log("Checking....");

    var resistance = (1023 - a) * 10000 / a; //get the resistance of the sensor;
    //console.log("Resistance: "+resistance);
    var celsius_temperature = 1 / (Math.log(resistance / 10000) / B + 1 / 298.15) - 273.15;//convert to temperature via datasheet ;
    //console.log("Celsius Temperature "+celsius_temperature);
    var fahrenheit_temperature = (celsius_temperature * (9 / 5)) + 32;
    console.log("Fahrenheit Temperature: " + fahrenheit_temperature);
    res.json({ message: 'temperature get: ' + fahrenheit_temperature });
}

console.log("Sample Reading Grove Kit Temperature Sensor");

var port = process.env.PORT || 8080;        // set our port

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here

router.route('/temperature')

    // temperature toggle
    .post(function(req, res) {

        //insert code to toggle temperature control
        res.json({ message: 'temperature post!' })

    })

    //temperature get
    .get(function(req, res) {
        console.log("Sensor watch begin");
        startSensorWatch(res);
        //insert code to return temperature data

    });

//Attach a 'connection' event handler to the server
//io.sockets.on('connection', function (socket) {
//    'use strict';
//    console.log('a user connected');
//    //Emits an event along with a message
//    socket.emit('connected', 'Welcome');
//
//    //Start watching Sensors connected to Galileo board
//    startSensorWatch(socket);
//
//    //Attach a 'disconnect' event handler to the socket
//    socket.on('disconnect', function () {
//        console.log('user disconnected');
//    });
//});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);<commit_msg>Fixed response<commit_after>var B = 3975;
var mraa = require("mraa");

//GROVE Kit A0 Connector --> Aio(0)
var myAnalogPin = new mraa.Aio(0);

/*
 Function: startSensorWatch(socket)
 Parameters: socket - client communication channel
 Description: Read Temperature Sensor and send temperature in degrees of Fahrenheit every 4 seconds
 */
function startSensorWatch(res) {
    'use strict';
    var a = myAnalogPin.read();
    console.log("Analog Pin (A0) Output: " + a);
    //console.log("Checking....");

    var resistance = (1023 - a) * 10000 / a; //get the resistance of the sensor;
    //console.log("Resistance: "+resistance);
    var celsius_temperature = 1 / (Math.log(resistance / 10000) / B + 1 / 298.15) - 273.15;//convert to temperature via datasheet ;
    //console.log("Celsius Temperature "+celsius_temperature);
    var fahrenheit_temperature = (celsius_temperature * (9 / 5)) + 32;
    console.log("Fahrenheit Temperature: " + fahrenheit_temperature);
    res.json({ message: fahrenheit_temperature });
}

console.log("Sample Reading Grove Kit Temperature Sensor");

var port = process.env.PORT || 8080;        // set our port

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here

router.route('/temperature')

    // temperature toggle
    .post(function(req, res) {

        //insert code to toggle temperature control
        res.json({ message: 'temperature post!' })

    })

    //temperature get
    .get(function(req, res) {
        console.log("Sensor watch begin");
        startSensorWatch(res);
        //insert code to return temperature data

    });

//Attach a 'connection' event handler to the server
//io.sockets.on('connection', function (socket) {
//    'use strict';
//    console.log('a user connected');
//    //Emits an event along with a message
//    socket.emit('connected', 'Welcome');
//
//    //Start watching Sensors connected to Galileo board
//    startSensorWatch(socket);
//
//    //Attach a 'disconnect' event handler to the socket
//    socket.on('disconnect', function () {
//        console.log('user disconnected');
//    });
//});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);<|endoftext|>


<commit_before>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var DIRECTIVE = {
  SLOT: 'slot',
  INCLUDE: 'include',
  LAYOUT: 'layout',
  NONLAYOUT: '!layout'
};
var CWD = process.cwd();

var assert = {
  delimiter: function (options, defaults){
    Object.keys(options.delimiter).forEach(function (key){
      var def = defaults.delimiter[key];
      var delimiter = options.delimiter[key];

      if (!util.array(delimiter)) {
        options.delimiter[key] = def;
      } else {
        if (!util.string(delimiter[0])) {
          delimiter[0] = def[0];
        }

        if (!util.string(delimiter[1])) {
          delimiter[1] = def[1];
        }
      }
    });
  },
  data: function (options, defaults){
    Object.keys(options.data).forEach(function (key){
      var def = defaults.data[key];
      var data = options.data[key];

      if (util.fn(data)) {
        data = data(options.src);
      }

      if (!util.string(data)) {
        options.data[key] = def;
      }
    });
  }
};

/**
 * Transform
 * @param src
 * @param source
 * @param options
 * @constructor
 */
function Transform(src, source, options){
  if (!util.string(src)) {
    throw new TypeError('options.src must be a file path.');
  }

  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    layout: null,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: 'dirname',
      filename: 'filename'
    }
  };

  context.index = 0;
  context.slot = null;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix(defaults, options);

  assert.data(options, defaults);
  assert.delimiter(options, defaults);

  context.src = path.resolve(CWD, src);
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.root = path.resolve(CWD, util.string(options.root) ? options.root : CWD);
  context.layout = util.fn(options.layout) ? options.layout(context.src) : options.layout;
  context.layout = util.string(context.layout) ? context.resolve(context.layout) : null;

  if (context.src === context.layout) {
    context.layout = null;
  }

  var dataDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  var dataDirective = Object.keys(options.data).map(function (data){
    return util.str4regex(data);
  }).join('|');

  var directiveDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  context.regexp = {
    tranform: new RegExp(
      directiveDelimiter[0]
      + '\\s*('
      + util.str4regex(DIRECTIVE.INCLUDE)
      + '\\s+\\(\\s*(.+?)\\s*\\)|'
      + util.str4regex(DIRECTIVE.SLOT)
      + ')\\s*'
      + directiveDelimiter[1]
      + '|'
      + dataDelimiter[0]
      + '\\s*('
      + dataDirective
      + ')\\s*'
      + dataDelimiter[1],
      'img'
    ),
    layout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.LAYOUT)
      + '\\s+\\(\\s*(.+?)\\s*\\)\\s*'
      + directiveDelimiter[1]
    ),
    nonlayout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.NONLAYOUT)
      + '\\s*'
      + directiveDelimiter[1]
    )
  };

  context.readLayout();
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.readLayout = function (){
  var context = this;
  var layout = context.regexp.layout.exec(context.source);
  var nonlayout = context.regexp.nonlayout.exec(context.source);

  if (layout && (!nonlayout || layout.index < nonlayout.index)) {
    context.layout = context.resolve(layout[1]);
  }

  if (context.layout) {
    fs.readFile(context.layout, function (error, source){
      if (error) {
        return context.next();
      }

      var layout = new Transform(context.layout, source.toString(), context.options);

      layout.entry = context;

      layout.on('data', function (data){
        context.write(data);
      });

      context.on('end', function (){
        layout.next();
      });

      layout.on('end', function (){
        context.end();
      });
    });
  } else {
    process.nextTick(function (){
      context.next();
    });
  }
};

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.tranform.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.write(context.source.substring(context.index, index));

  context.index = index + match.length;

  if (type === 'directive') {
    command = command.toLowerCase();

    switch (command) {
      case DIRECTIVE.SLOT:
        console.log(DIRECTIVE.SLOT);
        break;
      default:
        if (command.indexOf(DIRECTIVE.INCLUDE) === 0) {
          var entry = context.entry;

          while (entry instanceof Transform) {
            if (context.src === entry.src) {
              return true;
            }

            entry = entry.entry;
          }

          var include = context.resolve(command);

          fs.readFile(include, function (error, source){
            if (error) {
              return context.next();
            }

            var child = new Transform(include, source.toString(), options);

            child.entry = context;

            child.on('end', function (){
              var entry = this.entry;

              if (this.entry instanceof Transform) {
                entry.next();
              }
            });
          });
        } else {
          context.write(match);
          context.next();
        }
        break;
    }
  } else {
    context.write(context.options.data[command] || match);
    context.next();
  }

  return true;
};

Transform.prototype.resolve = function (url){
  return path.resolve(this.dirname, url);
};

Transform.prototype.write = function (data){
  this.emit('data', data);

  return data;
};

Transform.prototype.end = function (data){
  if (data) {
    this.emit('data', data);
  }

  this.emit('end');

  return data;
};

Transform.prototype.next = function (){
  var context = this;

  if (!context.exec()) {
    if (!context.layout) {
      context.end();
    } else {
      context.end(context.source.substring(context.index));
    }
  }
};

// exports
module.exports = Transform;
<commit_msg>update files<commit_after>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var DIRECTIVE = {
  SLOT: 'slot',
  INCLUDE: 'include',
  LAYOUT: 'layout',
  NONLAYOUT: '!layout'
};
var CWD = process.cwd();

var assert = {
  delimiter: function (options, defaults){
    Object.keys(options.delimiter).forEach(function (key){
      var def = defaults.delimiter[key];
      var delimiter = options.delimiter[key];

      if (!util.array(delimiter)) {
        options.delimiter[key] = def;
      } else {
        if (!util.string(delimiter[0])) {
          delimiter[0] = def[0];
        }

        if (!util.string(delimiter[1])) {
          delimiter[1] = def[1];
        }
      }
    });
  },
  data: function (options, defaults){
    Object.keys(options.data).forEach(function (key){
      var def = defaults.data[key];
      var data = options.data[key];

      if (util.fn(data)) {
        data = data(options.src);
      }

      if (!util.string(data)) {
        options.data[key] = def;
      }
    });
  }
};

/**
 * Transform
 * @param src
 * @param source
 * @param options
 * @constructor
 */
function Transform(src, source, options){
  if (!util.string(src)) {
    throw new TypeError('options.src must be a file path.');
  }

  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    layout: null,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: 'dirname',
      filename: 'filename'
    }
  };

  context.index = 0;
  context.slot = null;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix(defaults, options);

  assert.data(options, defaults);
  assert.delimiter(options, defaults);

  context.src = path.resolve(CWD, src);
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.root = path.resolve(CWD, util.string(options.root) ? options.root : CWD);
  context.layout = util.fn(options.layout) ? options.layout(context.src) : options.layout;
  context.layout = util.string(context.layout) ? context.resolve(context.layout) : null;

  if (context.src === context.layout) {
    context.layout = null;
  }

  var dataDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  var dataDirective = Object.keys(options.data).map(function (data){
    return util.str4regex(data);
  }).join('|');

  var directiveDelimiter = options.delimiter.directive.map(function (directive){
    return util.str4regex(directive);
  });

  context.regexp = {
    tranform: new RegExp(
      directiveDelimiter[0]
      + '\\s*('
      + util.str4regex(DIRECTIVE.INCLUDE)
      + '\\s+\\(\\s*(.+?)\\s*\\)|'
      + util.str4regex(DIRECTIVE.SLOT)
      + ')\\s*'
      + directiveDelimiter[1]
      + '|'
      + dataDelimiter[0]
      + '\\s*('
      + dataDirective
      + ')\\s*'
      + dataDelimiter[1],
      'img'
    ),
    layout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.LAYOUT)
      + '\\s+\\(\\s*(.+?)\\s*\\)\\s*'
      + directiveDelimiter[1]
    ),
    nonlayout: new RegExp(
      directiveDelimiter[0]
      + '\\s*'
      + util.str4regex(DIRECTIVE.NONLAYOUT)
      + '\\s*'
      + directiveDelimiter[1]
    )
  };

  context.readLayout();
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.readLayout = function (){
  var context = this;
  var layout = context.regexp.layout.exec(context.source);
  var nonlayout = context.regexp.nonlayout.exec(context.source);

  if (layout && (!nonlayout || layout.index < nonlayout.index)) {
    context.layout = context.resolve(layout[1]);
  }

  if (context.layout) {
    fs.readFile(context.layout, function (error, source){
      if (error) {
        return context.next();
      }

      var layout = new Transform(context.layout, source.toString(), context.options);

      layout.entry = context;

      layout.on('data', function (data){
        context.write(data);
      });

      context.on('end', function (){
        layout.next();
      });

      layout.on('end', function (){
        context.end();
      });
    });
  } else {
    process.nextTick(function (){
      context.next();
    });
  }
};

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.tranform.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.write(context.source.substring(context.index, index));

  context.index = index + match.length;

  if (type === 'directive') {
    command = command.toLowerCase();

    switch (command) {
      case DIRECTIVE.SLOT:
        console.log(DIRECTIVE.SLOT);
        break;
      default:
        if (command.indexOf(DIRECTIVE.INCLUDE) === 0) {
          var entry = context.entry;

          while (entry instanceof Transform) {
            if (context.src === entry.src) {
              context.entry = null;

              return true;
            }

            entry = entry.entry;
          }

          var include = context.resolve(command);

          fs.readFile(include, function (error, source){
            if (error) {
              return context.next();
            }

            var child = new Transform(include, source.toString(), options);

            child.entry = context;

            child.on('data', function (data){
              entry.write(data);
            });

            child.on('end', function (){
              var entry = this.entry;

              if (this.entry instanceof Transform) {
                entry.next();
              }
            });
          });
        } else {
          context.write(match);
          context.next();
        }
        break;
    }
  } else {
    context.write(context.options.data[command] || match);
    context.next();
  }

  return true;
};

Transform.prototype.resolve = function (url){
  return path.resolve(this.dirname, url);
};

Transform.prototype.write = function (data){
  this.emit('data', data);

  return data;
};

Transform.prototype.end = function (data){
  if (data) {
    this.emit('data', data);
  }

  this.emit('end');

  return data;
};

Transform.prototype.next = function (){
  var context = this;

  if (!context.exec()) {
    if (!context.layout) {
      context.end();
    } else {
      context.end(context.source.substring(context.index));
    }
  }
};

// exports
module.exports = Transform;
<|endoftext|>


<commit_before>import { select } from 'd3';
import { Observer } from '@scola/d3-model';
import Button from './part/button';
import Icon from './part/icon';
import Icons from './part/icons';
import Scroller from './part/scroller';
import Space from './part/space';
import Switch from './part/switch';
import Input from './part/input';
import Text from './part/text';
import Textarea from './part/textarea';
import Texts from './part/texts';

export default class Item extends Observer {
  constructor() {
    super();

    this._parts = [];

    this._disabled = false;
    this._first = false;
    this._visible = true;

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola item', true)
      .styles({
        'background': '#FFF',
        'display': 'flex',
        'flex-direction': 'row'
      });

    this._padding = this._root
      .append('div')
      .classed('scola padding', true)
      .styles({
        'border-top': '1px solid transparent',
        'width': '1em'
      });

    this._bindRoot();
    this.first(false);
  }

  destroy() {
    super.destroy();
    this._unbindRoot();

    this._parts.forEach((part) => {
      part.destroy();
    });

    this._parts = [];

    this._root.dispatch('destroy');
    this._root.remove();
    this._root = null;
  }

  root() {
    return this._root;
  }

  disabled(value = null) {
    if (value === null) {
      return this._disabled;
    }

    this._disabled = value;
    this._root.classed('disabled', value);

    this._parts.forEach((part) => {
      part.disabled(value);
    });

    return this;
  }

  first(value = null) {
    if (value === null) {
      return this._first;
    }

    this._first = value;

    const color = value === true ?
      'transparent' : '#CCC';

    this._root.style('border-color', color);

    return this;
  }

  show(value = null) {
    if (value === null) {
      return this._visible;
    }

    this._visible = value;

    const display = value === true ?
      'flex' : 'none';

    this._root.style('display', display);

    return this;
  }

  order(part = null, value = -1) {
    if (part !== null) {
      this._move(part, value);
    }

    this._order();
  }

  part(index) {
    return this._parts[index];
  }

  button(value = null) {
    const button = new Button()
      .item(this);

    button.class(value);
    this._add(button);

    return button;
  }

  icon(value = null) {
    const icon = new Icon()
      .item(this);

    icon.class(value);
    this._add(icon);

    return icon;
  }

  icons() {
    const icon = new Icons()
      .item(this);

    this._add(icon);
    return icon;
  }

  input(value = null) {
    const input = new Input()
      .item(this);

    input.type(value);
    this._add(input);

    return input;
  }

  scroller() {
    const scroller = new Scroller()
      .item(this);

    this._add(scroller);
    return scroller;
  }

  space() {
    const space = new Space()
      .item(this);

    this._add(space);
    return space;
  }

  switch () {
    const part = new Switch()
      .item(this);

    this._add(part);
    return part;
  }

  text(value = null) {
    const text = new Text()
      .item(this);

    text.text(value);
    this._add(text);

    return text;
  }

  textarea() {
    const textarea = new Textarea()
      .item(this);

    this._add(textarea);
    return textarea;
  }

  texts() {
    const texts = new Texts()
      .item(this);

    this._add(texts);
    return texts;
  }

  _bindRoot() {
    this._root.on('click.scola-item', () => this._click());
  }

  _unbindRoot() {
    this._root.on('click.scola-item', null);
  }

  _add(part) {
    this._parts.push(part);
    this._order();
  }

  _move(part, value) {
    this._parts.splice(value, 0,
      this._parts.splice(
        this._parts.indexOf(part), 1).pop());
  }

  _order() {
    this._parts.forEach((part, index) => {
      part.order(index + 2, false);
      this._root.append(() => part.root().node());
    });
  }

  _click() {}
}
<commit_msg>Fix super destroy in item<commit_after>import { select } from 'd3';
import { Observer } from '@scola/d3-model';
import Button from './part/button';
import Icon from './part/icon';
import Icons from './part/icons';
import Scroller from './part/scroller';
import Space from './part/space';
import Switch from './part/switch';
import Input from './part/input';
import Text from './part/text';
import Textarea from './part/textarea';
import Texts from './part/texts';

export default class Item extends Observer {
  constructor() {
    super();

    this._parts = [];

    this._disabled = false;
    this._first = false;
    this._visible = true;

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola item', true)
      .styles({
        'background': '#FFF',
        'display': 'flex',
        'flex-direction': 'row'
      });

    this._padding = this._root
      .append('div')
      .classed('scola padding', true)
      .styles({
        'border-top': '1px solid transparent',
        'width': '1em'
      });

    this._bindRoot();
    this.first(false);
  }

  destroy() {
    this._unbindRoot();

    this._parts.forEach((part) => {
      part.destroy();
    });

    this._parts = [];

    this._root.dispatch('destroy');
    this._root.remove();
    this._root = null;

    super.destroy();
  }

  root() {
    return this._root;
  }

  disabled(value = null) {
    if (value === null) {
      return this._disabled;
    }

    this._disabled = value;
    this._root.classed('disabled', value);

    this._parts.forEach((part) => {
      part.disabled(value);
    });

    return this;
  }

  first(value = null) {
    if (value === null) {
      return this._first;
    }

    this._first = value;

    const color = value === true ?
      'transparent' : '#CCC';

    this._root.style('border-color', color);

    return this;
  }

  show(value = null) {
    if (value === null) {
      return this._visible;
    }

    this._visible = value;

    const display = value === true ?
      'flex' : 'none';

    this._root.style('display', display);

    return this;
  }

  order(part = null, value = -1) {
    if (part !== null) {
      this._move(part, value);
    }

    this._order();
  }

  part(index) {
    return this._parts[index];
  }

  button(value = null) {
    const button = new Button()
      .item(this);

    button.class(value);
    this._add(button);

    return button;
  }

  icon(value = null) {
    const icon = new Icon()
      .item(this);

    icon.class(value);
    this._add(icon);

    return icon;
  }

  icons() {
    const icon = new Icons()
      .item(this);

    this._add(icon);
    return icon;
  }

  input(value = null) {
    const input = new Input()
      .item(this);

    input.type(value);
    this._add(input);

    return input;
  }

  scroller() {
    const scroller = new Scroller()
      .item(this);

    this._add(scroller);
    return scroller;
  }

  space() {
    const space = new Space()
      .item(this);

    this._add(space);
    return space;
  }

  switch () {
    const part = new Switch()
      .item(this);

    this._add(part);
    return part;
  }

  text(value = null) {
    const text = new Text()
      .item(this);

    text.text(value);
    this._add(text);

    return text;
  }

  textarea() {
    const textarea = new Textarea()
      .item(this);

    this._add(textarea);
    return textarea;
  }

  texts() {
    const texts = new Texts()
      .item(this);

    this._add(texts);
    return texts;
  }

  _bindRoot() {
    this._root.on('click.scola-item', () => this._click());
  }

  _unbindRoot() {
    this._root.on('click.scola-item', null);
  }

  _add(part) {
    this._parts.push(part);
    this._order();
  }

  _move(part, value) {
    this._parts.splice(value, 0,
      this._parts.splice(
        this._parts.indexOf(part), 1).pop());
  }

  _order() {
    this._parts.forEach((part, index) => {
      part.order(index + 2, false);
      this._root.append(() => part.root().node());
    });
  }

  _click() {}
}
<|endoftext|>


<commit_before>/*
* -*- mode: text; coding: utf-8; -*-

   This file is part of Indico.
   Copyright (C) 2002 - 2013 European Organization for Nuclear Research (CERN).

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

   Indico 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/

(function($) {
    $.widget("ui.fieldarea", {

        options: {
            fields_caption: "field",
            parameter_manager: undefined
        },

        _create: function() {
            var self = this;

            self.info = {};
            self.info["next_index"] = 2;

            self.table = $("

");
            self.element.addClass("field-area scrollable");
            self.element.append(self.table);

            self._handleEvents();
            self._drawTable();
        },

        _handleEvents: function() {
            var self = this;

            self.element.on("focusout", "input", function(e) {
                self._updateField(this);
            });

            self.element.on("click", "a", function(e) {
                e.preventDefault();
                self._deleteRow($(this).closest("tr"));
            });

            self.element.on("keyup propertychange paste", "input", function(e) {
                // Enter
                if (e.type == "keyup" && e.which == 13) {
                    $(this).blur();
                }

                if ($(this).val() === "") {
                    self._deleteInput($(this).closest("tr"));
                }

                self._drawInput();
            });

            self.element.on("keydown", "input", function(e) {
                // ESC
                if (e.which == 27) {
                    e.stopPropagation();
                    value = self.info[$(this).data("id")];
                    $(this).val(value);
                    $(this).blur();
                }
            });
        },

        _drawTable: function() {
            var self = this;
            var table = self.table;

            table.find("tr").each(function() {
                $(this).remove();
            });

            for (var key in self.info) {
                if (!isNaN(key)) {
                    table.append(self._row(key));
                }
            }

            self._drawInput();
        },

        _drawInput: function() {
            if (this.new_row === undefined || this.new_row.find("input").val() !== "") {
                this.new_row = this._row();
                this.table.append(this.new_row);
                this.element.scrollTop(this.element[0].scrollHeight);
            }
        },

        _deleteInput: function(row) {
            if (row.next()[0] == this.new_row[0]) {
                this._prevIndex();
                this.new_row.remove();
                this.new_row = row;
            }
        },

        destroy: function() {
            this.element.off("focusout click keyup propertychange paste");
            this.element.removeClass("field-area scrollable");
            this.table.remove();
        },

        _deleteRow: function(row) {
            if (row[0] != this.new_row[0]) {
                var id = $(this).closest("tr").find("input").data("id");
                delete this.info[id];
                row.remove();
            }
        },

        _nextIndex: function() {
            return this.info["next_index"]++;
        },

        _prevIndex: function() {
            return this.info["next_index"]--;
        },

        _row: function(id) {
            var value;
            var placeholder = "Type to add " + this.options["fields_caption"];

            if (id !== undefined) {
                value = this.info[id];
            } else {
                id = this._nextIndex();
                value = "";
            }

            var row = $("

");
            var dragger = $(".	");
            var field = $("<input class='input-text' type='text' data-id='"+ id +"' placeholder='"+ placeholder+"' value='"+ value +"'/>	");
            var remove = $("	");

            return row.append(dragger).append(field).append(remove);
        },

        _updateField: function(input) {
            input = $(input);
            if (input.val() === "") {
                var row = input.closest("tr");
                this._deleteRow(row);
            } else {
                this.info[input.data("id")] = input.val();
                if (this.options["parameter_manager"] !== undefined) {
                    this.options["parameter_manager"].add(input, "int", false);
                }
            }
        },

        getInfo: function() {
            return this.info;
        },

        setInfo: function(info) {
            this.info = info;
            _drawTable();
        }
    });
})(jQuery);
<commit_msg>[IMP] Better ParameterManager in FieldArea widget<commit_after>/*
* -*- mode: text; coding: utf-8; -*-

   This file is part of Indico.
   Copyright (C) 2002 - 2013 European Organization for Nuclear Research (CERN).

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

   Indico 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/

(function($) {
    $.widget("ui.fieldarea", {

        options: {
            fields_caption: "field",
            parameter_manager: undefined,
            parameter_type: "text"
        },

        _create: function() {
            var self = this;

            self.info = {};
            self.info["next_index"] = 0;

            self.table = $("

");
            self.element.addClass("field-area scrollable");
            self.element.append(self.table);

            self._handleEvents();
            self._drawTable();
        },

        _handleEvents: function() {
            var self = this;

            self.element.on("focusout", "input", function(e) {
                self._updateField(this);
            });

            self.element.on("click", "a", function(e) {
                e.preventDefault();
                self._deleteRow($(this).closest("tr"));
            });

            self.element.on("keyup propertychange paste", "input", function(e) {
                // Enter
                if (e.type == "keyup" && e.which == 13) {
                    $(this).blur();
                }

                if ($(this).val() === "") {
                    self._deleteInput($(this).closest("tr"));
                }

                self._drawInput();
            });

            self.element.on("keydown", "input", function(e) {
                // ESC
                if (e.which == 27) {
                    e.stopPropagation();
                    value = self.info[$(this).data("id")];
                    $(this).val(value);
                    $(this).blur();
                }
            });
        },

        _drawTable: function() {
            var self = this;
            var table = self.table;

            table.find("tr").each(function() {
                $(this).remove();
            });

            for (var key in self.info) {
                if (!isNaN(key)) {
                    table.append(self._row(key));
                }
            }

            self._drawInput();
        },

        _drawInput: function() {
            if (this.new_row === undefined || this.new_row.find("input").val() !== "") {
                this.new_row = this._row();
                this.table.append(this.new_row);
                this.element.scrollTop(this.element[0].scrollHeight);
            }
        },

        _deleteInput: function(row) {
            if (row.next()[0] == this.new_row[0]) {
                this._prevIndex();
                this.new_row.remove();
                this.new_row = row;
                this._removeFromPM(row.find("input"));
            }
        },

        destroy: function() {
            this.element.off("focusout click keyup propertychange paste");
            this.element.removeClass("field-area scrollable");
            this.table.remove();
        },

        _deleteRow: function(row) {
            if (row[0] != this.new_row[0]) {
                var id = $(this).closest("tr").find("input").data("id");
                delete this.info[id];
                this._removeFromPM(row.find("input"));
                row.remove();
            }
        },

        _nextIndex: function() {
            return this.info["next_index"]++;
        },

        _prevIndex: function() {
            return this.info["next_index"]--;
        },

        _addToPM: function(input) {
            if (this.options["parameter_manager"] !== undefined) {
                var parameter_type = this.options["parameter_type"];
                this.options["parameter_manager"].remove(input);
                this.options["parameter_manager"].add(input, parameter_type, false);
            }
        },

        _removeFromPM: function(input) {
            if (this.options["parameter_manager"] !== undefined) {
                this.options["parameter_manager"].remove(input);
            }
        },

        _row: function(id) {
            var value;
            var placeholder = "Type to add " + this.options["fields_caption"];

            if (id !== undefined) {
                value = this.info[id];
            } else {
                id = this._nextIndex();
                value = "";
            }

            var row = $("

");
            var dragger = $(".	");
            var field = $("<input class='input-text' type='text' data-id='"+ id +"' placeholder='"+ placeholder+"' value='"+ value +"'/>	");
            var remove = $("	");

            return row.append(dragger).append(field).append(remove);
        },

        _updateField: function(input) {
            input = $(input);
            if (input.val() === "") {
                var row = input.closest("tr");
                this._deleteRow(row);
            } else {
                this.info[input.data("id")] = input.val();
                this._addToPM(input);
            }
        },

        getInfo: function() {
            return this.info;
        },

        setInfo: function(info) {
            this.info = info;
            _drawTable();
        }
    });
})(jQuery);
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/rest/hello', function (req, res) {
  res.json({reply: 'Hello World!'});
});

app.listen(3000, function () {
  console.log('Starting app);
});

<commit_msg>added angular to backend<commit_after>var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/api/hello', function (req, res) {
  res.json({reply: 'Hello World!'});
});

app.listen(3000, function () {
  console.log('Starting app');
});

<|endoftext|>


<commit_before>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

import React from 'react';

import MatrixClientPeg from '../../../MatrixClientPeg';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from '../../../Modal';

export default class CrossSigningPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = this._getUpdatedStatus();
    }

    _getUpdatedStatus() {
        // XXX: Add public accessors if we keep this around in production
        const cli = MatrixClientPeg.get();
        const crossSigning = cli._crypto._crossSigningInfo;
        const secretStorage = cli._crypto._secretStorage;
        const crossSigningPublicKeysOnDevice = crossSigning.getId();
        const crossSigningPrivateKeysInStorage = crossSigning.isStoredInSecretStorage(secretStorage);
        const secretStorageKeyInAccount = secretStorage.hasKey();

        return {
            crossSigningPublicKeysOnDevice,
            crossSigningPrivateKeysInStorage,
            secretStorageKeyInAccount,
        };
    }

    _bootstrapSecureSecretStorage = async () => {
        try {
            const InteractiveAuthDialog = sdk.getComponent("dialogs.InteractiveAuthDialog");
            await MatrixClientPeg.get().bootstrapSecretStorage({
                authUploadDeviceSigningKeys: async (makeRequest) => {
                    const { finished } = Modal.createTrackedDialog(
                        'Cross-signing keys dialog', '', InteractiveAuthDialog,
                        {
                            title: _t("Send cross-signing keys to homeserver"),
                            matrixClient: MatrixClientPeg.get(),
                            makeRequest,
                        },
                    );
                    const [confirmed] = await finished;
                    if (!confirmed) {
                        throw new Error("Cross-signing key upload auth canceled");
                    }
                },
            });
        } catch (e) {
            console.error(e);
        }
        this.setState(this._getUpdatedStatus());
    }

    render() {
        const AccessibleButton = sdk.getComponent("elements.AccessibleButton");
        const {
            crossSigningPublicKeysOnDevice,
            crossSigningPrivateKeysInStorage,
            secretStorageKeyInAccount,
        } = this.state;

        return (

                        {_t("Cross-signing public keys:")}
                        {crossSigningPublicKeysOnDevice ? _t("on device") : _t("not found")}

                        {_t("Cross-signing private keys:")}
                        {crossSigningPrivateKeysInStorage ? _t("in secret storage") : _t("not found")}

                        {_t("Secret storage public key:")}
                        {secretStorageKeyInAccount ? _t("in account data") : _t("not found")}

                    <AccessibleButton kind="primary" onClick={this._bootstrapSecureSecretStorage}>
                        {_t("Bootstrap Secure Secret Storage")}
                    </AccessibleButton>

        );
    }
}
<commit_msg>Add error to debug panel<commit_after>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

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

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

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

import React from 'react';

import MatrixClientPeg from '../../../MatrixClientPeg';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from '../../../Modal';

export default class CrossSigningPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            ...this._getUpdatedStatus(),
        };
    }

    _getUpdatedStatus() {
        // XXX: Add public accessors if we keep this around in production
        const cli = MatrixClientPeg.get();
        const crossSigning = cli._crypto._crossSigningInfo;
        const secretStorage = cli._crypto._secretStorage;
        const crossSigningPublicKeysOnDevice = crossSigning.getId();
        const crossSigningPrivateKeysInStorage = crossSigning.isStoredInSecretStorage(secretStorage);
        const secretStorageKeyInAccount = secretStorage.hasKey();

        return {
            crossSigningPublicKeysOnDevice,
            crossSigningPrivateKeysInStorage,
            secretStorageKeyInAccount,
        };
    }

    _bootstrapSecureSecretStorage = async () => {
        this.setState({ error: null });
        try {
            const InteractiveAuthDialog = sdk.getComponent("dialogs.InteractiveAuthDialog");
            await MatrixClientPeg.get().bootstrapSecretStorage({
                authUploadDeviceSigningKeys: async (makeRequest) => {
                    const { finished } = Modal.createTrackedDialog(
                        'Cross-signing keys dialog', '', InteractiveAuthDialog,
                        {
                            title: _t("Send cross-signing keys to homeserver"),
                            matrixClient: MatrixClientPeg.get(),
                            makeRequest,
                        },
                    );
                    const [confirmed] = await finished;
                    if (!confirmed) {
                        throw new Error("Cross-signing key upload auth canceled");
                    }
                },
            });
        } catch (e) {
            this.setState({ error: e });
            console.error(e);
        }
        this.setState(this._getUpdatedStatus());
    }

    render() {
        const AccessibleButton = sdk.getComponent("elements.AccessibleButton");
        const {
            error,
            crossSigningPublicKeysOnDevice,
            crossSigningPrivateKeysInStorage,
            secretStorageKeyInAccount,
        } = this.state;

        let errorSection;
        if (error) {
            errorSection =
{error.toString()}
;
        }

        return (

                        {_t("Cross-signing public keys:")}
                        {crossSigningPublicKeysOnDevice ? _t("on device") : _t("not found")}

                        {_t("Cross-signing private keys:")}
                        {crossSigningPrivateKeysInStorage ? _t("in secret storage") : _t("not found")}

                        {_t("Secret storage public key:")}
                        {secretStorageKeyInAccount ? _t("in account data") : _t("not found")}

                    <AccessibleButton kind="primary" onClick={this._bootstrapSecureSecretStorage}>
                        {_t("Bootstrap Secure Secret Storage")}
                    </AccessibleButton>

                {errorSection}

        );
    }
}
<|endoftext|>


<commit_before>'use strict'

const config = require('config')

const logAPI = module.exports = {}

logAPI.get = function *() {
  var token

  // TODO: Add support for session cookie authentication.

  token = this.token

  // Check necessary if fields are provided.
  if (!token._id) this.throw('User id is required.', 400)
  var log = this.query.log
  if (!log) this.throw('Log has no content.', 400)

  var payload = [{
    topic: config.kafkaTopic,
    messages: log
  }]

  // Commit logs to kafka.
  yield this.kafkaClient.send(payload)

  this.body = {
    token: token,
    log: log
  }
}
<commit_msg>Modify payload format for kafka message<commit_after>'use strict'

const config = require('config')

const logAPI = module.exports = {}

logAPI.get = function *() {
  var token

  // TODO: Add support for session cookie authentication.

  token = this.token

  // Check necessary if fields are provided.
  if (!token._id) this.throw('User id is required.', 400)
  if (!log) this.throw('Log has no content.', 400)

  var payload = {
    topic: config.kafkaTopic,
    messages: log
  }

  // Commit logs to kafka.
  yield this.kafkaClient.send([payload])

  this.body = {
    token: token,
    log: log
  }
}
<|endoftext|>


<commit_before>import 'babel/polyfill';
import './client/lib/index';

import $ from 'jquery';
import React from 'react';
import Router from 'react-router';
import app from 'app/client/components/main/app';
import routes from './routes';
import configureStore from './client/stores/index';

$(document).ready(() => {
  const appDOM = document.getElementById('app');
  const store = configureStore(window.__data);

  Router.run(routes, Router.HistoryLocation, (Handler, routerState) => {
    React.render(app(store, Handler, routerState), appDOM);
  });
});
<commit_msg>Allow fetchData in development mode<commit_after>import 'babel/polyfill';
import './client/lib/index';

import $ from 'jquery';
import React from 'react';
import Router from 'react-router';
import app from 'app/client/components/main/app';
import routes from './routes';
import configureStore from './client/stores/index';

$(document).ready(() => {
  const appDOM = document.getElementById('app');
  const store = configureStore(window.__data);

  if (process.env.NODE_ENV === 'development') {
    const fetchData = require('./client/helpers/fetch-data');
    let areFetchedData = false;

    Router.run(routes, Router.HistoryLocation, (Handler, routerState) => {
      if (!areFetchedData) {
        fetchData(store, routerState);
        areFetchedData = true;
      }
      React.render(app(store, Handler, routerState), appDOM);
    });
  } else {
    Router.run(routes, Router.HistoryLocation, (Handler, routerState) => {
      React.render(app(store, Handler, routerState), appDOM);
    });
  }
});
<|endoftext|>


<commit_before>var express = require('express'),
	routes = require('./routes'),
	User = require('./routes/user'),
	Game = require('./routes/game'),
	http = require('http'),
	expressLayouts = require('express-ejs-layouts'),
	path = require('path'),
	app = express(),
	mongoose = require('mongoose');

//shared server
//var dbPath = 'mongodb://192.168.241.233/pingpong';
//local server
var dbPath = 'mongodb://localhost/local';
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// configure Express
app.configure(function() {
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.set('layout', 'layout');
	app.use(expressLayouts);
	app.use(express.favicon());
	//app.use(express.logger('dev')); //this spams my logs
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('your secret here'));
	app.use(express.session());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
	mongoose.connect(dbPath, function onMongooseError(err) {
		if (err) throw err;
	});
});

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

var playerSchema = mongoose.Schema({
	fname: String,
	lname: String,
	nickname: String
})

//two players for now...
var gameSchema = mongoose.Schema({
	redPlayer: String,
	bluePlayer: String,
	matches: [matchSchema],
	redPlayerDetails: [playerSchema], // Populatd by route logic
	bluePlayerDetails: [playerSchema] // Populated by route logic
})

var matchSchema = mongoose.Schema({
	redScore: String,
	blueScore: String
})

var teamSchema = mongoose.Schema({
	redPlayer: String,
	bluePlayer: String
})

var Players = mongoose.model('players', playerSchema);
var Games = mongoose.model('games', gameSchema);
var Matches = mongoose.model('matches', matchSchema);
var Teams = mongoose.model('teams', teamSchema);

user = new User({Players: Players});
game = new Game({Games: Games, Players: Players});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

app.get('/', routes.index);
app.get('/users', function(){ user.list.apply(user, arguments) });
app.post('/users', function(){ user.add.apply(user, arguments) });

app.get('/games', function(){ game.list.apply(game, arguments) });
app.post('/games', function(){ game.add.apply(game, arguments) });
app.get('/games/json', function(){ game.json.apply(game, arguments) });<commit_msg>Notes about TODO<commit_after>var express = require('express'),
	routes = require('./routes'),
	User = require('./routes/user'),
	Game = require('./routes/game'),
	http = require('http'),
	expressLayouts = require('express-ejs-layouts'),
	path = require('path'),
	app = express(),
	mongoose = require('mongoose');

//shared server
//var dbPath = 'mongodb://192.168.241.233/pingpong';
//local server
var dbPath = 'mongodb://localhost/local';
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// configure Express
app.configure(function() {
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.set('layout', 'layout');
	app.use(expressLayouts);
	app.use(express.favicon());
	//app.use(express.logger('dev')); //this spams my logs
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('your secret here'));
	app.use(express.session());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
	mongoose.connect(dbPath, function onMongooseError(err) {
		if (err) throw err;
	});
});

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

var playerSchema = mongoose.Schema({
	fname: String,
	lname: String,
	nickname: String
})

//two players for now...
var gameSchema = mongoose.Schema({
	redPlayer: String,
	bluePlayer: String,
	matches: [matchSchema],
	redPlayerDetails: [playerSchema], // TODO: Get these out of arrays
	bluePlayerDetails: [playerSchema] // TODO: Get these out of arrays
})

var matchSchema = mongoose.Schema({
	redScore: String,
	blueScore: String
})

var teamSchema = mongoose.Schema({
	redPlayer: String,
	bluePlayer: String
})

var Players = mongoose.model('players', playerSchema);
var Games = mongoose.model('games', gameSchema);
var Matches = mongoose.model('matches', matchSchema);
var Teams = mongoose.model('teams', teamSchema);

user = new User({Players: Players});
game = new Game({Games: Games, Players: Players});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

app.get('/', routes.index);
app.get('/users', function(){ user.list.apply(user, arguments) });
app.post('/users', function(){ user.add.apply(user, arguments) });

app.get('/games', function(){ game.list.apply(game, arguments) });
app.post('/games', function(){ game.add.apply(game, arguments) });
app.get('/games/json', function(){ game.json.apply(game, arguments) });<|endoftext|>