<commit_before>/*jshint node:true*/

'use strict';

var path = require('path');
var fs = require('fs');
var jshintTrees = require('broccoli-jshint');
var MergeTrees = require('broccoli-merge-trees');
var BabelTranspiler = require('broccoli-babel-transpiler');
var Concat = require('broccoli-concat');
var Funnel = require('broccoli-funnel');
var resolve = require('resolve');
var VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'Ember CLI Mocha',

  overrideTestCommandFilter: function() {
    var TestCommand = this.project.require('ember-cli/lib/commands/test');

    TestCommand.prototype.buildTestPageQueryString = function(options) {
      var params = [];

      if (options.filter) {
        params.push('grep=' + options.filter);

        if (options.invert) {
           params.push('invert=1');
        }
      }

      if (options.query) {
        params.push(options.query);
      }

      return params.join('&');
    };

    TestCommand.prototype.availableOptions.push({
      name: 'invert',
      type: Boolean,
      default: false,
      description: 'Invert the filter specified by the --filter argument',
      aliases: ['i']
    });
  },

  _getDependencyTrees: function() {
    if (this._dependencyTrees) {
      return this._dependencyTrees;
    }

    var emberTestHelpersPath = path.dirname(resolve.sync('ember-test-helpers', { basedir: this._emberMochaLibPath }));
    var klassyPath = path.dirname(resolve.sync('klassy', { basedir: emberTestHelpersPath }));

    this._dependencyTrees = [
      this.treeGenerator(this._emberMochaLibPath),
      this.treeGenerator(emberTestHelpersPath),
      this.treeGenerator(klassyPath)
    ];

    return this._dependencyTrees;
  },

  init: function() {
    this.overrideTestCommandFilter();

    var checker = new VersionChecker(this);
    var dep = checker.for('ember-cli', 'npm');

    this._shouldImportEmberMocha = !dep.gt('2.2.0-alpha');
    this._emberMochaLibPath = path.dirname(resolve.sync('ember-mocha'));

    this.setTestGenerator();
  },

  postBuild: function () {
    this.checkPackages();
  },

  checkPackages: function () {
    var packages = Object.keys(this.project.addonPackages);
    if (packages.indexOf('ember-cli-qunit') !== -1) {
      console.warn('\nIt looks like you are using "ember-cli-qunit" which can cause issues with "ember-cli-mocha", please remove this package.\n');
      process.exit(1);
    }
    if (packages.indexOf('ember-cli-htmlbars-inline-precompile') < 0) {
      console.warn('\nIt looks like you\'re not on ember-cli 1.13, which includes ember-cli-htmlbars-inline-precompile by default. Please run: ember install ember-cli-htmlbars-inline-precompile.\n');
      process.exit(1);
    }
  },

  blueprintsPath: function() {
    return path.join(__dirname, 'blueprints');
  },

  treeForVendor: function(tree) {
    var emberMochaBuildSupportPath = path.join(this._emberMochaLibPath, '..', 'build-support');

    var mochaSetupTree = new Funnel(emberMochaBuildSupportPath, {
      files: ['mocha-setup.js'],
      destDir: '/ember-mocha'
    });

    var trees = [
      tree,
      mochaSetupTree
    ];

    if (this._shouldImportEmberMocha) {
      // support for Ember CLI < 2.2.0-beta.1
      var depTree = new MergeTrees(this._getDependencyTrees());

      var transpiled = new BabelTranspiler(depTree, {
        loose: true,
        moduleIds: true,
        modules: 'amdStrict'
      });

      var concattedTree = new Concat(transpiled, {
        inputFiles: ['**/*.js'],
        outputFile: '/ember-mocha/ember-mocha.js',
        annotation: 'Concat: Ember Mocha'
      });

      trees.push(concattedTree);
    }

    return new MergeTrees(trees, {
      annotation: 'ember-cli-mocha: treeForVendor'
    });
  },

  treeForAddonTestSupport: function() {
    // for Ember CLI >= 2.2.0-beta.1
    return new MergeTrees(this._getDependencyTrees());
  },

  included: function included(app, parentAddon) {
    var target = (parentAddon || app);
    this._super.included.call(this, target);

    this.options = target.options;

    if (app.tests) {
      var fileAssets = [
        app.bowerDirectory + '/mocha/mocha.js',
        app.bowerDirectory + '/mocha/mocha.css',
        app.bowerDirectory + '/chai/chai.js',
        'vendor/ember-mocha/mocha-setup.js',
        app.bowerDirectory + '/ember-mocha-adapter/adapter.js',
        'vendor/ember-cli-mocha/test-loader.js'
      ];

      if (this._shouldImportEmberMocha) {
        // support for Ember CLI < 2.2.0-beta.1
        fileAssets.push('vendor/ember-mocha/ember-mocha.js');
      }

      var addonOptions = app.options['ember-cli-mocha'] || {};
      if (addonOptions && !addonOptions.disableContainerStyles) {
        fileAssets.push('vendor/ember-cli-mocha/test-container-styles.css');
      }

      app.import(app.bowerDirectory + '/ember-cli-shims/test-shims.js', {
        type: 'test'
      });

      fileAssets.forEach(function(file){
        app.import(file, {
          type: 'test'
        });
      });
    }
    this.jshintrc = app.options.jshintrc;
  },

  contentFor: function(type) {
    if (type === 'test-body') {
      return this._readTemplate('test-body');
    }
  },

  _readTemplate: function(name) {
    return fs.readFileSync(path.join(__dirname, 'templates', name + '.html'));
  },

  setTestGenerator: function() {
    this.project.generateTestFile = function(moduleName, tests) {
      var output = "describe('" + moduleName + "', function() {\n";

      tests.forEach(function(test) {
        output += "  it('" + test.name + "', function() {\n";
        output += "    expect(" + test.passed + ", '" + test.errorMessage + "').to.be.ok;\n";
        output += "  });\n";
      });

      output += "});\n";

      return output;
    };
  },

  lintTree: function(type, tree) {
    var project = this.project;

    // Skip if useLintTree === false.
    if (this.options && this.options['ember-cli-mocha'] && this.options['ember-cli-mocha'].useLintTree === false) {
      // Fakes an empty broccoli tree
      return { inputTree: tree, rebuild: function() { return []; } };
    }

    return jshintTrees(tree, {
      jshintrcPath: this.jshintrc[type],
      description: 'JSHint ' + type + '- Mocha',
      testGenerator: function(relativePath, passed, errors) {
        if (errors) {
          errors = "\\n" + this.escapeErrorString(errors);
        } else {
          errors = "";
        }

        return project.generateTestFile('JSHint - ' + relativePath, [{
          name: 'should pass jshint',
          passed: !!passed,
          errorMessage: relativePath + ' should pass jshint.' + errors
        }]);
      }
    });
  }
};
<commit_msg>Opt out of linting when another linter is present.<commit_after>/*jshint node:true*/

'use strict';

var path = require('path');
var fs = require('fs');
var jshintTrees = require('broccoli-jshint');
var MergeTrees = require('broccoli-merge-trees');
var BabelTranspiler = require('broccoli-babel-transpiler');
var Concat = require('broccoli-concat');
var Funnel = require('broccoli-funnel');
var resolve = require('resolve');
var VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'Ember CLI Mocha',

  overrideTestCommandFilter: function() {
    var TestCommand = this.project.require('ember-cli/lib/commands/test');

    TestCommand.prototype.buildTestPageQueryString = function(options) {
      var params = [];

      if (options.filter) {
        params.push('grep=' + options.filter);

        if (options.invert) {
           params.push('invert=1');
        }
      }

      if (options.query) {
        params.push(options.query);
      }

      return params.join('&');
    };

    TestCommand.prototype.availableOptions.push({
      name: 'invert',
      type: Boolean,
      default: false,
      description: 'Invert the filter specified by the --filter argument',
      aliases: ['i']
    });
  },

  _getDependencyTrees: function() {
    if (this._dependencyTrees) {
      return this._dependencyTrees;
    }

    var emberTestHelpersPath = path.dirname(resolve.sync('ember-test-helpers', { basedir: this._emberMochaLibPath }));
    var klassyPath = path.dirname(resolve.sync('klassy', { basedir: emberTestHelpersPath }));

    this._dependencyTrees = [
      this.treeGenerator(this._emberMochaLibPath),
      this.treeGenerator(emberTestHelpersPath),
      this.treeGenerator(klassyPath)
    ];

    return this._dependencyTrees;
  },

  init: function() {
    this.overrideTestCommandFilter();

    var checker = new VersionChecker(this);
    var dep = checker.for('ember-cli', 'npm');

    this._shouldImportEmberMocha = !dep.gt('2.2.0-alpha');
    this._emberMochaLibPath = path.dirname(resolve.sync('ember-mocha'));

    this.setTestGenerator();
  },

  postBuild: function () {
    this.checkPackages();
  },

  checkPackages: function () {
    var packages = Object.keys(this.project.addonPackages);
    if (packages.indexOf('ember-cli-qunit') !== -1) {
      console.warn('\nIt looks like you are using "ember-cli-qunit" which can cause issues with "ember-cli-mocha", please remove this package.\n');
      process.exit(1);
    }
    if (packages.indexOf('ember-cli-htmlbars-inline-precompile') < 0) {
      console.warn('\nIt looks like you\'re not on ember-cli 1.13, which includes ember-cli-htmlbars-inline-precompile by default. Please run: ember install ember-cli-htmlbars-inline-precompile.\n');
      process.exit(1);
    }
  },

  blueprintsPath: function() {
    return path.join(__dirname, 'blueprints');
  },

  treeForVendor: function(tree) {
    var emberMochaBuildSupportPath = path.join(this._emberMochaLibPath, '..', 'build-support');

    var mochaSetupTree = new Funnel(emberMochaBuildSupportPath, {
      files: ['mocha-setup.js'],
      destDir: '/ember-mocha'
    });

    var trees = [
      tree,
      mochaSetupTree
    ];

    if (this._shouldImportEmberMocha) {
      // support for Ember CLI < 2.2.0-beta.1
      var depTree = new MergeTrees(this._getDependencyTrees());

      var transpiled = new BabelTranspiler(depTree, {
        loose: true,
        moduleIds: true,
        modules: 'amdStrict'
      });

      var concattedTree = new Concat(transpiled, {
        inputFiles: ['**/*.js'],
        outputFile: '/ember-mocha/ember-mocha.js',
        annotation: 'Concat: Ember Mocha'
      });

      trees.push(concattedTree);
    }

    return new MergeTrees(trees, {
      annotation: 'ember-cli-mocha: treeForVendor'
    });
  },

  treeForAddonTestSupport: function() {
    // for Ember CLI >= 2.2.0-beta.1
    return new MergeTrees(this._getDependencyTrees());
  },

  included: function included(app, parentAddon) {
    var target = (parentAddon || app);
    this._super.included.call(this, target);

    this.options = target.options || {};

    if (app.tests) {
      var fileAssets = [
        app.bowerDirectory + '/mocha/mocha.js',
        app.bowerDirectory + '/mocha/mocha.css',
        app.bowerDirectory + '/chai/chai.js',
        'vendor/ember-mocha/mocha-setup.js',
        app.bowerDirectory + '/ember-mocha-adapter/adapter.js',
        'vendor/ember-cli-mocha/test-loader.js'
      ];

      if (this._shouldImportEmberMocha) {
        // support for Ember CLI < 2.2.0-beta.1
        fileAssets.push('vendor/ember-mocha/ember-mocha.js');
      }

      var addonOptions = app.options['ember-cli-mocha'] || {};
      if (addonOptions && !addonOptions.disableContainerStyles) {
        fileAssets.push('vendor/ember-cli-mocha/test-container-styles.css');
      }

      app.import(app.bowerDirectory + '/ember-cli-shims/test-shims.js', {
        type: 'test'
      });

      fileAssets.forEach(function(file){
        app.import(file, {
          type: 'test'
        });
      });
    }
    this.jshintrc = app.options.jshintrc;
  },

  contentFor: function(type) {
    if (type === 'test-body') {
      return this._readTemplate('test-body');
    }
  },

  _readTemplate: function(name) {
    return fs.readFileSync(path.join(__dirname, 'templates', name + '.html'));
  },

  setTestGenerator: function() {
    this.project.generateTestFile = function(moduleName, tests) {
      var output = "describe('" + moduleName + "', function() {\n";

      tests.forEach(function(test) {
        output += "  it('" + test.name + "', function() {\n";
        output += "    expect(" + test.passed + ", '" + test.errorMessage + "').to.be.ok;\n";
        output += "  });\n";
      });

      output += "});\n";

      return output;
    };
  },

  lintTree: function(type, tree) {
    var project = this.project;

    var addonContext = this;
    var disableLinting = this.options['ember-cli-mocha'] && this.options['ember-cli-mocha'].useLintTree === false;
    var lintingAddonExists = this.project.addons.filter(function(addon) {
      return addonContext !== addon && addon.lintTree && addon.isDefaultJSLinter;
    }).length > 0;

    // Skip if useLintTree === false or another primary linter addon is present
    if (disableLinting || lintingAddonExists) {
      // Fakes an empty broccoli tree
      return { inputTree: tree, rebuild: function() { return []; } };
    }

    return jshintTrees(tree, {
      jshintrcPath: this.jshintrc[type],
      description: 'JSHint ' + type + '- Mocha',
      testGenerator: function(relativePath, passed, errors) {
        if (errors) {
          errors = "\\n" + this.escapeErrorString(errors);
        } else {
          errors = "";
        }

        return project.generateTestFile('JSHint - ' + relativePath, [{
          name: 'should pass jshint',
          passed: !!passed,
          errorMessage: relativePath + ' should pass jshint.' + errors
        }]);
      }
    });
  }
};
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 5000;

// app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 'home' page
app.get('/', (req, res) => res.render('pages/index'));
// about page
app.get('/about', (req, res) => res.render('pages/about'));
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
<commit_msg>Update server configuration.<commit_after>// server.js
// load the things we need
const express = require('express');
const app = express();

const PORT = process.env.PORT || 8080;

// set the view engine to ejs
app.set('view engine', 'ejs');

// index page
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(PORT);
console.log('8080 is the magic port');
<|endoftext|>


<commit_before>'use strict';
var got = require('got');
var cheerio = require('cheerio');
var Promise = require('pinkie-promise');

function remuseChars(getString) {
	const finalVerp = getString.split('is')[0].trim();

	return finalVerp;
}

module.exports = function (packageName) {
	if (typeof packageName !== 'string') {
		return Promise.reject(new Error('package name required'));
	}

	var url = 'https://www.npmjs.com/packages/' + packageName;

	return got(url).then(function (res) {
		var $ = cheerio.load(res.body);

		return remuseChars($('.box li').eq(1).text()) || null;
	}).catch(function (err) {
		if (err.statusCode === 404) {
			err.message = 'Package doesn\'t exist';
		}

		throw err;
	});
};
<commit_msg>>1 | pass<commit_after>'use strict';
var got = require('got');
var cheerio = require('cheerio');
var Promise = require('pinkie-promise');

function remuseChars(getString) {
	var finalVerp = getString.split('is')[0].trim();

	return finalVerp;
}

module.exports = function (packageName) {
	if (typeof packageName !== 'string') {
		return Promise.reject(new Error('package name required'));
	}

	var url = 'https://www.npmjs.com/packages/' + packageName;

	return got(url).then(function (res) {
		var $ = cheerio.load(res.body);

		return remuseChars($('.box li').eq(1).text()) || null;
	}).catch(function (err) {
		if (err.statusCode === 404) {
			err.message = 'Package doesn\'t exist';
		}

		throw err;
	});
};
<|endoftext|>


<commit_before>//really simple data replication.

var EventEmitter = require('events').EventEmitter
var i = require('iterate')
var duplex = require('duplex')
var inherits = require('util').inherits
var serializer = require('stream-serializer')
var u = require('./util')
exports =
module.exports = Scuttlebutt

exports.createID = u.createID
exports.updateIsRecent = u.filter
exports.filter = u.filter
exports.timestamp = u.timestamp

function dutyOfSubclass() {
  throw new Error('method must be implemented by subclass')
}

function validate (data) {
  //must be an 4 element array
  //string, *, string, number
  //log a message and ignore if invalid.
  function error () {
    console.error('invalid update', data)
  }
  var key = data[0], ts = data[2], source = data[3]

  /*console.log(!Array.isArray(data)
    , data.length !== 4
    , 'string'    !== typeof key
    , 'string'    !== typeof source
    , 'number'    !== typeof ts
  )*/

  if(  !Array.isArray(data)
    || data.length !== 4
    || 'string'    !== typeof key
    || 'string'    !== typeof source
    || 'number'    !== typeof ts
  )
    return error(), false

  return true
}

inherits (Scuttlebutt, EventEmitter)

function Scuttlebutt (id) {
  if(!(this instanceof Scuttlebutt)) return new Scuttlebutt(id)
  this.sources = {}
  this.id = id = id || u.createID()
}

var sb = Scuttlebutt.prototype

var emit = EventEmitter.prototype.emit

sb.applyUpdate = dutyOfSubclass
sb.history      = dutyOfSubclass

sb.localUpdate = function (key, value) {
  this._update([key, value, u.timestamp(), this.id])
  return this
}

//checks whether this update is valid.

sb._update = function (update) {
  var ts = update[2]
  var source = update[3]

  //if this message is old for it's source,
  //ignore it. it's out of order.
  //each node must emit it's changes in order!

  var latest = this.sources[source]
  if(latest && latest >= ts)
    return emit.call(this, 'old_data', update), false

  this.sources[source] = ts

  //check if this message is older than
  //the value we already have.
  //do nothing if so
  //emit an 'old-data' event because i'll want to track how many
  //unnecessary messages are sent.
  if(this.applyUpdate(update)) {
    emit.call(this, '_update', update)
    return true
  }

  //key, value, timestamp, source
  return false
}

sb.createStream = function (opts) {
  var self = this
  //the sources for the remote end.
  var sources = {}
  var d = duplex()
  var outer = serializer(opts && opts.wrapper)(d)
  outer.inner = d
  d
    .on('write', function (data) {
    //if it's an array, it's an update.
    //if it's an object, it's a scuttlebut digest.
      if(Array.isArray(data)) {
        if(validate(data))
          return self._update(data)
      }
      else if('object' === typeof data && data) {
        //when the digest is recieved from the other end,
        //send the history.
        //merge with the current list of sources.
        sources = data
        i.each(self.history(sources), d.emitData.bind(d))
        outer.emit('sync')
      }
    }).on('ended', function () { d.emitEnd() })
    .on('close', function () {
      self.removeListener('data', onUpdate)
    })

  function onUpdate (update) { //key, value, source, ts) {
    if(!u.filter(update, sources))
      return

    //if I put this after source[source]= ... it breaks tests
    d.emitData(update)

    //really, this should happen before emitting.
    var ts = update[2]
    var source = update[3]
    sources[source] = ts
  }
  d.emitData(self.sources)
  self.on('_update', onUpdate)
  return outer
}

<commit_msg>createReadStream, and createWriteStream for persitance<commit_after>//really simple data replication.

var EventEmitter = require('events').EventEmitter
var i = require('iterate')
var duplex = require('duplex')
var inherits = require('util').inherits
var serializer = require('stream-serializer')
var u = require('./util')
var ReadableStream = require('readable-stream')

exports =
module.exports = Scuttlebutt

exports.createID = u.createID
exports.updateIsRecent = u.filter
exports.filter = u.filter
exports.timestamp = u.timestamp

function dutyOfSubclass() {
  throw new Error('method must be implemented by subclass')
}

function validate (data) {
  //must be an 4 element array
  //string, *, string, number
  //log a message and ignore if invalid.
  function error () {
    console.error('invalid update', data)
  }
  var key = data[0], ts = data[2], source = data[3]

  /*console.log(!Array.isArray(data)
    , data.length !== 4
    , 'string'    !== typeof key
    , 'string'    !== typeof source
    , 'number'    !== typeof ts
  )*/

  if(  !Array.isArray(data)
    || data.length !== 4
    || 'string'    !== typeof key
    || 'string'    !== typeof source
    || 'number'    !== typeof ts
  )
    return error(), false

  return true
}

inherits (Scuttlebutt, EventEmitter)

function Scuttlebutt (id) {
  if(!(this instanceof Scuttlebutt)) return new Scuttlebutt(id)
  this.sources = {}
  this.id = id = id || u.createID()
}

var sb = Scuttlebutt.prototype

var emit = EventEmitter.prototype.emit

sb.applyUpdate = dutyOfSubclass
sb.history      = dutyOfSubclass

sb.localUpdate = function (key, value) {
  this._update([key, value, u.timestamp(), this.id])
  return this
}

//checks whether this update is valid.

sb._update = function (update) {
  var ts = update[2]
  var source = update[3]

  //if this message is old for it's source,
  //ignore it. it's out of order.
  //each node must emit it's changes in order!

  var latest = this.sources[source]
  if(latest && latest >= ts)
    return emit.call(this, 'old_data', update), false

  this.sources[source] = ts

  //check if this message is older than
  //the value we already have.
  //do nothing if so
  //emit an 'old-data' event because i'll want to track how many
  //unnecessary messages are sent.
  if(this.applyUpdate(update)) {
    emit.call(this, '_update', update)
    return true
  }

  //key, value, timestamp, source
  return false
}

sb.createStream = function (opts) {
  var self = this
  //the sources for the remote end.
  var sources = {}, other
  var d = duplex()
  var outer = serializer(opts && opts.wrapper)(d)
  outer.inner = d
  d
    .on('write', function (data) {
    //if it's an array, it's an update.
    //if it's an object, it's a scuttlebut digest.
      if(Array.isArray(data)) {
        if(validate(data))
          return self._update(data)
      }
      else if('object' === typeof data && data) {
        //when the digest is recieved from the other end,
        //send the history.
        //merge with the current list of sources.
        sources = data
        i.each(self.history(sources), d.emitData.bind(d))
        outer.emit('sync')
      }
    }).on('ended', function () { d.emitEnd() })
    .on('close', function () {
      self.removeListener('data', onUpdate)
    })

  function onUpdate (update) { //key, value, source, ts) {
    if(!u.filter(update, sources))
      return

    //if I put this after source[source]= ... it breaks tests
    d.emitData(update)

    //really, this should happen before emitting.
    var ts = update[2]
    var source = update[3]
    sources[source] = ts
  }
  d.emitData(self.sources)
  self.on('_update', onUpdate)
  return outer
}

//createReadStream -- for persisting.

sb.createReadStream = function (opts) {
  opts = opts || {}

  //write this.id
  //then write the histroy.
  //then, if opts.tail
  //listen for updates, else emit 'end'

  var out = this.history()
  out.unshift(this.id)

  var wrapper = ({
    json: function (e) { return JSON.stringify(e) + '\n' },
    raw: function (e) { return e }
  }) [opts.wrapper || 'json']

  var rs = new ReadableStream()
  rs.read = function () {
    var data = out.shift()
    console.log('>>', data)
    if(!data && !opts.tail)
      return this.emit('end'), null

    return wrapper(data)
  }

  if(opts.tail) {
    this.on('_update', function (update) {
      out.push(update)
      rs.emit('readable')
    })
  }

  return rs
}

sb.createWriteStream = function (opts) {
  opts = opts || {}
  var Stream = require('stream')
  var ws = new Stream()
  var self = this, first = true
  ws.writable = true
  ws.write = function (data) {
    if(!this.writable) return
    if('string' === typeof data)
      return self.id = data, true
    first = false
    self.applyUpdate(data)
    return true
  }
  ws.end = function () {
    this.writable = false
    self.sync = true
    self.emit('sync')
  }
  ws.destroy = function () {
    this.writable = false
    this.emit('close')
  }

  return serializer(opts.wrapper)(ws)
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

// TODO watchify lib/flow.client.js -vd -o 'gzip -9 > M.js'
// TODO clean up module by separating functionality into files

var fs = require('fs');
var path = require('path');
var zlib = require('zlib');
var mkdirp = require('mkdirp');
var browserify = require('browserify');
var factor = require('factor-bundle');
var uglifyify = require('uglifyify');
var getModules = require('./lib/getModules');
var argv = require('yargs')
    .demand(1)
    .option('d', {
        alias: 'debug',
        default: false,
        type: 'boolean',
        describe: 'Bundle scripts unminified and with a source map.'
    })
    .usage('flow-pack [options] [APP_REPO_PATH]')
    .example('flow-pack -d', "Bundle scripts unminified and with a source map.")
    .help('h')
    .alias('h', 'help')
    .strict()
    .argv;
var base = path.resolve(argv._[0]);
var base_app_modules = base + '/app_modules';
var base_node_modules = base + '/node_modules';
var bundles_target = base + '/.bundles';
var bo = {
    debug: argv.d,
    basedir: base,
    require: []
};

// ensure bundle target
mkdirp(bundles_target, function (err) {

    // bundle the individual modules
    getModules(base, function (err, packages) {

        if (err) {
            throw err;
        }

        var outputs = [];
        Object.keys(packages).forEach(function (module) {
            var pkg = packages[module];

            if (pkg.browser && typeof pkg.browser !== 'string') {
                // TODO add all files from the object
                return;
            }

            var file = pkg._flow_custom ? pkg.main : base_node_modules + '/' + module + '/' + (pkg.browser || pkg.main);

            bo.require.push({
                file:  file,
                expose: module
            });

            outputs.push(bundles_target + '/' + module + '.js');
        });

        console.log('Flow-pack.bundle:', outputs.length, 'Files.');

        var count = 0;
        var b = browserify(bo);

        // uglify code
        b.transform({global: true}, uglifyify);

        // handle individual packs
        b.on('factor.pipeline', function (file, pipeline) {

            // zip files
            pipeline.get('pack').push(zlib.createGzip());

            // TODO find a better way, to know when all bundles are written.
            pipeline.on('end', function () {
                if (++count === outputs.length) {
                    console.log('Flow-pack.bundle: All files bundled.');
                }
            });
        });

        b.plugin(factor, {outputs: outputs});
        b.on('error', console.log.bind(console));
        b.bundle();
    });
});
<commit_msg>add "target" cli option, to define the bundles target folder<commit_after>#!/usr/bin/env node

// TODO watchify lib/flow.client.js -vd -o 'gzip -9 > M.js'
// TODO clean up module by separating functionality into files

var fs = require('fs');
var path = require('path');
var zlib = require('zlib');
var mkdirp = require('mkdirp');
var browserify = require('browserify');
var factor = require('factor-bundle');
var uglifyify = require('uglifyify');
var getModules = require('./lib/getModules');
var argv = require('yargs')
    .demand(1)
    .option('d', {
        alias: 'debug',
        default: false,
        type: 'boolean',
        describe: 'Bundle scripts unminified and with a source map.'
    })
    .option('t', {
        alias: 'target',
        default: '.bundles',
        type: 'string',
        describe: 'Ensures the target folder for bundles.'
    })
    .usage('flow-pack [options] [APP_REPO_PATH]')
    .example('flow-pack -d', "Bundle scripts unminified and with a source map.")
    .example('flow-pack -t .bundles', "Ensures the target folder for bundles.")
    .help('h')
    .alias('h', 'help')
    .strict()
    .argv;

var base = path.resolve(argv._[0]);
var base_node_modules = base + '/node_modules';
var bundles_target = base + '/' + argv.t;
var bo = {
    debug: argv.d,
    basedir: base,
    require: []
};

// ensure bundle target
mkdirp(bundles_target, function (err) {

    // bundle the individual modules
    getModules(base, function (err, packages) {

        if (err) {
            throw err;
        }

        var outputs = [];
        Object.keys(packages).forEach(function (module) {
            var pkg = packages[module];

            if (pkg.browser && typeof pkg.browser !== 'string') {
                // TODO add all files from the object
                return;
            }

            var file = pkg._flow_custom ? pkg.main : base_node_modules + '/' + module + '/' + (pkg.browser || pkg.main);

            bo.require.push({
                file:  file,
                expose: module
            });

            outputs.push(bundles_target + '/' + module + '.js');
        });

        console.log('Flow-pack.bundle:', outputs.length, 'Files.');

        var count = 0;
        var b = browserify(bo);

        // uglify code
        b.transform({global: true}, uglifyify);

        // handle individual packs
        b.on('factor.pipeline', function (file, pipeline) {

            // zip files
            pipeline.get('pack').push(zlib.createGzip());

            // TODO find a better way, to know when all bundles are written.
            pipeline.on('end', function () {
                if (++count === outputs.length) {
                    console.log('Flow-pack.bundle: All files bundled.');
                }
            });
        });

        b.plugin(factor, {outputs: outputs});
        b.on('error', console.log.bind(console));
        b.bundle();
    });
});
<|endoftext|>


<commit_before>/**
* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
* and multiple types of buttons.
*
* @namespace onyx
*/
module.exports.version = "2.6.0-pre.4.dev";
<commit_msg>Update version string to 2.6.0-pre.14.1<commit_after>/**
* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
* and multiple types of buttons.
*
* @namespace onyx
*/
module.exports.version = "2.6.0-pre.14.1";
<|endoftext|>


<commit_before>/**
 *
 */

(function(){

	//Simple webserver

	var fs=require('fs');
	var http=require('http');
	var async=require('async');
	var port=80;
	var documentRoot='./html/';

	var server=http.createServer(function(req, res) {

		var file=req.url.split('/').pop();
		if(file===''){
			file='index.html';
		}
		if(file.indexOf('.')>=0){

			fs.exists(documentRoot+file, function(exists){

				if(exists){
					var contentTypes={
						js:'text/javascript',
						css:'text/css',
						html:'text/html'
					};

					var type=file.split('.').pop();
					res.writeHead(200, {
						'Content-Type': contentTypes[type]
					});

					fs.readFile(documentRoot+file, function (err, data) {
						res.write(data);
						res.end();
					});

				}else{

					res.writeHead(404);
					res.end('File not found: '+file);

				}

			});
		}else{

			res.writeHead(500);
			res.end('resuest: '+file);

		}

	});

	server.listen(port);
	console.log('webserver listening on: '+port);

})();

var devices=require('./devices.json');

var gpio = require('rpi-gpio');
devices.forEach(function(dconf){

	var direction=dconf.direction==='in'?gpio.DIR_IN:gpio.DIR_OUT;

	gpio.setup(dconf.pin, direction, function(err){

		 gpio.read(dconf.pin, function(err, value) {
		        console.log('The value is ' + value);
		        dconf.state=value?true:false;
		 });

	});

});

var setDeviceState=function(pin, value, callback){

    gpio.write(pin, value, function(err) {
        if (err) throw err;
        callback(value);
    });

}
var clientCanSetPin=function(client, pin){
	return isOutputPin(pin);
};

var isOutputPin=function(pin){
	return true;
};

(function(){

	// Simple websocket server

	var port = 8080;
	var clients = [];

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		clients.push(wsclient);

		wsclient.on('message',function(data){

			var request=JSON.parse(data);
			console.log([data, request]);
			var id=request.id;
			var task=request.task;
			var arguments=request.json;

			if(task=='list_devices'){
				wsclient.send(id+':'+JSON.stringify(devices));
			}

			if(task=='set_device_value'){
				var pin=arguments.pin;
				var value=!!arguments.value;
				if(clientCanSetPin(wsclient, pin)){
					setDeviceState(pin, value, function(value){
						wsclient.send(id+':set '+pin+' to '+(value?'true':'false'));
					});
				}

			}

		}).on('close',function(code, message){
			var i = clients.indexOf(wsclient);
			console.log('ws:'+i+' client closed: '+code+' '+message);
			clients.splice(i, 1);
		});

	}).on('error', function(error){

		console.log('error: '+error);

	});

	console.log('websocket listening on: '+port);

})();

<commit_msg>added some console messages<commit_after>/**
 *
 */

(function(){

	//Simple webserver

	var fs=require('fs');
	var http=require('http');
	var async=require('async');
	var port=80;
	var documentRoot='./html/';

	var server=http.createServer(function(req, res) {

		var file=req.url.split('/').pop();
		if(file===''){
			file='index.html';
		}
		if(file.indexOf('.')>=0){

			fs.exists(documentRoot+file, function(exists){

				if(exists){
					var contentTypes={
						js:'text/javascript',
						css:'text/css',
						html:'text/html'
					};

					var type=file.split('.').pop();
					res.writeHead(200, {
						'Content-Type': contentTypes[type]
					});

					fs.readFile(documentRoot+file, function (err, data) {
						res.write(data);
						res.end();
					});

				}else{

					res.writeHead(404);
					res.end('File not found: '+file);

				}

			});
		}else{

			res.writeHead(500);
			res.end('resuest: '+file);

		}

	});

	server.listen(port);
	console.log('webserver listening on: '+port);

})();

var devices=require('./devices.json');

var gpio = require('rpi-gpio');
devices.forEach(function(dconf){

	var direction=dconf.direction==='in'?gpio.DIR_IN:gpio.DIR_OUT;

	gpio.setup(dconf.pin, direction, function(err){

		 gpio.read(dconf.pin, function(err, value) {
		        console.log('The value is ' + value);
		        dconf.state=value?true:false;
		 });

	});

});

var setDeviceState=function(pin, value, callback){

    gpio.write(pin, value, function(err) {
        if (err) throw err;
        callback(value);
    });

}
var clientCanSetPin=function(client, pin){
	return isOutputPin(pin);
};

var isOutputPin=function(pin){
	return true;
};

(function(){

	// Simple websocket server

	var port = 8080;
	var clients = [];

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		clients.push(wsclient);
		console.log('client connected: '+wsclient);

		wsclient.on('message',function(data){

			var request=JSON.parse(data);
			//console.log([data, request]);
			var id=request.id;
			var task=request.task;
			var arguments=request.json;

			if(task=='list_devices'){
				wsclient.send(id+':'+JSON.stringify(devices));
				console.log('sent device list: '+devices.length+' devices');
			}

			if(task=='set_device_value'){
				var pin=arguments.pin;
				var value=!!arguments.value;
				if(clientCanSetPin(wsclient, pin)){
					setDeviceState(pin, value, function(value){
						wsclient.send(id+':set '+pin+' to '+(value?'true':'false'));
						console.log('set device: '+pin+' to '+(value?'true':'false'));
					});
				}

			}

		}).on('close',function(code, message){
			var i = clients.indexOf(wsclient);
			console.log('ws:'+i+' client closed: '+code+' '+message);
			clients.splice(i, 1);
		});

	}).on('error', function(error){

		console.log('error: '+error);

	});

	console.log('websocket listening on: '+port);

})();

<|endoftext|>


<commit_before>import {
    GraphQLBoolean,
    GraphQLID,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString,
    GraphQLInt,
    GraphQLInputObjectType,
} from 'graphql';

import GraphQLDate from 'graphql-custom-datetype';

import {
    connectionArgs,
    connectionDefinitions,
    fromGlobalId,
    globalIdField,
    mutationWithClientMutationId,
    nodeDefinitions,
} from 'graphql-relay';

import connectionFromMongooseQuery from 'relay-mongoose-connection';
import moment from 'moment';
import config from 'config';
import nodemailer from 'nodemailer';

import { User, Organization } from '../models';
import { File } from '../models/files';
import { Project, Event } from '../models/projects';

let transporter;
if (config.mail && config.mail.auth && config.mail.host) {
    transporter = nodemailer.createTransport({
        secure: true,
        host: config.mail.host,
        auth: config.mail.auth,
    });
}
else {
    transporter = nodemailer.createTransport();
}

class UserDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class OrganizationDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class EventDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class ProjectDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class FileDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }

const { nodeInterface, nodeField } = nodeDefinitions(
    (globalId) => {
        const { type, id } = fromGlobalId(globalId);
        if (type === 'User') {
            return User.findById(id).exec().then((user) => new UserDTO(user.toObject()));
        }
        if (type === 'Organization') {
            return Organization.findById(id).exec().then((organization) => new OrganizationDTO(organization.toObject()));
        }
        if (type === 'Event') {
            return Event.findById(id).exec().then((event) => new EventDTO(event.toObject()));
        }
        if (type === 'Project') {
            return Project.findById(id).exec().then((project) => new ProjectDTO(project.toObject()));
        }
        if (type === 'File') {
            return File.findById(id).exec().then((file) => new FileDTO(file.toObject()));
        }
        return null;
    },
    (obj) => {
        if (obj instanceof UserDTO) {
            return userType;
        }
        if (obj instanceof OrganizationDTO) {
            return organizationType;
        }
        if (obj instanceof EventDTO) {
            return eventType;
        }
        if (obj instanceof ProjectDTO) {
            return projectType;
        }
        if (obj instanceof FileDTO) {
            return fileType;
        }
        return null;
    }
);

const userType = new GraphQLObjectType({
    name: 'User',
    description: 'A person',
    fields: {
        id: globalIdField('User'),
        name: { type: GraphQLString },
        username: { type: GraphQLString },
        email: { type: GraphQLString },
        created: { type: GraphQLString },
        updated: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const fileType = new GraphQLObjectType({
    name: 'File',
    fields: {
        id: globalIdField('File'),
        filename: { type: GraphQLString },
        thumbnail_path: { type: GraphQLString },
        normal_path: { type: GraphQLString },
        large_path: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const eventType = new GraphQLObjectType({
    name: 'Event',
    fields: {
        id: globalIdField('Event'),
        title: { type: GraphQLString },
        start: { type: GraphQLDate },
        end: { type: GraphQLDate },
        mdtext: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const projectType = new GraphQLObjectType({
    name: 'Project',
    fields: {
        id: globalIdField('Project'),
        title: { type: GraphQLString },
        tag: { type: GraphQLString },
        start: { type: GraphQLDate },
        end: { type: GraphQLDate },
        year: { type: GraphQLString },
        public_mdtext: { type: GraphQLString },
        conductors: { type: new GraphQLList(userType) },
        poster: {
            type: fileType,
            resolve: (a) => File.findById(a.poster).exec(),
        },
    },
    interfaces: [nodeInterface],
});

const organizationType = new GraphQLObjectType({
    name: 'Organization',
    description: 'Organization and site info',
    fields: {
        id: globalIdField('Organization'),
        name: { type: GraphQLString },
        webdomain: { type: GraphQLString },
        mail_address: { type: GraphQLString },
        postcode: { type: GraphQLString },
        city: { type: GraphQLString },
        email: { type: GraphQLString },
        public_bank_account: { type: GraphQLString },
        organization_number: { type: GraphQLString },
        encoded_email: { type: GraphQLString },
        website: { type: GraphQLString },
        twitter: { type: GraphQLString },
        facebook: { type: GraphQLString },
        description_nb: { type: GraphQLString }, // TODO: Migrate
        map_url: { type: GraphQLString },
        contact_text: { type: GraphQLString },
        project: {
            type: projectType,
            args: {
                year: { name: 'year', type: GraphQLString },
                tag: { name: 'tag', type: GraphQLString },
            },
            resolve: (_, args) => Project.findOne({ tag: args.tag, year: args.year }).exec(),
        },
        nextProject: {
            type: projectType,
            async resolve() {
                return await Project
                .findOne({ end: { $gte: moment().startOf('day').toDate() } })
                .sort({ end: 1 })
                .exec();
            },
        },
        nextProjects: {
            type: connectionDefinitions({ name: 'UpcomingProject', nodeType: projectType }).connectionType,
            args: connectionArgs,
            async resolve(term, { ...args }) { // term here is unused for now, coming from server
                return await connectionFromMongooseQuery(
                    Project.find({
                        end: { $gte: moment().startOf('day').toDate() },
                    }).sort({ end: 1 }),
                    args,
                );
            },
        },
        previousProjects: {
            type: connectionDefinitions({ name: 'Project', nodeType: projectType }).connectionType,
            args: connectionArgs,
            async resolve(term, { ...args }) { // term here is unused for now, coming from server
                return await connectionFromMongooseQuery(
                    Project.find({
                        end: { $lt: moment().startOf('day').toDate() },
                    }).sort({ end: -1 }),
                    args,
                );
            },
        },
        event: {
            type: eventType,
            args: {
                id: { name: 'id', type: GraphQLString },
            },
            resolve: (_, args) => Event.findById(args.id).exec(),
        },
        nextEvents: {
            type: connectionDefinitions({ name: 'Event', nodeType: eventType }).connectionType,
            args: connectionArgs,
            async resolve(root, { ...args }) {
                const query = Event
                .find({
                    start: {
                        $gte: moment().startOf('day').toDate(),
                        $lt: moment().add(2, 'months').startOf('day').toDate(),
                    },
                })
                .sort({ start: 1 });
                if (root.viewer) {
                    query.or([
                        { creator: root.viewer },
                        { 'permissions.public': true },
                        { 'permissions.users': root.viewer._id },
                        { 'permissions.groups': { $in: root.viewer.groups } },
                    ]);
                }
                else {
                    query.where({ 'permissions.public': true });
                    query.select({ mdtext: 0 });
                }
                return await connectionFromMongooseQuery(
                    query,
                    args,
                );
            },
        },
    },
    interfaces: [nodeInterface],
});

const queryType = new GraphQLObjectType({
    name: 'Query',
    fields: {
        node: nodeField,
        viewer: {
            type: userType,
            resolve: ({ viewer }) => viewer,
        },
        organization: {
            /*
            args: {
                username: {
                    name: 'username',
                    type: new GraphQLNonNull(GraphQLString),
                },
            },
            */
            type: organizationType,
            resolve: ({ organization, viewer }) => ({ organization, viewer }),
        },
    },
});

const mutationUserUpdate = mutationWithClientMutationId({
    name: 'UpdateUser',
    inputFields: {
        userid: { type: new GraphQLNonNull(GraphQLID) },
        email: { type: new GraphQLNonNull(GraphQLString) },
        message: { type: GraphQLString },
    },
    outputFields: {
        viewer: {
            type: userType,
            resolve: (payload) => payload,
        },
    },
    mutateAndGetPayload: ({ userid, email, message, participants }) => {
        const id = fromGlobalId(userid).id;
        return User.findByIdAndUpdate(
            id,
            { email, message, participants, updated: moment.utc().toDate() },
            { new: true },
        ).exec().then(user => {
            if (message && config.mail && user) {
                transporter.sendMail({
                    to: config.mail.to || 'sigurdga-nidarholm-test@sigurdga.no',
                    from: config.mail.from || 'drangen@nidarholm.no',
                    subject: `Ny kommentar fra ${user.name}`,
                    text: message,
                }, (error, info) => {
                    if (error) {
                        return console.error(error);
                    }
                    console.log(`Message sent: ${info.response}`);
                    return false;
                });
            }
            return JSON.parse(JSON.stringify(user));
        });
    },
});

const mutationType = new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
        updateUser: mutationUserUpdate,
    }),
});

const schema = new GraphQLSchema({
    query: queryType,
    mutation: mutationType,
});

export default schema;
<commit_msg>No more async await, use normal promises.<commit_after>import {
    GraphQLBoolean,
    GraphQLID,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString,
    GraphQLInt,
    GraphQLInputObjectType,
} from 'graphql';

import GraphQLDate from 'graphql-custom-datetype';

import {
    connectionArgs,
    connectionDefinitions,
    fromGlobalId,
    globalIdField,
    mutationWithClientMutationId,
    nodeDefinitions,
} from 'graphql-relay';

import connectionFromMongooseQuery from 'relay-mongoose-connection';
import moment from 'moment';
import config from 'config';
import nodemailer from 'nodemailer';

import { User, Organization } from '../models';
import { File } from '../models/files';
import { Project, Event } from '../models/projects';

let transporter;
if (config.mail && config.mail.auth && config.mail.host) {
    transporter = nodemailer.createTransport({
        secure: true,
        host: config.mail.host,
        auth: config.mail.auth,
    });
}
else {
    transporter = nodemailer.createTransport();
}

class UserDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class OrganizationDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class EventDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class ProjectDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }
class FileDTO { constructor(obj) { for (const k of Object.keys(obj)) { this[k] = obj[k]; } } }

const { nodeInterface, nodeField } = nodeDefinitions(
    (globalId) => {
        const { type, id } = fromGlobalId(globalId);
        if (type === 'User') {
            return User.findById(id).exec().then((user) => new UserDTO(user.toObject()));
        }
        if (type === 'Organization') {
            return Organization.findById(id).exec().then((organization) => new OrganizationDTO(organization.toObject()));
        }
        if (type === 'Event') {
            return Event.findById(id).exec().then((event) => new EventDTO(event.toObject()));
        }
        if (type === 'Project') {
            return Project.findById(id).exec().then((project) => new ProjectDTO(project.toObject()));
        }
        if (type === 'File') {
            return File.findById(id).exec().then((file) => new FileDTO(file.toObject()));
        }
        return null;
    },
    (obj) => {
        if (obj instanceof UserDTO) {
            return userType;
        }
        if (obj instanceof OrganizationDTO) {
            return organizationType;
        }
        if (obj instanceof EventDTO) {
            return eventType;
        }
        if (obj instanceof ProjectDTO) {
            return projectType;
        }
        if (obj instanceof FileDTO) {
            return fileType;
        }
        return null;
    }
);

const userType = new GraphQLObjectType({
    name: 'User',
    description: 'A person',
    fields: {
        id: globalIdField('User'),
        name: { type: GraphQLString },
        username: { type: GraphQLString },
        email: { type: GraphQLString },
        created: { type: GraphQLString },
        updated: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const fileType = new GraphQLObjectType({
    name: 'File',
    fields: {
        id: globalIdField('File'),
        filename: { type: GraphQLString },
        thumbnail_path: { type: GraphQLString },
        normal_path: { type: GraphQLString },
        large_path: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const eventType = new GraphQLObjectType({
    name: 'Event',
    fields: {
        id: globalIdField('Event'),
        title: { type: GraphQLString },
        start: { type: GraphQLDate },
        end: { type: GraphQLDate },
        mdtext: { type: GraphQLString },
    },
    interfaces: [nodeInterface],
});

const projectType = new GraphQLObjectType({
    name: 'Project',
    fields: {
        id: globalIdField('Project'),
        title: { type: GraphQLString },
        tag: { type: GraphQLString },
        start: { type: GraphQLDate },
        end: { type: GraphQLDate },
        year: { type: GraphQLString },
        public_mdtext: { type: GraphQLString },
        conductors: { type: new GraphQLList(userType) },
        poster: {
            type: fileType,
            resolve: (a) => File.findById(a.poster).exec(),
        },
    },
    interfaces: [nodeInterface],
});

const organizationType = new GraphQLObjectType({
    name: 'Organization',
    description: 'Organization and site info',
    fields: {
        id: globalIdField('Organization'),
        name: { type: GraphQLString },
        webdomain: { type: GraphQLString },
        mail_address: { type: GraphQLString },
        postcode: { type: GraphQLString },
        city: { type: GraphQLString },
        email: { type: GraphQLString },
        public_bank_account: { type: GraphQLString },
        organization_number: { type: GraphQLString },
        encoded_email: { type: GraphQLString },
        website: { type: GraphQLString },
        twitter: { type: GraphQLString },
        facebook: { type: GraphQLString },
        description_nb: { type: GraphQLString }, // TODO: Migrate
        map_url: { type: GraphQLString },
        contact_text: { type: GraphQLString },
        project: {
            type: projectType,
            args: {
                year: { name: 'year', type: GraphQLString },
                tag: { name: 'tag', type: GraphQLString },
            },
            resolve: (_, args) => Project.findOne({ tag: args.tag, year: args.year }).exec(),
        },
        nextProject: {
            type: projectType,
            resolve: () => Project
                .findOne({ end: { $gte: moment().startOf('day').toDate() } })
                .sort({ end: 1 })
                .exec(),
        },
        nextProjects: {
            type: connectionDefinitions({ name: 'UpcomingProject', nodeType: projectType }).connectionType,
            args: connectionArgs,
            resolve: (term, { ...args }) => // term here is unused for now, coming from server
                connectionFromMongooseQuery(
                    Project.find({
                        end: { $gte: moment().startOf('day').toDate() },
                    }).sort({ end: 1 }),
                    args,
                ),
        },
        previousProjects: {
            type: connectionDefinitions({ name: 'Project', nodeType: projectType }).connectionType,
            args: connectionArgs,
            resolve: (term, { ...args }) => //{ // term here is unused for now, coming from server
                connectionFromMongooseQuery(
                    Project.find({
                        end: { $lt: moment().startOf('day').toDate() },
                    }).sort({ end: -1 }),
                    args,
                ),
        },
        event: {
            type: eventType,
            args: {
                id: { name: 'id', type: GraphQLString },
            },
            resolve: (_, args) => Event.findById(args.id).exec(),
        },
        nextEvents: {
            type: connectionDefinitions({ name: 'Event', nodeType: eventType }).connectionType,
            args: connectionArgs,
            resolve: (root, { ...args }) => {
                const query = Event
                .find({
                    start: {
                        $gte: moment().startOf('day').toDate(),
                        $lt: moment().add(2, 'months').startOf('day').toDate(),
                    },
                })
                .sort({ start: 1 });
                if (root.viewer) {
                    query.or([
                        { creator: root.viewer },
                        { 'permissions.public': true },
                        { 'permissions.users': root.viewer._id },
                        { 'permissions.groups': { $in: root.viewer.groups } },
                    ]);
                }
                else {
                    query.where({ 'permissions.public': true });
                    query.select({ mdtext: 0 });
                }
                return connectionFromMongooseQuery(
                    query,
                    args,
                );
            },
        },
    },
    interfaces: [nodeInterface],
});

const queryType = new GraphQLObjectType({
    name: 'Query',
    fields: {
        node: nodeField,
        viewer: {
            type: userType,
            resolve: ({ viewer }) => viewer,
        },
        organization: {
            /*
            args: {
                username: {
                    name: 'username',
                    type: new GraphQLNonNull(GraphQLString),
                },
            },
            */
            type: organizationType,
            resolve: ({ organization, viewer }) => ({ organization, viewer }),
        },
    },
});

const mutationUserUpdate = mutationWithClientMutationId({
    name: 'UpdateUser',
    inputFields: {
        userid: { type: new GraphQLNonNull(GraphQLID) },
        email: { type: new GraphQLNonNull(GraphQLString) },
        message: { type: GraphQLString },
    },
    outputFields: {
        viewer: {
            type: userType,
            resolve: (payload) => payload,
        },
    },
    mutateAndGetPayload: ({ userid, email, message, participants }) => {
        const id = fromGlobalId(userid).id;
        return User.findByIdAndUpdate(
            id,
            { email, message, participants, updated: moment.utc().toDate() },
            { new: true },
        ).exec().then(user => {
            if (message && config.mail && user) {
                transporter.sendMail({
                    to: config.mail.to || 'sigurdga-nidarholm-test@sigurdga.no',
                    from: config.mail.from || 'drangen@nidarholm.no',
                    subject: `Ny kommentar fra ${user.name}`,
                    text: message,
                }, (error, info) => {
                    if (error) {
                        return console.error(error);
                    }
                    console.log(`Message sent: ${info.response}`);
                    return false;
                });
            }
            return JSON.parse(JSON.stringify(user));
        });
    },
});

const mutationType = new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
        updateUser: mutationUserUpdate,
    }),
});

const schema = new GraphQLSchema({
    query: queryType,
    mutation: mutationType,
});

export default schema;
<|endoftext|>


<commit_before>"use strict";

// City-core
var cityAPIOrigin = "http://localhost:9000";
// var cityAPIOrigin = "https://city-api.ants.builders";
var bordeaux3dCore = require('city-core');
var MAX_Y = require('city-core/front/MAX_Y.js');
var meshToBuilding = require('city-core/front/meshToBuilding.js');

// City-blocks
var SkyViewControls = require('city-blocks/controls/SkyView_RTS.js');
var FirstPersonControls = require('city-blocks/controls/FirstPerson_PointerLock.js');
// var SkyViewControls = require('city-blocks/controls/SkyView_Basic.js');
// var FirstPersonControls = require('city-blocks/controls/FirstPerson_Basic.js');
var SunPosition = require('city-blocks/utils/SunPosition.js');
var GeoConverter = require('city-blocks/utils/geo/geoConverter.js');
var GeoCode = require('city-blocks/utils/geo/geoCode.js');
var raycasting = require('city-blocks/utils/ray/raycasting.js');
var GUI = require('city-blocks/gui/GUI_basic.js');

var THREE = require('three');

var guiControls = GUI.guiControls;

var view = document.querySelector('#view');

var bordeaux3DP = bordeaux3dCore(view, cityAPIOrigin);

// initialise the geoconverter that will pass from a shifted lambert cc 45 to lon, lat and reverse
// the map is shifted
// -0.583232, 44.839270 corresponds to 1416800.1046884255, 4188402.562212417 in lambert 45
// and to (X=119) * 200 + (x=100), (MAX_Y-(Y=115))*200 + (y=100) in the map
var deltaX = 1416800.1046884255 - 119*200 - 100;
var deltaY = 4188402.562212417 - (MAX_Y-115)*200 - 100;
var geoConverter = new GeoConverter(45, deltaX, deltaY);

var currentControls = "Sky";

var INITIAL_ALTITUDE = 200;
var SUN_ALTITUDE = 300;

var sunLight = new THREE.DirectionalLight(0xffffff, 1);

sunLight.castShadow = true;
sunLight.shadowDarkness = 0.6;
sunLight.shadowMapWidth = 4096;
sunLight.shadowMapHeight = 4096;
sunLight.shadowCameraNear = 1;
sunLight.shadowCameraFar = 4000;

sunLight.shadowCameraRight = 200;
sunLight.shadowCameraLeft = -200;
sunLight.shadowCameraTop = 200;
sunLight.shadowCameraBottom = -200;

var ambientLight = new THREE.AmbientLight( "#333329" );

var lights = {
    sun: sunLight,
    ambient: ambientLight
};

var splashScreen = document.body.querySelector("#splash-screen");

splashScreen.addEventListener('click', function(){
    splashScreen.style.opacity = 0;
    console.log("click");
});
splashScreen.addEventListener('transitionend', function(){
    splashScreen.remove();
})

bordeaux3DP.then(function(bordeaux3D){

    // initial position
    bordeaux3D.camera.position.x = 24341.22;
    bordeaux3D.camera.position.y = 10967.65;
    bordeaux3D.camera.position.z = INITIAL_ALTITUDE;

    bordeaux3D.addLight(lights.sun);
    bordeaux3D.addLight(lights.ambient);

    // Sun position changes only so that light.shadowCamera follows view
    bordeaux3D.camera.on('cameraviewchange', function(){
        var pos = bordeaux3D.camera.position;
        var sun = lights.sun;
        sun.position.x = pos.x;
        sun.position.y = pos.y;
        sun.position.z = SUN_ALTITUDE;
        console.log('cameraViewChange');
        var sunPos = SunPosition(guiControls.hour, sun, lights.ambient);
        sun.target.position.set(pos.x + sunPos[0], pos.y + sunPos[1], 0);
    });

    // activate raycasting
    raycasting(bordeaux3D.camera, bordeaux3D.scene, view);

    var currentAltitude = INITIAL_ALTITUDE;

    function moveTo(place){
        GeoCode(place).then(function(coords) {
            var newPosition = geoConverter.toLambert(coords.lon, coords.lat);

            bordeaux3D.camera.position = new THREE.Vector3(newPosition.X, newPosition.Y, currentAltitude);
            bordeaux3D.camera.lookAt( new THREE.Vector3(newPosition.X, newPosition.Y, 0) );
            bordeaux3D.camera.up = new THREE.Vector3(0, 1, 0);

            currentControls = 'Sky';
            toggleControls(currentControls);

        });
    }

    // moveTo(guiControls.address);

    GUI.addressControler.onFinishChange(function(value) {
        moveTo(value);
    });

    GUI.hourControler.onChange(function(){
        SunPosition(guiControls.hour, lights.sun, lights.ambient);
        bordeaux3D.render();
    });

    function toggleControls(mode){
        console.log('toggleControls', mode);

        if(mode === "Sky"){
            bordeaux3D.changeControls(SkyViewControls, { z: currentAltitude });
            window.removeEventListener('keydown', onKeyPressFirstPerson);
            view.addEventListener('meshClicked', onMeshClicked);
        }
        else{
            console.log('Switching to FPV: ', bordeaux3D.camera.position);
            currentAltitude = bordeaux3D.camera.position.z;
            bordeaux3D.changeControls(FirstPersonControls);
            view.removeEventListener('meshClicked', onMeshClicked);
            window.addEventListener('keydown', onKeyPressFirstPerson);
        }
    }

    function onMeshClicked(event){
        var detail = event.detail;
        console.log('Id', meshToBuilding.get(detail.mesh).id);
        console.log('Intersection point', detail.point.x, detail.point.y, detail.point.z);

        bordeaux3D.camera.position.x = detail.point.x;
        bordeaux3D.camera.position.y = detail.point.y;

        console.log('camera position: ', bordeaux3D.camera.x, bordeaux3D.camera.y, bordeaux3D.camera.z);

        currentControls = "FirstPerson";
        toggleControls(currentControls);
    }

    function onKeyPressFirstPerson(e){
        console.log('key press while first person', e.keyCode);
        if(e.keyCode === 27){ // escape
            e.preventDefault();
            currentControls = "Sky";
            toggleControls(currentControls);
        }
    }

    // toggle initial controls
    toggleControls(currentControls);

});

<commit_msg>cleaning<commit_after>"use strict";

// City-core
var cityAPIOrigin = "https://city-api.ants.builders";
var bordeaux3dCore = require('city-core');
var MAX_Y = require('city-core/front/MAX_Y.js');
var meshToBuilding = require('city-core/front/meshToBuilding.js');

// City-blocks
var SkyViewControls = require('city-blocks/controls/SkyView_RTS.js');
var FirstPersonControls = require('city-blocks/controls/FirstPerson_PointerLock.js');
var SunPosition = require('city-blocks/utils/SunPosition.js');
var GeoConverter = require('city-blocks/utils/geo/geoConverter.js');
var GeoCode = require('city-blocks/utils/geo/geoCode.js');
var raycasting = require('city-blocks/utils/ray/raycasting.js');
var GUI = require('city-blocks/gui/GUI_basic.js');

var THREE = require('three');

var guiControls = GUI.guiControls;

var view = document.querySelector('#view');

var bordeaux3DP = bordeaux3dCore(view, cityAPIOrigin);

// initialise the geoconverter that will pass from a shifted lambert cc 45 to lon, lat and reverse
// the map is shifted
// -0.583232, 44.839270 corresponds to 1416800.1046884255, 4188402.562212417 in lambert 45
// and to (X=119) * 200 + (x=100), (MAX_Y-(Y=115))*200 + (y=100) in the map
var deltaX = 1416800.1046884255 - 119*200 - 100;
var deltaY = 4188402.562212417 - (MAX_Y-115)*200 - 100;
var geoConverter = new GeoConverter(45, deltaX, deltaY);

var currentControls = "Sky";

var INITIAL_ALTITUDE = 200;
var SUN_ALTITUDE = 300;

var sunLight = new THREE.DirectionalLight(0xffffff, 1);

sunLight.castShadow = true;
sunLight.shadowDarkness = 0.6;
sunLight.shadowMapWidth = 4096;
sunLight.shadowMapHeight = 4096;
sunLight.shadowCameraNear = 1;
sunLight.shadowCameraFar = 4000;

sunLight.shadowCameraRight = 200;
sunLight.shadowCameraLeft = -200;
sunLight.shadowCameraTop = 200;
sunLight.shadowCameraBottom = -200;

var ambientLight = new THREE.AmbientLight( "#333329" );

var lights = {
    sun: sunLight,
    ambient: ambientLight
};

var splashScreen = document.body.querySelector("#splash-screen");

splashScreen.addEventListener('click', function(){
    splashScreen.style.opacity = 0;
});
splashScreen.addEventListener('transitionend', function(){
    splashScreen.remove();
})

bordeaux3DP.then(function(bordeaux3D){

    // initial position
    bordeaux3D.camera.position.x = 24341.22;
    bordeaux3D.camera.position.y = 10967.65;
    bordeaux3D.camera.position.z = INITIAL_ALTITUDE;

    bordeaux3D.addLight(lights.sun);
    bordeaux3D.addLight(lights.ambient);

    // Sun position changes only so that light.shadowCamera follows view
    bordeaux3D.camera.on('cameraviewchange', function(){
        var pos = bordeaux3D.camera.position;
        var sun = lights.sun;
        sun.position.x = pos.x;
        sun.position.y = pos.y;
        sun.position.z = SUN_ALTITUDE;
        var sunPos = SunPosition(guiControls.hour, sun, lights.ambient);
        sun.target.position.set(pos.x + sunPos[0], pos.y + sunPos[1], 0);
    });

    // activate raycasting
    raycasting(bordeaux3D.camera, bordeaux3D.scene, view);

    var currentAltitude = INITIAL_ALTITUDE;

    function moveTo(place){
        GeoCode(place).then(function(coords) {
            var newPosition = geoConverter.toLambert(coords.lon, coords.lat);

            bordeaux3D.camera.position = new THREE.Vector3(newPosition.X, newPosition.Y, currentAltitude);
            bordeaux3D.camera.lookAt( new THREE.Vector3(newPosition.X, newPosition.Y, 0) );
            bordeaux3D.camera.up = new THREE.Vector3(0, 1, 0);

            currentControls = 'Sky';
            toggleControls(currentControls);

        });
    }

    // moveTo(guiControls.address);

    GUI.addressControler.onFinishChange(function(value) {
        moveTo(value);
    });

    GUI.hourControler.onChange(function(){
        SunPosition(guiControls.hour, lights.sun, lights.ambient);
        bordeaux3D.render();
    });

    function toggleControls(mode){

        if(mode === "Sky"){
            bordeaux3D.changeControls(SkyViewControls, { z: currentAltitude });
            window.removeEventListener('keydown', onKeyPressFirstPerson);
            view.addEventListener('meshClicked', onMeshClicked);
        }
        else{
            console.log('Switching to FPV: ', bordeaux3D.camera.position);
            currentAltitude = bordeaux3D.camera.position.z;
            bordeaux3D.changeControls(FirstPersonControls);
            view.removeEventListener('meshClicked', onMeshClicked);
            window.addEventListener('keydown', onKeyPressFirstPerson);
        }
    }

    function onMeshClicked(event){
        var detail = event.detail;
        // console.log('Id', meshToBuilding.get(detail.mesh).id);
        // console.log('Intersection point', detail.point.x, detail.point.y, detail.point.z);

        bordeaux3D.camera.position.x = detail.point.x;
        bordeaux3D.camera.position.y = detail.point.y;

        currentControls = "FirstPerson";
        toggleControls(currentControls);
    }

    function onKeyPressFirstPerson(e){
        console.log('key press while first person', e.keyCode);
        if(e.keyCode === 27){ // escape
            e.preventDefault();
            currentControls = "Sky";
            toggleControls(currentControls);
        }
    }

    // toggle initial controls
    toggleControls(currentControls);

});

<|endoftext|>


<commit_before>import _ from "underscore"

import Model from "./model"
import getLogger from "./logger"

const logger = getLogger()
const model = new Model()

export default class {
  constructor(ws) {
    this._socket = ws
  }

  join({name}) {
    const data = model.join(this._socket.id, name)

    if (!data) {
      logger.info(`user with name ${name} joined; held`)
      this._socket.send("hold")

    } else {
      const gid = data.gid
      const color = data[this._socket.id]
      const opp_id = data.opp
      const opp_color = color == "w" ? "b" : "w"

      logger.info(`user with name ${name}, this._socket_id ${this._socket.id} joined; assigned: ${color}; opponent: ${opp_id} ${opp_color}`)

      this._socket.send("game", {gid, color, states: data.states})
      this._sockets[opp_id].send("game", {gid, color: opp_color, states: data.states})
    }
  }

  move() {
    const from = this._message.f
    const to = this._message.t
    const self = this

    model.update(this._socket.id, from, to, data => {
      if (!data) return; // client disconnected during an update

      const gid = data.gid
      const opp_id = data.opp_id
      const watchers = data.watchers

      self._sockets[opp_id].send("state", data.state)

      for (let i = 0, l = watchers.length; i < l; i++) {
        const watcher = self._sockets[watchers[i]]
        if (watcher) watcher.send("state", data.state)
      }

      logger.info(`recieved move from client with socket id: ${self._socket.id}; from ${from} to ${to}; opp ${opp_id}`)
    })
  }

  kibitz() {
    const states = model.kibitz(this._socket.id, this._message.name)
    this._socket.send("kibitz", { states })
  }

  rotate() {
    const data = model.mv_watcher(this._socket.id, this._message.t)
    this._socket.send("rotate", _.extend(data, { to: this._message.t }))
  }

  disconnect({sessionId}) {
    model.quit(sessionId)
  }
}

export const __useDefault = true
<commit_msg>destructure commands<commit_after>import _ from "underscore"

import Model from "./model"
import getLogger from "./logger"

const logger = getLogger()
const model = new Model()

export default class {
  constructor(ws) {
    this._socket = ws
  }

  join({name}) {
    const data = model.join(this._socket.id, name)

    if (!data) {
      logger.info(`user with name ${name} joined; held`)
      this._socket.send("hold")

    } else {
      const gid = data.gid
      const color = data[this._socket.id]
      const opp_id = data.opp
      const opp_color = color == "w" ? "b" : "w"

      logger.info(`user with name ${name}, this._socket_id ${this._socket.id} joined; assigned: ${color}; opponent: ${opp_id} ${opp_color}`)

      this._socket.send("game", {gid, color, states: data.states})
      this._sockets[opp_id].send("game", {gid, color: opp_color, states: data.states})
    }
  }

  move({from, to}) {
    const self = this

    model.update(this._socket.id, from, to, data => {
      if (!data) return; // client disconnected during an update

      const gid = data.gid
      const opp_id = data.opp_id
      const watchers = data.watchers

      self._sockets[opp_id].send("state", data.state)

      for (let i = 0, l = watchers.length; i < l; i++) {
        const watcher = self._sockets[watchers[i]]
        if (watcher) watcher.send("state", data.state)
      }

      logger.info(`recieved move from client with socket id: ${self._socket.id}; from ${from} to ${to}; opp ${opp_id}`)
    })
  }

  kibitz({name}) {
    const states = model.kibitz(this._socket.id, name)
    this._socket.send("kibitz", { states })
  }

  rotate({to}) {
    const data = model.mv_watcher(this._socket.id, to)
    this._socket.send("rotate", _.extend(data, { to }))
  }

  disconnect({sessionId}) {
    model.quit(sessionId)
  }
}

export const __useDefault = true
<|endoftext|>


<commit_before>'use strict';
module.exports = function (input, opts) {
  var Consts = require('./consts.js');

  var expenseObject = {
    reason: input[2],
    category: opts.c,
    date: opts.d,
    credit: '',
    debit: ''
  };

  // validation step
  // make sure that everything is as it should be before proceeding

  if (expenseObject.date) {
    var dateRe = /(\d{4})-(\d{2})-(\d{2})/;
    var matchObject = expenseObject.date.match(dateRe);
    if (!matchObject) {
      throw new Error(Consts.MSG_INVALID_DATE);
    }
  } else {
    expenseObject.date = require('date-format').asString('yyyy-MM-dd', new Date());
  }

  // end validation step

  if (input[0] === 'file_path') {
    // open the wallet file in `less`
    console.log(Consts.WALLET_FILE_PATH);
    process.exit(0);
  }

  if (input[0] === 'credit' || input[0] === 'debit') {
    if (input.length < 3 || typeof input[1] !== 'number') {
      throw new Error(Consts.MSG_ERR_CREDIT_DEBIT_TRANS);
    }
  }

  if (input[0] === 'stash' && input[0] === 'unstash') {
    if (input.length < 2 || typeof input[1] !== 'number') {
      throw new Error(Consts.MSG_ERR_STASH_TRANS);
    }
  }

  switch (input[0]) {
    case 'debit':
      expenseObject.debit = input[1];
      require('./file-module.js').writeExpense(expenseObject);
      break;
    case 'credit':
      expenseObject.credit = input[1];
      require('./file-module.js').writeExpense(expenseObject);
      break;
    case 'stats':
      require('./stats-module.js').showStats();
      break;
    case 'clear':
      require('./close-account.js').closeAccount();
      break;
    case 'export':
      require('./export-module.js').exportToFile();
      break;
    case 'stash':
    case 'unstash':
      require('./stash-module.js').stashUnstash(input[0], input[1]);
      break;
    default:
      throw new Error(Consts.MSG_INVALID_OPTION);
  }
};
<commit_msg>Fix nasty bug because of using wrong operator<commit_after>'use strict';
module.exports = function (input, opts) {
  var Consts = require('./consts.js');

  var expenseObject = {
    reason: input[2],
    category: opts.c,
    date: opts.d,
    credit: '',
    debit: ''
  };

  // validation step
  // make sure that everything is as it should be before proceeding

  if (expenseObject.date) {
    var dateRe = /(\d{4})-(\d{2})-(\d{2})/;
    var matchObject = expenseObject.date.match(dateRe);
    if (!matchObject) {
      throw new Error(Consts.MSG_INVALID_DATE);
    }
  } else {
    expenseObject.date = require('date-format').asString('yyyy-MM-dd', new Date());
  }

  // end validation step

  if (input[0] === 'file_path') {
    // open the wallet file in `less`
    console.log(Consts.WALLET_FILE_PATH);
    process.exit(0);
  }

  if (input[0] === 'credit' || input[0] === 'debit') {
    if (input.length < 3 || typeof input[1] !== 'number') {
      throw new Error(Consts.MSG_ERR_CREDIT_DEBIT_TRANS);
    }
  }

  if (input[0] === 'stash' || input[0] === 'unstash') {
    if (input.length < 2) {
      throw new Error(Consts.MSG_ERR_STASH_TRANS);
    } else if (typeof input[1] !== number) {
      throw new Error(Consts.MSG_ERR_STASH_TRANS);
    }
  }

  switch (input[0]) {
    case 'debit':
      expenseObject.debit = input[1];
      require('./file-module.js').writeExpense(expenseObject);
      break;
    case 'credit':
      expenseObject.credit = input[1];
      require('./file-module.js').writeExpense(expenseObject);
      break;
    case 'stats':
      require('./stats-module.js').showStats();
      break;
    case 'clear':
      require('./close-account.js').closeAccount();
      break;
    case 'export':
      require('./export-module.js').exportToFile();
      break;
    case 'stash':
    case 'unstash':
      require('./stash-module.js').stashUnstash(input[0], input[1]);
      break;
    default:
      throw new Error(Consts.MSG_INVALID_OPTION);
  }
};
<|endoftext|>


<commit_before>'use strict';

var archiveType = require('archive-type');
var bz2 = require('seek-bzip');
var sbuff = require('simple-bufferstream');
var path = require('path');
var tar = require('tar');

/**
 * tar.bz2 decompress plugin
 *
 * @param {Object} opts
 * @api public
 */

module.exports = function (opts) {
    opts = opts || {};
    opts.strip = +opts.strip || 0;

    return function (file, decompress, cb) {
        var files = [];

        if (archiveType(file.contents) !== 'bz2') {
            return cb();
        }

        file.contents = bz2.decode(file.contents);

        sbuff(file.contents).pipe(tar.Parse())
            .on('error', function (err) {
                return cb(err);
            })
            .on('entry', function (file) {
                var chunk = '';

                file.on('data', function (data) {
                    chunk += data.toString();
                });

                file.on('end', function () {
                    chunk = new Buffer(chunk, 'utf8');

                    if (opts.strip) {
                        var f = path.basename(file.path);
                        var p = path.dirname(file.path.split('/'));

                        if (Array.isArray(p)) {
                            p = p.slice(opts.strip).join(path.sep);
                        }

                        file.path = path.join(p, f);
                    }

                    files.push({ contents: chunk, path: file.path });
                });
            })
            .on('end', function () {
                decompress.files = files;
                cb();
            });
    };
};
<commit_msg>Ignore directories<commit_after>'use strict';

var archiveType = require('archive-type');
var bz2 = require('seek-bzip');
var sbuff = require('simple-bufferstream');
var path = require('path');
var tar = require('tar');

/**
 * tar.bz2 decompress plugin
 *
 * @param {Object} opts
 * @api public
 */

module.exports = function (opts) {
    opts = opts || {};
    opts.strip = +opts.strip || 0;

    return function (file, decompress, cb) {
        var files = [];

        if (archiveType(file.contents) !== 'bz2') {
            return cb();
        }

        file.contents = bz2.decode(file.contents);

        sbuff(file.contents).pipe(tar.Parse())
            .on('error', function (err) {
                return cb(err);
            })
            .on('entry', function (file) {
                if (file.type !== 'Directory') {
                    var chunk = '';

                    file.on('data', function (data) {
                        chunk += data.toString();
                    });

                    file.on('end', function () {
                        chunk = new Buffer(chunk, 'utf8');

                        if (opts.strip) {
                            var f = path.basename(file.path);
                            var p = path.dirname(file.path.split('/'));

                            if (Array.isArray(p)) {
                                p = p.slice(opts.strip).join(path.sep);
                            }

                            file.path = path.join(p, f);
                        }

                        files.push({ contents: chunk, path: file.path });
                    });
                }
            })
            .on('end', function () {
                decompress.files = files;
                cb();
            });
    };
};
<|endoftext|>


<commit_before>var PJs;
class Blockp5 {
    constructor() {
        this._status = "run";
        this.p5_obj = {};
    }

    set status(s) {
        this._status = s;
    }

    get status() {
        return this._status;
    }

    runCode() {
        window.LoopTrap = 1000;
        Blockly.JavaScript.INFINITE_LOOP_TRAP =
            'if (--window.LoopTrap == 0) throw "Infinite loop.";\n';
        let code = Blockly.JavaScript.workspaceToCode(workspace);
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;

        try {
            let s = new Function("p", code);
            this.p5_obj = new p5(s);
        } catch (e) {
            alert(e);
        }
    }

    viewCode() {
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
        let code = Blockly.JavaScript.workspaceToCode(workspace);
        let codeDiv = document.getElementById('codeDiv');
        let html = Prism.highlight(code, Prism.languages.javascript, 'javascript');
        codeDiv.innerHTML = html;
    }

}

//  Block initiarize

let blocklyArea = document.getElementById('blocklyArea');
let blocklyDiv = document.getElementById('blocklyDiv');
let toolboxText = document.getElementById('toolbox').outerHTML;
let toolboxXml = Blockly.Xml.textToDom(toolboxText);
let workspace = Blockly.inject(blocklyDiv, {
    media: '../../media/',
    toolbox: toolboxXml,
    collapse: true,
    comments: true,
    disable: false,
    maxBlocks: Infinity,
    trashcan: true,
    horizontalLayout: false,
    toolboxPosition: 'start',
    css: true,
    media: 'https://blockly-demo.appspot.com/static/media/',
    rtl: false,
    scrollbars: true,
    sounds: true,
    oneBasedIndex: true,
    grid: {
        spacing: 20,
        length: 1,
        colour: '#888',
        snap: true
    },
    zoom: {
        controls: true,
        wheel: false,
        startScale: 1,
        maxScale: 3,
        minScale: 0.3,
        scaleSpeed: 1.2
    }
});

Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'), workspace);

// Browser window resize
let onresize = function(e) {
    // Compute the absolute coordinates and dimensions of blocklyArea.
    let element = blocklyArea;
    let x = 0;
    let y = 0;
    do {
        x += element.offsetLeft;
        y += element.offsetTop;
        element = element.offsetParent;
    } while (element);
    // Position blocklyDiv over blocklyArea.
    blocklyDiv.style.left = x + 'px';
    blocklyDiv.style.top = y + 'px';
    blocklyDiv.style.width = blocklyArea.offsetWidth + 'px';
    blocklyDiv.style.height = blocklyArea.offsetHeight + 'px';
};

window.addEventListener('resize', onresize, false);
window.scrollTo(0, 0);
workspace.resizeContents();
setTimeout(function() {
    onresize();
    Blockly.svgResize(workspace);
}, 1000)

// Init blockp5
var blockp5 = new Blockp5();
blockp5.viewCode();
blockp5.runCode();

document.getElementById('p5Run').onclick = function() {
    blockp5.status = "run";
    blockp5.runCode();
};

document.getElementById('p5Reset').onclick = function() {
    if (confirm("Reset All!")) {
        window.scrollTo(0, 0);
        location.reload(false);
    }
};

document.getElementById('blockly_code_tab').onclick = function() {
    blockp5.viewCode();
};
<commit_msg>refactaring<commit_after>var PJs;
class Blockp5 {
    constructor() {
        this.p5_obj = {};
    }

    runCode() {
        window.LoopTrap = 1000;
        Blockly.JavaScript.INFINITE_LOOP_TRAP =
            'if (--window.LoopTrap == 0) throw "Infinite loop.";\n';
        let code = Blockly.JavaScript.workspaceToCode(workspace);
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;

        try {
            let s = new Function("p", code);
            this.p5_obj = new p5(s);
        } catch (e) {
            alert(e);
        }
    }

    viewCode() {
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
        let code = Blockly.JavaScript.workspaceToCode(workspace);
        let codeDiv = document.getElementById('codeDiv');
        let html = Prism.highlight(code, Prism.languages.javascript, 'javascript');
        codeDiv.innerHTML = html;
    }

}

//  Block initiarize

let blocklyArea = document.getElementById('blocklyArea');
let blocklyDiv = document.getElementById('blocklyDiv');
let toolboxText = document.getElementById('toolbox').outerHTML;
let toolboxXml = Blockly.Xml.textToDom(toolboxText);
let workspace = Blockly.inject(blocklyDiv, {
    media: '../../media/',
    toolbox: toolboxXml,
    collapse: true,
    comments: true,
    disable: false,
    maxBlocks: Infinity,
    trashcan: true,
    horizontalLayout: false,
    toolboxPosition: 'start',
    css: true,
    media: 'https://blockly-demo.appspot.com/static/media/',
    rtl: false,
    scrollbars: true,
    sounds: true,
    oneBasedIndex: true,
    grid: {
        spacing: 20,
        length: 1,
        colour: '#888',
        snap: true
    },
    zoom: {
        controls: true,
        wheel: false,
        startScale: 1,
        maxScale: 3,
        minScale: 0.3,
        scaleSpeed: 1.2
    }
});

Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'), workspace);

// Browser window resize
let onresize = function(e) {
    // Compute the absolute coordinates and dimensions of blocklyArea.
    let element = blocklyArea;
    let x = 0;
    let y = 0;
    do {
        x += element.offsetLeft;
        y += element.offsetTop;
        element = element.offsetParent;
    } while (element);
    // Position blocklyDiv over blocklyArea.
    blocklyDiv.style.left = x + 'px';
    blocklyDiv.style.top = y + 'px';
    blocklyDiv.style.width = blocklyArea.offsetWidth + 'px';
    blocklyDiv.style.height = blocklyArea.offsetHeight + 'px';
};

window.addEventListener('resize', onresize, false);
window.scrollTo(0, 0);
workspace.resizeContents();
setTimeout(function() {
    onresize();
    Blockly.svgResize(workspace);
}, 1000)

// Init blockp5
var blockp5 = new Blockp5();
blockp5.viewCode();
blockp5.runCode();

document.getElementById('p5Run').onclick = function() {
    blockp5.runCode();
};

document.getElementById('p5Reset').onclick = function() {
    if (confirm("Reset All!")) {
        window.scrollTo(0, 0);
        location.reload(false);
    }
};

document.getElementById('blockly_code_tab').onclick = function() {
    blockp5.viewCode();
};
<|endoftext|>


<commit_before>const wildcard = require('wildcard');
const co = require('co');

const PopulationStrategies = {
    'express': {
        getMethod: (req, res) => {
            return req.method;
        },
        getPath: (req, res) => {
            return req.path;
        },
        isSecure: (req, res) => {
            return req.secure;
        },
        getOrigin: (req, res) => {
            return req.get('origin') || '';
        },
        getIpAddress: (req, res) => {
            return req.ip;
        }
    },
    'restify': {
        getMethod: (req, res) => {
            return req.method;
        },
        getPath: (req, res) => {
            return req.getPath();
        },
        isSecure: (req, res) => {
            return req.isSecure();
        },
        getOrigin: (req, res) => {
            return req.headers['origin'] || '';
        },
        getIpAddress: (req, res) => {
            return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        }
    }
}

function compare(pattern, s) {
    if (typeof (s) !== 'string') return false;

    if (pattern instanceof RegExp) {
        return s.match(pattern);
    }

    return wildcard(pattern, s);
}

function roleschk(uroles, rroles) {
    if (uroles.length === 0) return rroles.indexOf('*') >= 0;

    for (let i = 0; i < rroles.length; i++) {
        for (let z = 0; z < uroles.length; z++) {
            if (compare(rroles[i], uroles[z])) return true;
        }
    }

    return false;
}

function emptyfn() {
    return true;
}

module.exports = (config) => {
    config.defaultAction = (config.defaultAction || 'DROP').toUpperCase();
    for (let rule of config.rules) {
        rule.origin = rule.origin || ['*'];
        rule.methods = rule.methods || ['*'];
        rule.ipAddresses = rule.ipAddresses || ['*'];
        rule.secure = (rule.secure === true);
        rule.handler = rule.handler || emptyfn;
    }
    let strategy = PopulationStrategies[config.populationStrategy] || PopulationStrategies['restify'];

    return function (req, res, next) {
        co(function* () {
            let getUserEmail = config.getUserEmail || Promise.resolve(req.user ? req.user.email : null);
            let getUserPhone = config.getUserPhone || Promise.resolve(req.user ? req.user.phone : null);
            let getUserRoles = config.getUserRoles || Promise.resolve(req.user ? req.user.roles : null);

            let method = strategy.getMethod(req, res);
            let path = strategy.getPath(req, res);
            let secure = strategy.isSecure(req, res);
            let origin = strategy.getOrigin(req, res);
            let ipAddress = strategy.getIpAddress(req, res);
            let email = yield getUserEmail(req);
            let phone = yield getUserPhone(req);
            let roles = yield getUserRoles(req);

            for (let rule of config.rules) {
                if (rule.paths.find((e) => compare(e, path))) {
                    if (rule.methods.find((e) => compare(e.toUpperCase(), method)) &&
                        rule.origin.find((e) => compare(e, origin)) &&
                        rule.ipAddresses.find((e) => compare(e, ipAddress)) &&
                        (!rule.users || rule.users.find((e) => compare(e, email)) || rule.users.find((e) => compare(e, phone))) &&
                        (!rule.roles || roleschk(roles, rule.roles)) &&
                        (undefined === rule.secure || secure == rule.secure) &&
                        (yield rule.handler(req))) {
                        switch (rule.action.toUpperCase()) {
                            case 'ACCEPT':
                                next();
                                break;
                            case 'DROP':
                                let err = new Error();
                                err.status = 401;
                                next(err);
                                break;
                        }

                        return;
                    }
                }
            }

            switch (config.defaultAction) {
                case 'ACCEPT':
                    next();
                    break;
                case 'DROP':
                    let err = new Error();
                    err.status = 401;
                    next(err);
                    break;
            }
        }).catch(next);
    };
}<commit_msg>Properly defining default population functions.<commit_after>const wildcard = require('wildcard');
const co = require('co');

const PopulationStrategies = {
    'express': {
        getMethod: (req, res) => {
            return req.method;
        },
        getPath: (req, res) => {
            return req.path;
        },
        isSecure: (req, res) => {
            return req.secure;
        },
        getOrigin: (req, res) => {
            return req.get('origin') || '';
        },
        getIpAddress: (req, res) => {
            return req.ip;
        }
    },
    'restify': {
        getMethod: (req, res) => {
            return req.method;
        },
        getPath: (req, res) => {
            return req.getPath();
        },
        isSecure: (req, res) => {
            return req.isSecure();
        },
        getOrigin: (req, res) => {
            return req.headers['origin'] || '';
        },
        getIpAddress: (req, res) => {
            return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        }
    }
}

function compare(pattern, s) {
    if (typeof (s) !== 'string') return false;

    if (pattern instanceof RegExp) {
        return s.match(pattern);
    }

    return wildcard(pattern, s);
}

function roleschk(uroles, rroles) {
    if (uroles.length === 0) return rroles.indexOf('*') >= 0;

    for (let i = 0; i < rroles.length; i++) {
        for (let z = 0; z < uroles.length; z++) {
            if (compare(rroles[i], uroles[z])) return true;
        }
    }

    return false;
}

function emptyfn() {
    return true;
}

module.exports = (config) => {
    config.defaultAction = (config.defaultAction || 'DROP').toUpperCase();
    for (let rule of config.rules) {
        rule.origin = rule.origin || ['*'];
        rule.methods = rule.methods || ['*'];
        rule.ipAddresses = rule.ipAddresses || ['*'];
        rule.secure = (rule.secure === true);
        rule.handler = rule.handler || emptyfn;
    }
    let strategy = PopulationStrategies[config.populationStrategy] || PopulationStrategies['restify'];

    return function (req, res, next) {
        co(function* () {
            let getUserEmail = config.getUserEmail || ((req) => Promise.resolve(req.user ? req.user.email : null));
            let getUserPhone = config.getUserPhone || ((req) => Promise.resolve(req.user ? req.user.phone : null));
            let getUserRoles = config.getUserRoles || ((req) => Promise.resolve(req.user ? req.user.roles : null));

            let method = strategy.getMethod(req, res);
            let path = strategy.getPath(req, res);
            let secure = strategy.isSecure(req, res);
            let origin = strategy.getOrigin(req, res);
            let ipAddress = strategy.getIpAddress(req, res);
            let email = yield getUserEmail(req);
            let phone = yield getUserPhone(req);
            let roles = yield getUserRoles(req);

            for (let rule of config.rules) {
                if (rule.paths.find((e) => compare(e, path))) {
                    if (rule.methods.find((e) => compare(e.toUpperCase(), method)) &&
                        rule.origin.find((e) => compare(e, origin)) &&
                        rule.ipAddresses.find((e) => compare(e, ipAddress)) &&
                        (!rule.users || rule.users.find((e) => compare(e, email)) || rule.users.find((e) => compare(e, phone))) &&
                        (!rule.roles || roleschk(roles, rule.roles)) &&
                        (undefined === rule.secure || secure == rule.secure) &&
                        (yield rule.handler(req))) {
                        switch (rule.action.toUpperCase()) {
                            case 'ACCEPT':
                                next();
                                break;
                            case 'DROP':
                                let err = new Error();
                                err.status = 401;
                                next(err);
                                break;
                        }

                        return;
                    }
                }
            }

            switch (config.defaultAction) {
                case 'ACCEPT':
                    next();
                    break;
                case 'DROP':
                    let err = new Error();
                    err.status = 401;
                    next(err);
                    break;
            }
        }).catch(next);
    };
}<|endoftext|>