<commit_before>var _b_ = __BRYTHON__.builtins

function get_self(name, args){
    return $B.args(name, 1, {self: null}, ["self"], args, {}, null, null).self
}

var _IOBase = $B.make_class("_IOBase")
_IOBase.__mro__ = [_b_.object]

_IOBase.close = function(){
    get_self("close", arguments).__closed = true
}

_IOBase.flush = function(){
    get_self("flush", arguments)
    return _b_.None
}

$B.set_func_names(_IOBase, '_io')

// Base class for binary streams that support some kind of buffering.
var _BufferedIOBase = $B.make_class("_BufferedIOBase")
_BufferedIOBase.__mro__ = [_IOBase, _b_.object]

_BufferedIOBase.__enter__ = function(self){
    return self
}
_BufferedIOBase.__exit__ = function(self, type, value, traceback){
    try{
        $B.$call($B.$getattr(self, 'close'))()
        self.__closed = true
        return true
    }catch(err){
        return false
    }
}

$B.set_func_names(_BufferedIOBase, '_io')

// Base class for raw binary I/O.
var _RawIOBase = $B.make_class("_RawIOBase")

_RawIOBase.__mro__ = [_IOBase, _b_.object]

_RawIOBase.read = function(){
    var $ = $B.args("read", 2, {self: null, size: null}, ["self", "size"],
                    arguments, {size: -1}, null, null),
        self = $.self,
        size = $.size,
        res
    self.$pos = self.$pos || 0
    if(size == -1){
        if(self.$pos == 0){
            res = self.$content
        }else{
            res = _b_.bytes.$factory(self.$content.source.slice(self.$pos))
        }
        self.$pos = self.$content.source.length - 1
    }else{
        res = _b_.bytes.$factory(self.$content.source.slice(self.$pos, size))
        self.$pos += size
    }
    return res
}

_RawIOBase.readall = function(){
    return _RawIOBase.read(get_self("readall", arguments))
}

$B.set_func_names(_RawIOBase, '_io')

// Base class for text streams.
_TextIOBase = $B.make_class("_TextIOBase")
_TextIOBase.__mro__ = [_IOBase, _b_.object]

var StringIO = $B.make_class("StringIO",
    function(){
        var $ = $B.args("StringIO", 2, {value: null, newline: null},
                ["value", "newline"], arguments, {value: '', newline: "\n"},
                null, null)
        return {
            __class__: StringIO,
            $counter: 0,
            $content: $.value
        }
    }
)
StringIO.__mro__ = [$B.Reader, _b_.object]

StringIO.getvalue = function(){
    var $ = $B.args("getvalue", 1, {self: null},
            ["self"], arguments, {}, null, null)
    return $.self.$content
}

StringIO.write = function(){
    var $ = $B.args("write", 2, {self: null, data: null},
            ["self", "data"], arguments, {}, null, null)
    if(! _b_.isinstance($.data, _b_.str)){
        throw _b_.TypeError.$factory('string argument expected, got ' +
            `'${$B.class_name($.data)}'`)
    }
    var text = $.self.$content,
        position = $.self.$counter
    text = text.substr(0, position) + $.data +
        text.substr(position + $.data.length)
    $.self.$content = text
    $.self.$counter += $.data.length
    return $.data.length
}

$B.set_func_names(StringIO, "_io")

var BytesIO = $B.make_class("BytesIO",
    function(){
        var $ = $B.args("BytesIO", 1, {value: null},
                ["value"], arguments, {value: _b_.bytes.$factory()},
                null, null)
        return {
            __class__: BytesIO,
            $binary: true,
            $content: $.value,
            $length: $.value.source.length,
            $counter: 0
        }
    }
)
BytesIO.__mro__ = [$B.Reader, _b_.object]

BytesIO.getbuffer = function(){
    var self = get_self("getbuffer", arguments)
    return self.$content
}

BytesIO.getvalue = function(){
    var self = get_self("getvalue", arguments)
    return self.$content
}

BytesIO.write = function(){
    var $ = $B.args("write", 2, {self: null, data: null},
            ["self", "data"], arguments, {}, null, null)
    $.self.$content.source = $.self.$content.source.concat(
        $.data.source)
    $.self.$counter += $.data.source.length
    return _b_.None
}

$B.set_func_names(BytesIO, "_io")

var BlockingIOError = $B.make_class('BlockingIOError')
BlockingIOError.__bases__ = [_b_.OSError]

$B.set_func_names(BlockingIOError, '_io')

var $module = (function($B){
    return {
        _BufferedIOBase,
        _IOBase,
        _RawIOBase,
        _TextIOBase: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BlockingIOError,
        BytesIO: BytesIO,
        FileIO: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        StringIO: StringIO,
        BufferedReader: $B.BufferedReader,
        BufferedWriter: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BufferedRWPair: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BufferedRandom: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        IncrementalNewlineDecoder: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        TextIOWrapper: $B.TextIOWrapper
    }
})(__BRYTHON__)
$module._IOBase.__doc__ = "_IOBase"<commit_msg>Add method truncate() to StringIO<commit_after>var _b_ = __BRYTHON__.builtins

function get_self(name, args){
    return $B.args(name, 1, {self: null}, ["self"], args, {}, null, null).self
}

var _IOBase = $B.make_class("_IOBase")
_IOBase.__mro__ = [_b_.object]

_IOBase.close = function(){
    get_self("close", arguments).__closed = true
}

_IOBase.flush = function(){
    get_self("flush", arguments)
    return _b_.None
}

$B.set_func_names(_IOBase, '_io')

// Base class for binary streams that support some kind of buffering.
var _BufferedIOBase = $B.make_class("_BufferedIOBase")
_BufferedIOBase.__mro__ = [_IOBase, _b_.object]

_BufferedIOBase.__enter__ = function(self){
    return self
}
_BufferedIOBase.__exit__ = function(self, type, value, traceback){
    try{
        $B.$call($B.$getattr(self, 'close'))()
        self.__closed = true
        return true
    }catch(err){
        return false
    }
}

$B.set_func_names(_BufferedIOBase, '_io')

// Base class for raw binary I/O.
var _RawIOBase = $B.make_class("_RawIOBase")

_RawIOBase.__mro__ = [_IOBase, _b_.object]

_RawIOBase.read = function(){
    var $ = $B.args("read", 2, {self: null, size: null}, ["self", "size"],
                    arguments, {size: -1}, null, null),
        self = $.self,
        size = $.size,
        res
    self.$pos = self.$pos || 0
    if(size == -1){
        if(self.$pos == 0){
            res = self.$content
        }else{
            res = _b_.bytes.$factory(self.$content.source.slice(self.$pos))
        }
        self.$pos = self.$content.source.length - 1
    }else{
        res = _b_.bytes.$factory(self.$content.source.slice(self.$pos, size))
        self.$pos += size
    }
    return res
}

_RawIOBase.readall = function(){
    return _RawIOBase.read(get_self("readall", arguments))
}

$B.set_func_names(_RawIOBase, '_io')

// Base class for text streams.
_TextIOBase = $B.make_class("_TextIOBase")
_TextIOBase.__mro__ = [_IOBase, _b_.object]

var StringIO = $B.make_class("StringIO",
    function(){
        var $ = $B.args("StringIO", 2, {value: null, newline: null},
                ["value", "newline"], arguments, {value: '', newline: "\n"},
                null, null)
        return {
            __class__: StringIO,
            $counter: 0,
            $content: $.value
        }
    }
)

StringIO.__mro__ = [$B.Reader, _b_.object]

StringIO.getvalue = function(){
    var $ = $B.args("getvalue", 1, {self: null},
            ["self"], arguments, {}, null, null)
    return $.self.$content
}

StringIO.truncate = function(self, size){
    var $ = $B.args('truncate', 2, {self: null, size: null}, ['self', 'size'],
            arguments, {size: _b_.None}, null, null),
        self = $.self,
        size = $.size
    if(size === _b_.None){
        self.$counter = self.$content.length - 1
    }else{
        self.$content = self.$content.substr(0, size)
        self.$counter = self.$content.length - 1
    }
    return self.$counter
}

StringIO.write = function(){
    var $ = $B.args("write", 2, {self: null, data: null},
            ["self", "data"], arguments, {}, null, null)
    if(! _b_.isinstance($.data, _b_.str)){
        throw _b_.TypeError.$factory('string argument expected, got ' +
            `'${$B.class_name($.data)}'`)
    }
    var text = $.self.$content,
        position = $.self.$counter
    text = text.substr(0, position) + $.data +
        text.substr(position + $.data.length)
    $.self.$content = text
    $.self.$counter += $.data.length
    return $.data.length
}

$B.set_func_names(StringIO, "_io")

var BytesIO = $B.make_class("BytesIO",
    function(){
        var $ = $B.args("BytesIO", 1, {value: null},
                ["value"], arguments, {value: _b_.bytes.$factory()},
                null, null)
        return {
            __class__: BytesIO,
            $binary: true,
            $content: $.value,
            $length: $.value.source.length,
            $counter: 0
        }
    }
)
BytesIO.__mro__ = [$B.Reader, _b_.object]

BytesIO.getbuffer = function(){
    var self = get_self("getbuffer", arguments)
    return self.$content
}

BytesIO.getvalue = function(){
    var self = get_self("getvalue", arguments)
    return self.$content
}

BytesIO.write = function(){
    var $ = $B.args("write", 2, {self: null, data: null},
            ["self", "data"], arguments, {}, null, null)
    $.self.$content.source = $.self.$content.source.concat(
        $.data.source)
    $.self.$counter += $.data.source.length
    return _b_.None
}

$B.set_func_names(BytesIO, "_io")

var BlockingIOError = $B.make_class('BlockingIOError')
BlockingIOError.__bases__ = [_b_.OSError]

$B.set_func_names(BlockingIOError, '_io')

var $module = (function($B){
    return {
        _BufferedIOBase,
        _IOBase,
        _RawIOBase,
        _TextIOBase: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BlockingIOError,
        BytesIO: BytesIO,
        FileIO: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        StringIO: StringIO,
        BufferedReader: $B.BufferedReader,
        BufferedWriter: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BufferedRWPair: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        BufferedRandom: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        IncrementalNewlineDecoder: $B.make_class("_TextIOBase",
            function(){
                return "fileio"
            }
        ),
        TextIOWrapper: $B.TextIOWrapper
    }
})(__BRYTHON__)
$module._IOBase.__doc__ = "_IOBase"<|endoftext|>


<commit_before>var insults = {

  var request = require('request')
  var url = 'https://www.foaas.com/thanks/nick'
  var options = {
    url: url,
    method: 'GET'
  }

  function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
          // Print out the response body
          var result = JSON.parse(body)
          var message = result.message
          var subtitle = result.subtitle
          console.log('message:' + message)
          console.log('subtitle:' + subtitle)
      }
  }

  var regex = '.*'
  var location = 'ambient'

  function(slapp) {
    slapp.
      message(regex,location, (msg) => {
        request(options, callback)
      }
  }
}

module.exports = insults
<commit_msg>slapp missing<commit_after>var insults = {

  var request = require('request')
  var url = 'https://www.foaas.com/thanks/nick'
  var options = {
    url: url,
    method: 'GET'
  }

  function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
          // Print out the response body
          var result = JSON.parse(body)
          var message = result.message
          var subtitle = result.subtitle
          console.log('message:' + message)
          console.log('subtitle:' + subtitle)
      }
  }

  var regex = '.*'
  var location = 'ambient'

  function(slapp) {
    slapp.
      message(regex,location, (msg) => {
        request(options, callback)
      }
  }
}

module.exports = insults(slapp)
<|endoftext|>


<commit_before>import loadScript from 'load-script';
import Promise from 'promise';
import ThreeDSecureStrategy from './strategy';

const debug = require('debug')('recurly:risk:three-d-secure:stripe');

export default class StripeStrategy extends ThreeDSecureStrategy {
  static libUrl = 'https://js.stripe.com/v3/';
  static strategyName = 'stripe';

  constructor (...args) {
    super(...args);

    debug('loading Stripe library');
    this.loadStripeLibrary()
      .catch(cause => this.threeDSecure.error('3ds-vendor-load-error', { vendor: 'Stripe', cause }))
      .then(() => {
        this.stripe = window.Stripe(this.stripePublishableKey);
        debug('Stripe checkout instance created', this.stripe);
        this.markReady();
      });
  }

  get stripePublishableKey () {
    return this.actionToken.gateway.credentials.publishable_key;
  }

  get stripeClientSecret () {
    return this.actionToken.three_d_secure.params.client_secret;
  }

  /**
   * Provides the target DOM element for which we will apply
   * fingerprint detection, challenge flows, and results
   *
   * @param {HTMLElement} element
   */
  attach (element) {
    super.attach(element);

    this.whenReady(() => {
      const handleAction = this.stripeClientSecret.startsWith("pi") ? this.stripe.handleCardAction : this.stripe.confirmCardSetup

      handleAction(this.stripeClientSecret).then(result => {
        if (result.error) {
          return this.threeDSecure.error('3ds-auth-error', { cause: result.error });
        }
        const { id } = result.paymentIntent || result.setupIntent;
        this.emit('done', { id });
      });
    });
  }

  /**
   * Loads Stripe library dependency
   */
  loadStripeLibrary () {
    return new Promise((resolve, reject) => {
      if (window.Stripe) return resolve();
      loadScript(StripeStrategy.libUrl, error => {
        if (error) reject(error);
        else resolve();
      });
    });
  }
}
<commit_msg>fix linting errors<commit_after>import loadScript from 'load-script';
import Promise from 'promise';
import ThreeDSecureStrategy from './strategy';

const debug = require('debug')('recurly:risk:three-d-secure:stripe');

export default class StripeStrategy extends ThreeDSecureStrategy {
  static libUrl = 'https://js.stripe.com/v3/';
  static strategyName = 'stripe';

  constructor (...args) {
    super(...args);

    debug('loading Stripe library');
    this.loadStripeLibrary()
      .catch(cause => this.threeDSecure.error('3ds-vendor-load-error', { vendor: 'Stripe', cause }))
      .then(() => {
        this.stripe = window.Stripe(this.stripePublishableKey);
        debug('Stripe checkout instance created', this.stripe);
        this.markReady();
      });
  }

  get stripePublishableKey () {
    return this.actionToken.gateway.credentials.publishable_key;
  }

  get stripeClientSecret () {
    return this.actionToken.three_d_secure.params.client_secret;
  }

  /**
   * Provides the target DOM element for which we will apply
   * fingerprint detection, challenge flows, and results
   *
   * @param {HTMLElement} element
   */
  attach (element) {
    super.attach(element);

    this.whenReady(() => {
      const handleAction = this.stripeClientSecret.startsWith('pi') ? this.stripe.handleCardAction : this.stripe.confirmCardSetup;

      handleAction(this.stripeClientSecret).then(result => {
        if (result.error) {
          return this.threeDSecure.error('3ds-auth-error', { cause: result.error });
        }
        const { id } = result.paymentIntent || result.setupIntent;
        this.emit('done', { id });
      });
    });
  }

  /**
   * Loads Stripe library dependency
   */
  loadStripeLibrary () {
    return new Promise((resolve, reject) => {
      if (window.Stripe) return resolve();
      loadScript(StripeStrategy.libUrl, error => {
        if (error) reject(error);
        else resolve();
      });
    });
  }
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var _ = require('lodash'),
    utils = require('../../../utils/helpers'),
    hasOwnProperty = utils.object.hasOwnProperty;

/**
 * Model.toObject()
 *
 * Returns a cloned object containing just the model
 * values. Useful for doing operations on the current values
 * minus the instance methods.
 *
 * @param {Object} context, Waterline collection instance
 * @param {Object} proto, model prototype
 * @api public
 * @return {Object}
 */

var toObject = module.exports = function(context, proto) {

  this.context = context;
  this.proto = proto;

  this.object = Object.create(proto.__proto__);

  this.addAssociations();
  this.addProperties();
  this.makeObject();
  this.filterJoins();
  this.filterFunctions();

  return this.object;
};

/**
 * Add Association Keys
 *
 * If a showJoins flag is active, add all association keys.
 *
 * @param {Object} keys
 * @api private
 */

toObject.prototype.addAssociations = function() {
  var self = this;

  if(!this.proto._properties) return;
  if(!this.proto._properties.showJoins) return;

  // Copy prototype over for attributes
  for(var association in this.proto.associations) {

    // Handle hasMany attributes
    if(hasOwnProperty(this.proto.associations[association], 'value')) {

      var records = [];
      var values = this.proto.associations[association].value;

      values.forEach(function(record) {
        var item = Object.create(record.__proto__);
        Object.keys(record).forEach(function(key) {
          item[key] = _.cloneDeep(record[key]);
        });
        records.push(item);
      });

      this.object[association] = records;
      continue;
    }

    // Handle belongsTo attributes
    var record = this.proto[association];

    if(_.isObject(record) && !Array.isArray(record)) {

      var item = Object.create(record.__proto__);

      Object.keys(record).forEach(function(key) {
        item[key] = _.cloneDeep(record[key]);
      });

      this.object[association] = item;
    } else {
      this.object[association] = record;
    }
  }
};

/**
 * Add Properties
 *
 * Copies over non-association attributes to the newly created object.
 *
 * @api private
 */

toObject.prototype.addProperties = function() {
  var self = this;

  Object.keys(this.proto).forEach(function(key) {
    if(hasOwnProperty(self.object, key)) return;
    self.object[key] = _.cloneDeep(self.proto[key]);
  });
};

/**
 * Make Object
 *
 * Runs toJSON on all associated values
 *
 * @api private
 */

toObject.prototype.makeObject = function() {
  var self = this;

  if(!this.proto._properties) return;
  if(!this.proto._properties.showJoins) return;

  // Handle Belongs-To Joins
  Object.keys(this.proto.associations).forEach(function(association) {

    // Don't run toJSON on records that were not populated
    if(self.proto._properties && self.proto._properties.joins) {
      if(self.proto._properties.joins.indexOf(association) < 0) return;
    } else {
      return;
    }

    // Call toJSON on each associated record
    if(Array.isArray(self.object[association])) {
      var records = [];

      self.object[association].forEach(function(item) {
        if(!hasOwnProperty(item, 'toJSON')) return;
        records.push(item.toJSON());
      });

      self.object[association] = records;
      return;
    }

    if(!hasOwnProperty(self.object[association], 'toJSON')) return;
    self.object[association] = self.object[association].toJSON();
  });

};

/**
 * Remove Non-Joined Associations
 *
 * @api private
 */

toObject.prototype.filterJoins = function() {
  var attributes = this.context._attributes;
  var properties = this.proto._properties;

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'model') && !hasOwnProperty(attributes[attribute], 'collection')) continue;

    // If no properties and a collection attribute, delete the association and return
    if(!properties && hasOwnProperty(attributes[attribute], 'collection')) {
      delete this.object[attribute];
      continue;
    }

    // If showJoins is false remove the association object
    if(properties && !properties.showJoins) {

      // Don't delete belongs to keys
      if(!attributes[attribute].model) delete this.object[attribute];
    }

    if(properties && properties.joins) {

      // Build up a join key name based on the attribute's model/collection name
      var joinsName = attribute;
      if(attributes[attribute].model) joinsName = attributes[attribute].model.toLowerCase();
      if(attributes[attribute].collection) joinsName = attributes[attribute].collection.toLowerCase();

      if(properties.joins.indexOf(joinsName) < 0) {

        // Don't delete belongs to keys
        if(!attributes[attribute].model) delete this.object[attribute];
      }
    }
  }
};

/**
 * Filter Functions
 *
 * @api private
 */

toObject.prototype.filterFunctions = function() {
  for(var key in this.object) {
    if(typeof this.object[key] === 'function') {
      delete this.object[key];
    }
  }
};
<commit_msg>fix hasOwnProperty check<commit_after>
/**
 * Module dependencies
 */

var _ = require('lodash'),
    utils = require('../../../utils/helpers'),
    hasOwnProperty = utils.object.hasOwnProperty;

/**
 * Model.toObject()
 *
 * Returns a cloned object containing just the model
 * values. Useful for doing operations on the current values
 * minus the instance methods.
 *
 * @param {Object} context, Waterline collection instance
 * @param {Object} proto, model prototype
 * @api public
 * @return {Object}
 */

var toObject = module.exports = function(context, proto) {

  this.context = context;
  this.proto = proto;

  this.object = Object.create(proto.__proto__);

  this.addAssociations();
  this.addProperties();
  this.makeObject();
  this.filterJoins();
  this.filterFunctions();

  return this.object;
};

/**
 * Add Association Keys
 *
 * If a showJoins flag is active, add all association keys.
 *
 * @param {Object} keys
 * @api private
 */

toObject.prototype.addAssociations = function() {
  var self = this;

  if(!this.proto._properties) return;
  if(!this.proto._properties.showJoins) return;

  // Copy prototype over for attributes
  for(var association in this.proto.associations) {

    // Handle hasMany attributes
    if(hasOwnProperty(this.proto.associations[association], 'value')) {

      var records = [];
      var values = this.proto.associations[association].value;

      values.forEach(function(record) {
        var item = Object.create(record.__proto__);
        Object.keys(record).forEach(function(key) {
          item[key] = _.cloneDeep(record[key]);
        });
        records.push(item);
      });

      this.object[association] = records;
      continue;
    }

    // Handle belongsTo attributes
    var record = this.proto[association];

    if(_.isObject(record) && !Array.isArray(record)) {

      var item = Object.create(record.__proto__);

      Object.keys(record).forEach(function(key) {
        item[key] = _.cloneDeep(record[key]);
      });

      this.object[association] = item;
    } else {
      this.object[association] = record;
    }
  }
};

/**
 * Add Properties
 *
 * Copies over non-association attributes to the newly created object.
 *
 * @api private
 */

toObject.prototype.addProperties = function() {
  var self = this;

  Object.keys(this.proto).forEach(function(key) {
    if(hasOwnProperty(self.object, key)) return;
    self.object[key] = _.cloneDeep(self.proto[key]);
  });
};

/**
 * Make Object
 *
 * Runs toJSON on all associated values
 *
 * @api private
 */

toObject.prototype.makeObject = function() {
  var self = this;

  if(!this.proto._properties) return;
  if(!this.proto._properties.showJoins) return;

  // Handle Belongs-To Joins
  Object.keys(this.proto.associations).forEach(function(association) {

    // Don't run toJSON on records that were not populated
    if(self.proto._properties && self.proto._properties.joins) {
      if(self.proto._properties.joins.indexOf(association) < 0) return;
    } else {
      return;
    }

    // Call toJSON on each associated record
    if(Array.isArray(self.object[association])) {
      var records = [];

      self.object[association].forEach(function(item) {
        if(!hasOwnProperty(item, 'toJSON')) return;
        records.push(item.toJSON());
      });

      self.object[association] = records;
      return;
    }

    if(!hasOwnProperty(self.object[association].__proto__, 'toJSON')) return;
    self.object[association] = self.object[association].toJSON();
  });

};

/**
 * Remove Non-Joined Associations
 *
 * @api private
 */

toObject.prototype.filterJoins = function() {
  var attributes = this.context._attributes;
  var properties = this.proto._properties;

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'model') && !hasOwnProperty(attributes[attribute], 'collection')) continue;

    // If no properties and a collection attribute, delete the association and return
    if(!properties && hasOwnProperty(attributes[attribute], 'collection')) {
      delete this.object[attribute];
      continue;
    }

    // If showJoins is false remove the association object
    if(properties && !properties.showJoins) {

      // Don't delete belongs to keys
      if(!attributes[attribute].model) delete this.object[attribute];
    }

    if(properties && properties.joins) {

      // Build up a join key name based on the attribute's model/collection name
      var joinsName = attribute;
      if(attributes[attribute].model) joinsName = attributes[attribute].model.toLowerCase();
      if(attributes[attribute].collection) joinsName = attributes[attribute].collection.toLowerCase();

      if(properties.joins.indexOf(joinsName) < 0) {

        // Don't delete belongs to keys
        if(!attributes[attribute].model) delete this.object[attribute];
      }
    }
  }
};

/**
 * Filter Functions
 *
 * @api private
 */

toObject.prototype.filterFunctions = function() {
  for(var key in this.object) {
    if(typeof this.object[key] === 'function') {
      delete this.object[key];
    }
  }
};
<|endoftext|>


<commit_before>module.exports = {
    "rules": {
        // enforce linebreaks after opening and before closing array brackets
        "array-bracket-newline": 0,
        // enforce spacing inside array brackets
        "array-bracket-spacing": 0,
        // enforce line breaks after each array element
        "array-element-newline": 0,
        // disallow or enforce spaces inside of single line blocks
        "block-spacing": 0,
        // enforce one true brace style
        "brace-style": 2,
        // require camel case names
        "camelcase": 1,
        // enforce or disallow capitalization of the first letter of a comment
        "capitalized-comments": 0,
        // disallow trailing commas in object literals
        "comma-dangle": 2,
        // enforce spacing before and after comma
        "comma-spacing": 2,
        // enforce one true comma style
        "comma-style": 2,
        // require or disallow padding inside computed properties
        "computed-property-spacing": 0,
        // enforces consistent naming when capturing the current execution context
        "consistent-this": [1, "self"],
        // enforce newline at the end of file, with no multiple empty lines
        "eol-last": 0,
        // require or disallow spacing between function identifiers and their invocations
        "func-call-spacing": 0,
        // require function names to match the name of the variable or property to which they are assigned
        "func-name-matching": 0,
        // require function expressions to have a name
        "func-names": 0,
        // enforces use of function declarations or expressions
        "func-style": 0,
        // disallow specified identifiers
        "id-blacklist": 0,
        // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
        "id-length": 0,
        // require identifiers to match the provided regular expression
        "id-match": 0,
        // this option sets a specific tab width for your code
        "indent": [1, 4, {"SwitchCase": 1, "VariableDeclarator": 1}],
        // specify whether double or single quotes should be used in JSX attributes
        "jsx-quotes": 0,
        // enforces spacing between keys and values in object literal properties
        "key-spacing": [1, { "beforeColon": false, "afterColon": true }],
        // enforces spacing before and after keywords
        "keyword-spacing": [1, {"before": true, "after": true, "overrides": {}}],
        // enforce position of line comments
        "line-comment-position": 0,
        // disallow mixed 'LF' and 'CRLF' as linebreaks
        "linebreak-style": 0,
        // enforces empty lines around comments
        "lines-around-comment": 0,
        // specify the maximum depth that blocks can be nested
        "max-depth": [1, 4],
        // specify the maximum length of a line in your program
        "max-len": [1, { "code": 120, "tabWidth": 4, "ignoreComments": true, "ignoreUrls": true}],
        // enforce a maximum number of lines per file
        "max-lines": 0,
        // specify the maximum depth callbacks can be nested
        "max-nested-callbacks": 0,
        // limits the number of parameters that can be used in the function declaration.
        "max-params": 0,
        // enforce a maximum number of statements allowed per line
        "max-statements-per-line": 0,
        // specify the maximum number of statement allowed in a function
        "max-statements": 0,
        // enforce newlines between operands of ternary expressions
        "multiline-ternary": [1, "always-multiline"],
        // require a capital letter for constructors
        "new-cap": 0, // NOTE - DO NOT TOUCH. Use rule in babel.js
        // disallow the omission of parentheses when invoking a constructor with no arguments
        "new-parens": 0,
        // require a newline after each call in a method chain
        "newline-per-chained-call": 1,
        // disallow use of the Array constructor
        "no-array-constructor": 0,
        // disallow use of bitwise operators
        "no-bitwise": 0,
        // disallow use of the continue statement
        "no-continue": 0,
        // disallow comments inline after code
        "no-inline-comments": 0,
        // disallow if as the only statement in an else block
        "no-lonely-if": 1,
        // disallow mixed binary operators
        "no-mixed-operators": 2,
        // disallow mixed spaces and tabs for indentation
        "no-mixed-spaces-and-tabs": [2, false],
        // disallow use of chained assignment expressions
        "no-multi-assign": 2,
        // disallow multiple empty lines
        "no-multiple-empty-lines": 0,
        // disallow negated conditions
        "no-negated-condition": 0,
        // disallow nested ternary expressions
        "no-nested-ternary": 2,
        // disallow use of the Object constructor
        "no-new-object": 0,
        // disallow use of unary operators, ++ and --
        "no-plusplus": 0,
        // disallow use of certain syntax in code
        "no-restricted-syntax": 0,
        // disallow the use of ternary operators
        "no-ternary": 0,
        // disallow trailing whitespace at the end of lines
        "no-trailing-spaces": 1,
        // disallow dangling underscores in identifiers
        "no-underscore-dangle": 0,
        // disallow the use of Boolean literals in conditional expressions
        "no-unneeded-ternary": 2,
        // disallow whitespace before properties
        "no-whitespace-before-property": 2,
        // enforce the location of single-line statements
        "nonblock-statement-body-position": 0,
        // enforce consistent line breaks inside braces
        "object-curly-newline": 0,
        // require or disallow padding inside curly braces
        "object-curly-spacing": 0, // NOTE - DO NOT TOUCH. Use rule in babel.js
        // enforce placing object properties on separate lines
        "object-property-newline": 0,
        // allow just one var statement per function
        "one-var": [2, "never"],
        // require assignment operator shorthand where possible or prohibit it entirely
        "operator-assignment": 0,
        // enforce operators to be placed before or after line breaks
        "operator-linebreak": 0,
        // enforce padding within blocks
        "padded-blocks": 0,
        // require or disallow padding lines between statements
        "padding-line-between-statements": 0,
        // require quotes around object literal property names
        "quote-props": 0,
        // specify whether double or single quotes should be used
        "quotes": [1, "double"],
        // Require JSDoc comment
        "require-jsdoc": 0,
        // enforce spacing before and after semicolons
        "semi-spacing": 2,
        // enforce location of semicolons
        "semi-style": 2,
        // require or disallow use of semicolons instead of ASI
        "semi": 2,
        // require object keys to be sorted
        "sort-keys": 0,
        // sort variables within the same declaration block
        "sort-vars": 0,
        // require or disallow space before blocks
        "space-before-blocks": 0,
        // require or disallow space before function opening parenthesis
        "space-before-function-paren": [1, {"anonymous": "always", "named": "never"}],
        // require or disallow spaces inside parentheses
        "space-in-parens": 0,
        // require spaces around operators
        "space-infix-ops": 1,
        // Require or disallow spaces before/after unary operators
        "space-unary-ops": 0,
        // require or disallow a space immediately following the // or /* in a comment
        "spaced-comment": [1, "always", {"exceptions": ["/"]}],
        // enforce spacing around colons of switch statements
        "switch-colon-spacing": 2,
        // require or disallow spacing between template tags and their literals
        "template-tag-spacing": 0,
        // require or disallow Unicode byte order mark (BOM)
        "unicode-bom": 0,
        // require regex literals to be wrapped in parentheses
        "wrap-regex": 0
    }
};
<commit_msg>Added new ESLint rule<commit_after>module.exports = {
    "rules": {
        // enforce linebreaks after opening and before closing array brackets
        "array-bracket-newline": 0,
        // enforce spacing inside array brackets
        "array-bracket-spacing": 0,
        // enforce line breaks after each array element
        "array-element-newline": 0,
        // disallow or enforce spaces inside of single line blocks
        "block-spacing": 0,
        // enforce one true brace style
        "brace-style": 2,
        // require camel case names
        "camelcase": 1,
        // enforce or disallow capitalization of the first letter of a comment
        "capitalized-comments": 0,
        // disallow trailing commas in object literals
        "comma-dangle": 2,
        // enforce spacing before and after comma
        "comma-spacing": 2,
        // enforce one true comma style
        "comma-style": 2,
        // require or disallow padding inside computed properties
        "computed-property-spacing": 0,
        // enforces consistent naming when capturing the current execution context
        "consistent-this": [1, "self"],
        // enforce newline at the end of file, with no multiple empty lines
        "eol-last": 0,
        // require or disallow spacing between function identifiers and their invocations
        "func-call-spacing": 0,
        // require function names to match the name of the variable or property to which they are assigned
        "func-name-matching": 0,
        // require function expressions to have a name
        "func-names": 0,
        // enforces use of function declarations or expressions
        "func-style": 0,
        // enforce consistent line breaks inside function parentheses
        "function-paren-newline": 0,
        // disallow specified identifiers
        "id-blacklist": 0,
        // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
        "id-length": 0,
        // require identifiers to match the provided regular expression
        "id-match": 0,
        // this option sets a specific tab width for your code
        "indent": [1, 4, {"SwitchCase": 1, "VariableDeclarator": 1}],
        // specify whether double or single quotes should be used in JSX attributes
        "jsx-quotes": 0,
        // enforces spacing between keys and values in object literal properties
        "key-spacing": [1, { "beforeColon": false, "afterColon": true }],
        // enforces spacing before and after keywords
        "keyword-spacing": [1, {"before": true, "after": true, "overrides": {}}],
        // enforce position of line comments
        "line-comment-position": 0,
        // disallow mixed 'LF' and 'CRLF' as linebreaks
        "linebreak-style": 0,
        // enforces empty lines around comments
        "lines-around-comment": 0,
        // specify the maximum depth that blocks can be nested
        "max-depth": [1, 4],
        // specify the maximum length of a line in your program
        "max-len": [1, { "code": 120, "tabWidth": 4, "ignoreComments": true, "ignoreUrls": true}],
        // enforce a maximum number of lines per file
        "max-lines": 0,
        // specify the maximum depth callbacks can be nested
        "max-nested-callbacks": 0,
        // limits the number of parameters that can be used in the function declaration.
        "max-params": 0,
        // enforce a maximum number of statements allowed per line
        "max-statements-per-line": 0,
        // specify the maximum number of statement allowed in a function
        "max-statements": 0,
        // enforce newlines between operands of ternary expressions
        "multiline-ternary": [1, "always-multiline"],
        // require a capital letter for constructors
        "new-cap": 0, // NOTE - DO NOT TOUCH. Use rule in babel.js
        // disallow the omission of parentheses when invoking a constructor with no arguments
        "new-parens": 0,
        // require a newline after each call in a method chain
        "newline-per-chained-call": 1,
        // disallow use of the Array constructor
        "no-array-constructor": 0,
        // disallow use of bitwise operators
        "no-bitwise": 0,
        // disallow use of the continue statement
        "no-continue": 0,
        // disallow comments inline after code
        "no-inline-comments": 0,
        // disallow if as the only statement in an else block
        "no-lonely-if": 1,
        // disallow mixed binary operators
        "no-mixed-operators": 2,
        // disallow mixed spaces and tabs for indentation
        "no-mixed-spaces-and-tabs": [2, false],
        // disallow use of chained assignment expressions
        "no-multi-assign": 2,
        // disallow multiple empty lines
        "no-multiple-empty-lines": 0,
        // disallow negated conditions
        "no-negated-condition": 0,
        // disallow nested ternary expressions
        "no-nested-ternary": 2,
        // disallow use of the Object constructor
        "no-new-object": 0,
        // disallow use of unary operators, ++ and --
        "no-plusplus": 0,
        // disallow use of certain syntax in code
        "no-restricted-syntax": 0,
        // disallow the use of ternary operators
        "no-ternary": 0,
        // disallow trailing whitespace at the end of lines
        "no-trailing-spaces": 1,
        // disallow dangling underscores in identifiers
        "no-underscore-dangle": 0,
        // disallow the use of Boolean literals in conditional expressions
        "no-unneeded-ternary": 2,
        // disallow whitespace before properties
        "no-whitespace-before-property": 2,
        // enforce the location of single-line statements
        "nonblock-statement-body-position": 0,
        // enforce consistent line breaks inside braces
        "object-curly-newline": 0,
        // require or disallow padding inside curly braces
        "object-curly-spacing": 0, // NOTE - DO NOT TOUCH. Use rule in babel.js
        // enforce placing object properties on separate lines
        "object-property-newline": 0,
        // allow just one var statement per function
        "one-var": [2, "never"],
        // require assignment operator shorthand where possible or prohibit it entirely
        "operator-assignment": 0,
        // enforce operators to be placed before or after line breaks
        "operator-linebreak": 0,
        // enforce padding within blocks
        "padded-blocks": 0,
        // require or disallow padding lines between statements
        "padding-line-between-statements": 0,
        // require quotes around object literal property names
        "quote-props": 0,
        // specify whether double or single quotes should be used
        "quotes": [1, "double"],
        // Require JSDoc comment
        "require-jsdoc": 0,
        // enforce spacing before and after semicolons
        "semi-spacing": 2,
        // enforce location of semicolons
        "semi-style": 2,
        // require or disallow use of semicolons instead of ASI
        "semi": 2,
        // require object keys to be sorted
        "sort-keys": 0,
        // sort variables within the same declaration block
        "sort-vars": 0,
        // require or disallow space before blocks
        "space-before-blocks": 0,
        // require or disallow space before function opening parenthesis
        "space-before-function-paren": [1, {"anonymous": "always", "named": "never"}],
        // require or disallow spaces inside parentheses
        "space-in-parens": 0,
        // require spaces around operators
        "space-infix-ops": 1,
        // Require or disallow spaces before/after unary operators
        "space-unary-ops": 0,
        // require or disallow a space immediately following the // or /* in a comment
        "spaced-comment": [1, "always", {"exceptions": ["/"]}],
        // enforce spacing around colons of switch statements
        "switch-colon-spacing": 2,
        // require or disallow spacing between template tags and their literals
        "template-tag-spacing": 0,
        // require or disallow Unicode byte order mark (BOM)
        "unicode-bom": 0,
        // require regex literals to be wrapped in parentheses
        "wrap-regex": 0
    }
};
<|endoftext|>


<commit_before>
var query  = require( 'querystring' )
var http   = require( 'http' )
var https  = require( 'https' )
var crypto = require( 'crypto' )
var URL    = require( 'url' )

var OAuth = {
  util: require( './util' )
}

/**
 * Consumer constructor.
 * @param {Object} options
 */
function Consumer( options ) {

  if( !(this instanceof Consumer) ) {
    return new Consumer( options )
  }

  this.configure( options )

  this.Client = Consumer.Client( this )

}

/**
 * Consumer client (user).
 * @type {Function}
 */
Consumer.Client = require( './1.0-client' )

/**
 * Consumer default options.
 * @type {Object}
 */
Consumer.defaults = {
  base: '',
  key: '',
  secret: '',
  signature_method: 'HMAC-SHA1',
  headers: {
    'Accept': '*/*',
    'Connection': 'Close',
    'User-Agent': 'node.js/client-oauth'
  }
}

/**
 * Consumer prototype.
 * @type {Object}
 */
Consumer.prototype = {

  /**
   * OAuth protocol version.
   * @type {Number}
   */
  version: 1.0,

  /*
   * Performs a HTTP request against `url`
   * with given `method` and `data`. On completion or
   * error `callback` is called with `error`, `data` and `response`.
   *
   * @api public
   * @param {Object} client
   * @param {String} method
   * @param {String} url
   * @param {Object} data
   * @param {Function} callback
   */
  request: function( client, method, url, data, callback ) {

    method   = ( method + '' ).toUpperCase()
    url      = URL.parse( this.base + url )
    callback = callback || function() {}
    data     = query.stringify(
      this.prepareParams( client, method, url, data )
    )

    var body  = ''
    var layer = url.protocol === 'https:'
      ? https
      : http

    if( method !== 'POST' && method !== 'PUT' ) {
      url.path += '?' + data
    } else {
      body = data
    }

    url.method  = method
    url.headers = this.headers

    var request = layer.request( url, function( response ) {

      var buffer = ''
      var done = false

      response.setEncoding( 'utf8' )

      response.on( 'data', function( chunk ) {
        buffer += chunk
      })

      response.on( 'end', function() {
        done = true
        callback( null, buffer, response )
      })

      response.on( 'close', function() {
        if( !done ) { callback( error, buffer, response ) }
      })

    })

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

    request.end( body, 'utf8' )

  },

  /*
   * Prepares given `data` (Adds standard OAuth parameters,
   * sorts them and finally adds the signature).
   *
   * @api public
   * @param {Object} client
   * @param {String} method
   * @param {String|Object} url
   * @param {Object} data
   */
  prepareParams: function( client, method, url, data ) {

    data = data || Object.create( null )

    var defaults = {
      'oauth_timestamp':        OAuth.util.getTime(),
      'oauth_version':          this.version,
      'oauth_token':            client.key,
      'oauth_nonce':            OAuth.util.getNonce(),
      'oauth_signature_method': this.signature_method,
      'oauth_consumer_key':     this.key
    }

    for( var i in defaults ) {
      if( defaults.hasOwnProperty(i) ) {
        data[i] = defaults[i]
      }
    }

    var keys = Object.keys( data ).sort()
    var key, params = {}

    for( var k in keys ) {
      key = keys[k]
      params[ key ] = data[ key ]
    }

    params['oauth_signature'] = this.sign( client, method, url, params )

    return params

  },

  /*
   * Creates the OAuth signature from
   * `method`, `url` and `data`.
   *
   * @api public
   * @param {Object}        client
   * @param {String}        method
   * @param {String|Object} url
   * @param {Object}        data
   */
  sign: function( client, method, url, data ) {

    url = URL.parse( url )
    url = url.protocol + '//'
        + url.host
        + url.path
    url = OAuth.util.encodeComponent( url )

    // Remove `oauth_signature` if present
    // ref: spec: 9.1.1 ("the oauth_signature parameter MUST be excluded.")
    if( data.oauth_signature ) {
      delete data.oauth_signature
    }

    data = query.stringify( data )
    data = OAuth.util.encodeComponent( data )

    var base = [ method, url, data ].join( '&' )
    var key  = [ this.secret, client.secret ].join( '&' )
    var hash = ''

    switch( this.signature_method ) {
      case 'HMAC-SHA1':
        hash = crypto.createHmac( 'sha1', key )
                     .update( base )
                     .digest( 'base64' )
        break;
      case 'PLAINTEXT':
        hash = OAuth.util.encodeComponent( key )
        break;
      default:
        throw new Error( 'Signature method not implemented.' )
        break;
    }

    return hash

  },

  /**
   * Configures consumer instance with given `options`.
   * @param  {Object} options
   * @return {Undefined}
   */
  configure: function( options ) {

    var defaults = this.options || Consumer.defaults

    for( var i in defaults ) {
      if( defaults.hasOwnProperty( i ) ) {
        this[i] = options[i] || defaults[i]
      }
    }

    this.signature_method = this.signature_method.toUpperCase()

  }

}

module.exports = Consumer
<commit_msg>Minor fix in `api/1.0`<commit_after>
var query  = require( 'querystring' )
var http   = require( 'http' )
var https  = require( 'https' )
var crypto = require( 'crypto' )
var URL    = require( 'url' )

var OAuth = {
  util: require( './util' )
}

/**
 * Consumer constructor.
 * @param {Object} options
 */
function Consumer( options ) {

  if( !(this instanceof Consumer) ) {
    return new Consumer( options )
  }

  this.configure( options )

  this.Client = Consumer.Client( this )

}

/**
 * Consumer client (user).
 * @type {Function}
 */
Consumer.Client = require( './1.0-client' )

/**
 * Consumer default options.
 * @type {Object}
 */
Consumer.defaults = {
  base: '',
  key: '',
  secret: '',
  signature_method: 'HMAC-SHA1',
  headers: {
    'Accept': '*/*',
    'Connection': 'Close',
    'User-Agent': 'node.js/client-oauth'
  }
}

/**
 * Consumer prototype.
 * @type {Object}
 */
Consumer.prototype = {

  /**
   * OAuth protocol version.
   * @type {Number}
   */
  version: 1.0,

  /*
   * Performs a HTTP request against `url`
   * with given `method` and `data`. On completion or
   * error `callback` is called with `error`, `data` and `response`.
   *
   * @api public
   * @param {Object} client
   * @param {String} method
   * @param {String} url
   * @param {Object} data
   * @param {Function} callback
   */
  request: function( client, method, url, data, callback ) {

    method   = ( method + '' ).toUpperCase()
    url      = URL.parse( this.base + url )
    callback = callback || function() {}
    data     = query.stringify(
      this.prepareParams( client, method, url, data )
    )

    var body  = ''
    var layer = url.protocol === 'https:'
      ? https
      : http

    if( method !== 'POST' && method !== 'PUT' ) {
      url.path += '?' + data
    } else {
      body = data
    }

    url.method  = method
    url.headers = this.headers

    var request = layer.request( url, function( response ) {

      var buffer = ''
      var done = false

      response.setEncoding( 'utf8' )

      response.on( 'data', function( chunk ) {
        buffer += chunk
      })

      response.on( 'end', function() {
        done = true
        callback( null, buffer, response )
      })

      response.on( 'close', function() {
        if( !done ) { callback( error, buffer, response ) }
      })

    })

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

    request.end( body, 'utf8' )

  },

  /*
   * Prepares given `data` (Adds standard OAuth parameters,
   * sorts them and finally adds the signature).
   *
   * @api public
   * @param {Object} client
   * @param {String} method
   * @param {String|Object} url
   * @param {Object} data
   */
  prepareParams: function( client, method, url, data ) {

    data = data || Object.create( null )

    var defaults = {
      'oauth_timestamp':        OAuth.util.getTime(),
      'oauth_version':          this.version,
      'oauth_token':            client.key,
      'oauth_nonce':            OAuth.util.getNonce(),
      'oauth_signature_method': this.signature_method,
      'oauth_consumer_key':     this.key
    }

    for( var i in defaults ) {
      if( defaults.hasOwnProperty(i) ) {
        data[i] = defaults[i]
      }
    }

    var keys = Object.keys( data ).sort()
    var key, params = {}

    for( var k in keys ) {
      key = keys[k]
      params[ key ] = data[ key ]
    }

    params['oauth_signature'] = this.sign( client, method, url, params )

    return params

  },

  /*
   * Creates the OAuth signature from
   * `method`, `url` and `data`.
   *
   * @api public
   * @param {Object}        client
   * @param {String}        method
   * @param {String|Object} url
   * @param {Object}        data
   */
  sign: function( client, method, url, data ) {

    url = URL.parse( url )
    url = url.protocol + '//'
        + url.host
        + url.path
    url = OAuth.util.encodeComponent( url )

    // Remove `oauth_signature` if present
    // ref: spec: 9.1.1 ("the oauth_signature parameter MUST be excluded.")
    if( data.oauth_signature ) {
      delete data.oauth_signature
    }

    data = query.stringify( data )
    data = OAuth.util.encodeComponent( data )

    var base = [ method, url, data ].join( '&' )
    var key  = [ this.secret, client.secret ].join( '&' )
    var hash = ''

    switch( this.signature_method ) {
      case 'HMAC-SHA1':
        hash = crypto.createHmac( 'sha1', key )
                     .update( base )
                     .digest( 'base64' )
        break;
      case 'PLAINTEXT':
        hash = OAuth.util.encodeComponent( key )
        break;
      default:
        throw new Error( 'Signature method not implemented.' )
        break;
    }

    return hash

  },

  /**
   * Configures consumer instance with given `options`.
   * @param  {Object} options
   * @return {Undefined}
   */
  configure: function( options ) {

    var defaults = Consumer.defaults

    for( var i in defaults ) {
      if( defaults.hasOwnProperty( i ) ) {
        this[i] = options[i] || defaults[i]
      }
    }

    this.signature_method = this.signature_method.toUpperCase()

  }

}

module.exports = Consumer
<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (

Hello, world.

    );
  }
}<commit_msg>changed message<commit_after>import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (

Hello, worl.

    );
  }
}<|endoftext|>


<commit_before>var express = require('express'),
  mongoose = require('mongoose'),
  bodyParser = require('body-parser'),
  app = express(),
  fs = require('fs');

var config = {
  'database' : 'mongodb://127.0.0.1/agenda_colaborativa',
};

var router = express.Router();

// Conexão com o mongoDB.
mongoose.connect(config.database, function(err) {
  console.log('Erro no mongoDB');
});
app.use(bodyParser());
// Require all routes.
fs.readdirSync('./controllers').forEach(function(file) {
  if(file.substr(-3) == '.js') {
    route = require('./controllers/' + file);
    route.controller(app);
  }
});

app.set('port', process.env.PORT || 8080);

app.use('/', router);

app.listen(app.get('port'), function() {
  console.log('Servidor rodando na porta 8080');
});

<commit_msg>Corrigindo problema no log da conexao com o banco de dados<commit_after>var express = require('express'),
  mongoose = require('mongoose'),
  bodyParser = require('body-parser'),
  app = express(),
  fs = require('fs');

var config = {
  'database' : 'mongodb://localhost/agenda_colaborativa',
};

var router = express.Router();

// Conexão com o mongoDB.
mongoose.connect(config.database, function(err) {
  if (err) {
    console.log('Erro no mongoDB');
  }
});

app.use(bodyParser());
// Require all routes.
fs.readdirSync('./controllers').forEach(function(file) {
  if(file.substr(-3) == '.js') {
    route = require('./controllers/' + file);
    route.controller(app);
  }
});

app.set('port', process.env.PORT || 8080);

app.use('/', router);

app.listen(app.get('port'), function() {
  console.log('Servidor rodando na porta 8080');
});

<|endoftext|>


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

var express = require('express');
var http = require('http')
var path = require('path');
var socketio = require('socket.io');
var fs = require('fs');
var utils = require('./utils');

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('123456789987654321'));
	app.use(express.session());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

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

// Socket IO
var io = socketio.listen(webserver);

app.get('/', function (req, res){
	res.render('index', { title: 'SELVIE Video uploader' });
});

app.post('/xhrupload', function (req, res){
	if(!req.xhr) return utils.sendError(new Error('got no xhr request'), res);

	var size = req.header('x-file-size');
	var type = req.header('x-file-type');
	var name = path.basename(req.header('x-file-name'));

	// fix filename:
	name = utils.removeFileExt(name).replace(/([^a-z0-9]+)/gi, '-') + path.extname(name);
	name = Date.now() + '_' + name;
	var uploadedFile = path.join('public/data', name);

	var writeStream = fs.createWriteStream( uploadedFile );

	req.on('data', function (data) {
		writeStream.write(data);
	});

	req.on('end', function () {
		writeStream.end();
		console.log("XHR Upload done:", uploadedFile);

		fs.readdir('public/data', function (err, files) {
			res.send({err: 0, numberofuploadedfiles: files.length});
		});

	});
});

<commit_msg>fixed path<commit_after>#!/usr/bin/env node

var express = require('express');
var http = require('http')
var path = require('path');
var socketio = require('socket.io');
var fs = require('fs');
var utils = require('./utils');

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser('123456789987654321'));
	app.use(express.session());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

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

// Socket IO
var io = socketio.listen(webserver);

app.get('/', function (req, res){
	res.render('index', { title: 'SELVIE Video uploader' });
});

app.post('/xhrupload', function (req, res){
	if(!req.xhr) return utils.sendError(new Error('got no xhr request'), res);

	var size = req.header('x-file-size');
	var type = req.header('x-file-type');
	var name = path.basename(req.header('x-file-name'));

	// fix filename:
	name = utils.removeFileExt(name).replace(/([^a-z0-9]+)/gi, '-') + path.extname(name);
	name = Date.now() + '_' + name;
	var uploadedFile = path.join(__dirname, 'public/data', name);

	var writeStream = fs.createWriteStream( uploadedFile );

	req.on('data', function (data) {
		writeStream.write(data);
	});

	req.on('end', function () {
		writeStream.end();
		console.log("XHR Upload done:", uploadedFile);

		fs.readdir( path.join(__dirname, 'public/data') , function (err, files) {
			res.send({err: 0, numberofuploadedfiles: files.length});
		});

	});
});

<|endoftext|>


<commit_before>/**
 * Poster v0.1.0
 * A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 01 June, 2016
 * License: MIT
 *
 * React App Entry-point
 */

/*
 * Library
 */
import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";

/*
 * Page Components
 */
import Home             from "./components/Views/Home";
import SearchResults    from "./components/Views/Section/SearchResults";
import TopRated         from "./components/Views/Section/TopRated/TopRated";
import Upcoming         from "./components/Views/Section/Upcoming/Upcoming";
import Watchlist        from "./components/Views/Section/Watchlist/Watchlist";
import MovieDetail      from "./components/Views/Section/Shared/MovieDetail";

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Home}>
            <Route path="search" component={SearchResults}></Route>
            <Route path="top_rated" component={TopRated}></Route>
            <Route path="upcoming" component={Upcoming}></Route>
            <Route path="watchlist" component={Watchlist}></Route>
            <Route path="movie/:movieId" component={MovieDetail}></Route>
        </Route>
    </Router>,
    document.getElementById('poster-app')
);
<commit_msg>Updated path for MovieDetail component.<commit_after>/**
 * Poster v0.1.0
 * A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 01 June, 2016
 * License: MIT
 *
 * React App Entry-point
 */

/*
 * Library
 */
import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";

/*
 * Page Components
 */
import Home             from "./components/Views/Home";
import SearchResults    from "./components/Views/Section/SearchResults";
import TopRated         from "./components/Views/Section/TopRated/TopRated";
import Upcoming         from "./components/Views/Section/Upcoming/Upcoming";
import Watchlist        from "./components/Views/Section/Watchlist/Watchlist";
import MovieDetail      from "./components/Views/Section/MovieDetail/MovieDetail";

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Home}>
            <Route path="search" component={SearchResults}></Route>
            <Route path="top_rated" component={TopRated}></Route>
            <Route path="upcoming" component={Upcoming}></Route>
            <Route path="watchlist" component={Watchlist}></Route>
            <Route path="movie/:movieId" component={MovieDetail}></Route>
        </Route>
    </Router>,
    document.getElementById('poster-app')
);
<|endoftext|>


<commit_before>define(['jquery', 'backbone', 'underscore', 'core/views/MapBrowseLayout'], function($, Backbone, _, MapBrowseLayout) {
    var app = {

        navigate: _.wrap(Backbone.history.navigate, function(nav, path, options) {
            nav.apply(Backbone.history, [path, options]);
        }),
        currentLayout: null,

        layouts: {'MapBrowseLayout': MapBrowseLayout},

        showView: function(view) {
            return this.renderView(view);
        },

        renderView: function(view, options) {
            options = options || {};
            if (options.menu) {
                $('#back').hide();
                $('#home').show();
            } else {
                $('#home').hide();
                $('#back').show();
            }
            // Remove any existing layouts
            // If managed with LayoutManager this will call cleanup
            if (this.currentLayout) {
                this.currentLayout.remove();
            }
            // Attach a view to the DOM and call render
            this.currentLayout = view;
            $('#content').empty().append(this.currentLayout.el);
            this.currentLayout.render();
        },

        getLayout: function(name) {
            if (this.currentLayout && this.currentLayout.name === name) {
                return this.currentLayout;
            } else {
                if (this.layouts[name]) {
                    var RequestedLayout = this.layouts[name];
                    layout = new RequestedLayout();
                    this.renderView(layout);
                    return layout;
                } else {
                    throw "Layout doesn't exist";
                }
            }
        }
    };

    return app;
});
<commit_msg>Comment on app.layouts<commit_after>define(['jquery', 'backbone', 'underscore', 'core/views/MapBrowseLayout'], function($, Backbone, _, MapBrowseLayout) {
    var app = {

        navigate: _.wrap(Backbone.history.navigate, function(nav, path, options) {
            nav.apply(Backbone.history, [path, options]);
        }),
        currentLayout: null,

        // These are full-container layouts
        // Specifically we're using it so we don't remove the Map when
        // the layout is updated, to reduce processing/requests
        //
        // Most layouts don't need to be included here unless similar
        // benefits (such as keeping the Map in the DOM) can be found.
        layouts: {'MapBrowseLayout': MapBrowseLayout},

        showView: function(view) {
            return this.renderView(view);
        },

        renderView: function(view, options) {
            options = options || {};
            if (options.menu) {
                $('#back').hide();
                $('#home').show();
            } else {
                $('#home').hide();
                $('#back').show();
            }
            // Remove any existing layouts
            // If managed with LayoutManager this will call cleanup
            if (this.currentLayout) {
                this.currentLayout.remove();
            }
            // Attach a view to the DOM and call render
            this.currentLayout = view;
            $('#content').empty().append(this.currentLayout.el);
            this.currentLayout.render();
        },

        getLayout: function(name) {
            if (this.currentLayout && this.currentLayout.name === name) {
                return this.currentLayout;
            } else {
                if (this.layouts[name]) {
                    var RequestedLayout = this.layouts[name];
                    layout = new RequestedLayout();
                    this.renderView(layout);
                    return layout;
                } else {
                    throw "Layout doesn't exist";
                }
            }
        }
    };

    return app;
});
<|endoftext|>


<commit_before>// Set up dependencies
const express = require('express');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const moment = require('moment');
moment().format();

// App configuration
const path = require('path');
const dir = path.resolve(__dirname, '..');
let app = express();
app.set('view engine', 'pug');
app.use(favicon(dir + '/public/favicon.ico'));
app.use('/public', express.static(dir + '/public/'));
app.use('/semantic', express.static(dir + '/node_modules/semantic-ui-css/'));
app.use('/jquery', express.static(dir + '/node_modules/jquery/dist/'));
app.use('/moment', express.static(dir + '/node_modules/moment/min/'));
app.use('/assets', express.static(dir + '/assets/'));
app.use(function(req, res, next) {
    let pathStr = req.path;
    if (req.path.length != 1 && req.path.substr(-1) == '/') {
        pathStr = req.path.substring(0, req.path.length - 1);
    }
    res.locals = { path: pathStr };
    next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

// Database setup
let db = require(dir + '/config/db');
db.initialize(app);

// App locals
app.locals.title = 'Protect Yourself';
app.locals.moment = moment;
app.locals.navigation = [{
    title: 'Home',
    url: '/'
}];
/* }, {
    title: 'Checkup',
    url: '/checkup'
}, {
    title: 'Submit',
    url: '/submit'
}, {
    title: 'Browse',
    url: '/browse/all'
}, {
    title: 'Random',
    url: '/random'
}];*/

// Routes
require(dir + '/routes/general')(app);
require(dir + '/routes/survey')(app);

const port = 3000;
app.listen(port, function() {
    console.log(`Running on localhost:${port}`);
});
<commit_msg>Add local function to convert a string to proper case<commit_after>// Set up dependencies
const express = require('express');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const moment = require('moment');
moment().format();

// App configuration
const path = require('path');
const dir = path.resolve(__dirname, '..');
let app = express();
app.set('view engine', 'pug');
app.use(favicon(dir + '/public/favicon.ico'));
app.use('/public', express.static(dir + '/public/'));
app.use('/semantic', express.static(dir + '/node_modules/semantic-ui-css/'));
app.use('/jquery', express.static(dir + '/node_modules/jquery/dist/'));
app.use('/moment', express.static(dir + '/node_modules/moment/min/'));
app.use('/assets', express.static(dir + '/assets/'));
app.use(function(req, res, next) {
    let pathStr = req.path;
    if (req.path.length != 1 && req.path.substr(-1) == '/') {
        pathStr = req.path.substring(0, req.path.length - 1);
    }
    res.locals = { path: pathStr };
    next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

// Database setup
let db = require(dir + '/config/db');
db.initialize(app);

// App locals
app.locals.title = 'Protect Yourself';
app.locals.moment = moment;
app.locals.properCase = str => str.charAt(0).toUpperCase() + str.substring(1);
app.locals.navigation = [{
    title: 'Home',
    url: '/'
}];
/* }, {
    title: 'Checkup',
    url: '/checkup'
}, {
    title: 'Submit',
    url: '/submit'
}, {
    title: 'Browse',
    url: '/browse/all'
}, {
    title: 'Random',
    url: '/random'
}];*/

// Routes
require(dir + '/routes/general')(app);
require(dir + '/routes/survey')(app);

const port = 3000;
app.listen(port, function() {
    console.log(`Running on localhost:${port}`);
});
<|endoftext|>


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

var app = express();

app.set('port', (process.env.PORT || 3000));
app.get('/',function(req,res){
	res.send("Hello for codeship!?");
});

module.exports = app;<commit_msg>chaged homepage text to check deployment to heroku via codeship<commit_after>var express = require('express');

var app = express();

app.set('port', (process.env.PORT || 3000));
app.get('/',function(req,res){
	res.send("Hello for codeship I canny believe this!?");
});

module.exports = app;<|endoftext|>


<commit_before>var http = require('http');
var path = require('path');

var express = require('express');
var redis = require('redis');
var Q = require('q');

var config = require('./config/config');
var SteamApi = require('./steam_api');
var redisClient = redis.createClient(config.REDIS.PORT, config.REDIS.HOST, config.REDIS.OPTIONS);

var steamApi = new SteamApi(redisClient);
var app = module.exports = express();

// Serve public site as static files
app.use('/', express.static(path.join(__dirname, '../public')));

// Api methods
app.get('/api/:interfaceName/:methodName/:versionNumber', function (req, res, next) {
    var interfaceName = req.params['interfaceName'];
    var methodName = req.params['methodName'];
    var versionNumber = req.params['versionNumber'];
    var queryParams = req.query;

    steamApi.doApiCall(interfaceName, methodName, versionNumber, queryParams)
        .done(function (result) {
            res.send(result);
        }, function (err) {
            if(err instanceof Error) {
                next(err)
            } else {
                next(new Error(err));
            }
        });
});

// This route deals enables HTML5Mode by forwarding missing files to the index.html
app.all('/*', function(req, res) {
    res.sendfile(path.join(__dirname, '../public/index.html'));
});

/// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handler
app.use(function (err, req, res, next) {
    if(!err.status || err.status >= 500) {
        // An error on our end, log the stack
        console.error(err.stack);
    }
    res.status(err.status || 500);
    res.send({
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3000);

// Validate steam key and fetch the api methods
(function () {
    steamApi.setApiKey(config.STEAM_API_KEY)
        .then(steamApi.loadApiMethods)
        .then(function () {
            var runningDefer = Q.defer();
            var server = app.listen(app.get('port'), function () {
                console.log("Server running on port " + server.address().port + "...");
            }).on('error', function(err){
                server.close();
                runningDefer.reject(err);
            });
            return runningDefer.promise;
        })
        .fail(function (err) {
            if(err) {
                console.error(err.stack);
            }
        })
        .done();
})();<commit_msg>Enabled gzip caching for express.<commit_after>var http = require('http');
var path = require('path');

var express = require('express');
var redis = require('redis');
var Q = require('q');
var compression = require('compression')

var config = require('./config/config');
var SteamApi = require('./steam_api');
var redisClient = redis.createClient(config.REDIS.PORT, config.REDIS.HOST, config.REDIS.OPTIONS);

var steamApi = new SteamApi(redisClient);
var app = module.exports = express();

// Miliseconds in a day. Used to cache the static content
var oneDay = 86400000;

// use gzip
app.use(compression());

// Serve public site as static files
app.use('/', express.static(path.join(__dirname, '../public'), {maxAge: oneDay}));

// Api methods
app.get('/api/:interfaceName/:methodName/:versionNumber', function (req, res, next) {
    var interfaceName = req.params['interfaceName'];
    var methodName = req.params['methodName'];
    var versionNumber = req.params['versionNumber'];
    var queryParams = req.query;

    steamApi.doApiCall(interfaceName, methodName, versionNumber, queryParams)
        .done(function (result) {
            res.send(result);
        }, function (err) {
            if(err instanceof Error) {
                next(err)
            } else {
                next(new Error(err));
            }
        });
});

// This route deals enables HTML5Mode by forwarding missing files to the index.html
app.all('/*', function(req, res) {
    res.sendfile(path.join(__dirname, '../public/index.html'));
});

/// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handler
app.use(function (err, req, res, next) {
    if(!err.status || err.status >= 500) {
        // An error on our end, log the stack
        console.error(err.stack);
    }
    res.status(err.status || 500);
    res.send({
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3000);

// Validate steam key and fetch the api methods
(function () {
    steamApi.setApiKey(config.STEAM_API_KEY)
        .then(steamApi.loadApiMethods)
        .then(function () {
            var runningDefer = Q.defer();
            var server = app.listen(app.get('port'), function () {
                console.log("Server running on port " + server.address().port + "...");
            }).on('error', function(err){
                server.close();
                runningDefer.reject(err);
            });
            return runningDefer.promise;
        })
        .fail(function (err) {
            if(err) {
                console.error(err.stack);
            }
        })
        .done();
})();<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express')
	, http = require('http')
	, path = require('path')
	, webshot = require('./webshot')
	, fs = require('fs');

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	//app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

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

app.get('/', function(req, res){
	res.render('index', { name: req.query.name });
	logPerson(req.query.name, req.headers['user-agent'], 'main');
});

app.get('/youtube', function(req, res){
	res.render('youtube', { name: req.query.name });
	logPerson(req.query.name, req.headers['user-agent'], 'youtube');
});

app.get('/getgooglescreenshot', function(req, res){
	createWebshot(req.query.name, function (err, filename){
		if(err){
			res.json({err: err});
			console.log(err);
		}else{
			res.json({err: null, screenshot: filename});
		}
	});
});

function logPerson(name, useragent, page){
	var data = {
		time: (new Date()).getTime(),
		name: name,
		page: page,
		useragent: useragent
	};

	fs.appendFile('log.txt', JSON.stringify(data) + "\n", function (err) {
	});
}

function createWebshot(name, callback){
	var options = {
		screenSize: {
			width: 960,
			height: 2000
		},
		shotSize: {
			width: 'window',
			height: 2000
		},
		//userAgent: 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g'
		userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:18.0) Gecko/20100101 Firefox/18.0'
	}

	var filename =  __dirname + '/public/googleshots/'+ cleanName(name) +'.png';
	var onlineFilename = '/googleshots/'+ cleanName(name) +'.png';

	webshot('https://www.google.be/search?q=' + escape(name), filename, options, function(err) {
		callback(err, onlineFilename);
	});
}

// kuist de naam op zodat het filename-waardig is
function cleanName(str)
{
	var s=str.toLowerCase().replace(/\s/g, '_');

	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

	var repChar=['A','a','E','e','I','i','O','o','U','u'];

	for(var i=0; i<rExps.length; i++)
		s=s.replace(rExps[i],repChar[i]);

	return s;
}
<commit_msg>added shebang<commit_after>#!/usr/bin/env node
/**
 * Module dependencies.
 */

var express = require('express')
	, http = require('http')
	, path = require('path')
	, webshot = require('./webshot')
	, fs = require('fs');

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	//app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

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

app.get('/', function(req, res){
	res.render('index', { name: req.query.name });
	logPerson(req.query.name, req.headers['user-agent'], 'main');
});

app.get('/youtube', function(req, res){
	res.render('youtube', { name: req.query.name });
	logPerson(req.query.name, req.headers['user-agent'], 'youtube');
});

app.get('/getgooglescreenshot', function(req, res){
	createWebshot(req.query.name, function (err, filename){
		if(err){
			res.json({err: err});
			console.log(err);
		}else{
			res.json({err: null, screenshot: filename});
		}
	});
});

function logPerson(name, useragent, page){
	var data = {
		time: (new Date()).getTime(),
		name: name,
		page: page,
		useragent: useragent
	};

	fs.appendFile('log.txt', JSON.stringify(data) + "\n", function (err) {
	});
}

function createWebshot(name, callback){
	var options = {
		screenSize: {
			width: 960,
			height: 2000
		},
		shotSize: {
			width: 'window',
			height: 2000
		},
		//userAgent: 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g'
		userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:18.0) Gecko/20100101 Firefox/18.0'
	}

	var filename =  __dirname + '/public/googleshots/'+ cleanName(name) +'.png';
	var onlineFilename = '/googleshots/'+ cleanName(name) +'.png';

	webshot('https://www.google.be/search?q=' + escape(name), filename, options, function(err) {
		callback(err, onlineFilename);
	});
}

// kuist de naam op zodat het filename-waardig is
function cleanName(str)
{
	var s=str.toLowerCase().replace(/\s/g, '_');

	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

	var repChar=['A','a','E','e','I','i','O','o','U','u'];

	for(var i=0; i<rExps.length; i++)
		s=s.replace(rExps[i],repChar[i]);

	return s;
}
<|endoftext|>


<commit_before>/**
 * Modules Dependencies
 */
var express        = require('express');
var app	     	   = express();
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var path  		   = require('path');
var cookieParser   = require('cookie-parser');
var session 	   = require('express-session');
var RedisStore 	   = require('connect-redis')(session);
var passport 	   = require('passport');
var logger 	       = require('morgan');
var errorHandler   = require('errorhandler');

/**
 * Routes
 */
var indexRoute = require('./routes/indexRoute');
var configPassport = require('./config/passport');

/**
 * Middlewares
 */
// config Port
app.set('port', process.env.PORT || 3000);

// the directory where the template files are located.
app.set('views', './views');

// the template engine to use.
app.set('view engine', 'jade');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
    store: new RedisStore(),
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: false
}));

// use passport middleware
app.use(passport.initialize());
app.use(passport.session());

indexRoute(app, passport);
configPassport(passport);

app.use(express.static(path.join( __dirname, 'public' )));
app.use(logger('dev'));

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

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

<commit_msg>update app.js<commit_after>/**
 * Modules Dependencies
 */
var express        = require('express'),
	app	     	   = express(),
	bodyParser     = require('body-parser'),
	methodOverride = require('method-override'),
	path  		   = require('path'),
	cookieParser   = require('cookie-parser'),
	session 	   = require('express-session'),
	RedisStore 	   = require('connect-redis')(session),
	passport 	   = require('passport'),
	logger 	       = require('morgan'),
	errorHandler   = require('errorhandler'),
	flash          = require('connect-flash');

/**
 * Routes
 */
var indexRoute 	   = require('./routes/indexRoute'),
    configPassport = require('./config/passport');

/**
 * Middlewares
 */
// config Port
app.set('port', process.env.PORT || 3000);

// the directory where the template files are located.
app.set('views', './views');

// the template engine to use.
app.set('view engine', 'jade');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
    store: new RedisStore(),
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: false
}));

// use passport middleware
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

indexRoute(app, passport);
configPassport(passport);

app.use(express.static(path.join( __dirname, 'public' )));
app.use(logger('dev'));

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

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

<|endoftext|>


<commit_before>if(location.hostname!="www.lhu.edu.tw"){
    alert("請勿於非龍華學生系統的網頁上開啟此程式。");
}
if(!window.jQuery){
    var f=document.createElement('script');
    f.setAttribute('type','text/javascript');
    f.setAttribute('src','https://hans00.github.io/lhu_labor/jquery.min.js');
    document.getElementsByTagName('head')[0].appendChild(f);
    var f=document.createElement('script');
    f.setAttribute('type','text/javascript');
    f.setAttribute('src','https://hans00.github.io/lhu_labor/md5.min.js');
    document.getElementsByTagName('head')[0].appendChild(f);
}
if(!$(document).has("#labor_panel")){
    $.get('https://hans00.github.io/lhu_labor/panel.html',
    function (data) {
        //$("html").remove();
        $(document).html(data);
        $("#display h1").html("已就緒");
        $("#l,#p").change(function(){
            Interval($("#l").val()*1000, $("#p").val()*1000);
        });
    });
} else {
    $(document).ready(function(){
        $("#display h1").html("已就緒");
        $("#l,#p").change(function(){
            Interval($("#l").val()*1000, $("#p").val()*1000);
        });
    });
}
var iList=1000, iProc=800, en=false;
var BaseUrl="https://www.lhu.edu.tw/StudAp/C00/C4001/Apply/", logData={}, proc=false, loading=false;
function log(text){
	$("#log").text($("#log").text()+text+"\n");
	if($("#log").length){$("#log").scrollTop($("#log")[0].scrollHeight - $("#log").height());}
}
function a(item, name){
	if($("#a>#"+item).length==0){
		$("#a").append("
"+name+"
");
	}
	if($("#b>#"+item).length!=0){
		$("#b>#"+item).remove();
	}
}
function b(item, name){
	if($("#b>#"+item).length==0){
		$("#b").append("
"+name+"
");
	}
	if($("#a>#"+item).length!=0){
		$("#a>#"+item).remove();
	}
}
function get(ID, post,url){
    post = (typeof post === 'undefined') ? false : post;
    url = (typeof url === 'undefined') ? null : url;
    if(ID=="list"){
        $.ajax({
            url: BaseUrl+"Labor_Apply.aspx",
            cache: false
        })
        .done(function(data){
            if(data.search("登入")!=-1){
                $("#display h1").html("尚未登入學生資訊系統 ˋ_ˊ");
                _switch();
                return;
            }
            var table=$(data).find("#DG_Content");
            if(table.children("tr").length>=1){
                table.children("tr").each(function(){
                    var _url=BaseUrl+$(e).find("td:first-child a").prop("href"), _name=$(e).find("td:nth-child(2) font").text(), _id=md5(_name);
                    if(_name.search("限")!=-1) return;
                    if(_id in logData){
                        logData[_id]={url:_url,name:_name,stat:0};
                    }
                });
            } else {
                $("#display h1").html("暫無勞作，請稍後 030");
            }
            loading=false;
        })
        .fail(function(jqXHR, textStatus, errorThrown){
            log("取得清單失敗："+textStatus);
        });
    }else{
        if(post==false){
            var m="GET",d="";
        }else{
            var m="POST",d=post;
        }
        $.ajax({
            url: ((url!=null)?BaseUrl+logData[ID].url:url),
            method: m,
            data: d,
            cache: false
        })
        .done(function(data){
            var btn=$(data).find("#Btn_Join"), val=logData[ID];
            switch(btn.val()){
                case "取消參加此活動":
                    logData[ID].stat=1;
                    a(ID, val.name);
                    log("勞作「"+val.name+"」已報名完成。");
                    return;
                case "活動人數額滿":
                    logData[e].stat=0;
                    b(ID, val.name);
                    log("勞作「"+val.name+"」人數已額滿，重試中。");
                    return;
                default:
                    var data={__VIEWSTATE:$(data).find("[name='__VIEWSTATE']").val(),Btn_Join:$(data).find("#Btn_Join").val()},url=BaseUrl+$(data).find("#Labor_Apply_D").prop("action");
                    get(ID,data,url);
                    log("勞作「"+val.name+"」可以報名，嘗試中。");

            }
        })
        .fail(function(jqXHR, textStatus, errorThrown){
            log("取得活動狀態失敗："+textStatus);
        });
    }
}
function process(){
	if(!en){proc=false;return;}
	$.each(logData,function(e,val){
		if(val.stat==1) return;
        if(logData[e].stat==0){
            logData[e].stat=2;
            get(e);
        }
	});
	setTimeout("process();",iProc);
}
function getlist(){
	if(!en) return;
	if(!loading){
        get("list");
        loading=true;
    }
	if(!proc && logData.length>0){
		proc=true;
		$("#display h1").html("有勞作開放，正在爭取中 :3");
		process();
	}
	setTimeout("getlist();",iList);
}
function Interval(l,p){
	iList=l;
	iProc=p;
}
function _switch(e){
	en=!en;
    if(en){getlist();}
	var val=(en)?"結束":"啟動";
	$(e).text(val);
}<commit_msg>fix jquery not found<commit_after>if(location.hostname!="www.lhu.edu.tw"){
    alert("請勿於非龍華學生系統的網頁上開啟此程式。");
}
if(!window.jQuery){
    var f=document.createElement('script');
    f.setAttribute('type','text/javascript');
    f.setAttribute('src','https://hans00.github.io/lhu_labor/jquery.min.js');
    document.getElementsByTagName('head')[0].appendChild(f);
    var f=document.createElement('script');
    f.setAttribute('type','text/javascript');
    f.setAttribute('src','https://hans00.github.io/lhu_labor/md5.min.js');
    document.getElementsByTagName('head')[0].appendChild(f);
}
if(!jQuery(document).has("#labor_panel")){
    $.get('https://hans00.github.io/lhu_labor/panel.html',
    function (data) {
        //$("html").remove();
        $(document).html(data);
        $("#display h1").html("已就緒");
        $("#l,#p").change(function(){
            Interval($("#l").val()*1000, $("#p").val()*1000);
        });
    });
} else {
    $(document).ready(function(){
        $("#display h1").html("已就緒");
        $("#l,#p").change(function(){
            Interval($("#l").val()*1000, $("#p").val()*1000);
        });
    });
}
var iList=1000, iProc=800, en=false;
var BaseUrl="https://www.lhu.edu.tw/StudAp/C00/C4001/Apply/", logData={}, proc=false, loading=false;
function log(text){
	$("#log").text($("#log").text()+text+"\n");
	if($("#log").length){$("#log").scrollTop($("#log")[0].scrollHeight - $("#log").height());}
}
function a(item, name){
	if($("#a>#"+item).length==0){
		$("#a").append("
"+name+"
");
	}
	if($("#b>#"+item).length!=0){
		$("#b>#"+item).remove();
	}
}
function b(item, name){
	if($("#b>#"+item).length==0){
		$("#b").append("
"+name+"
");
	}
	if($("#a>#"+item).length!=0){
		$("#a>#"+item).remove();
	}
}
function get(ID, post,url){
    post = (typeof post === 'undefined') ? false : post;
    url = (typeof url === 'undefined') ? null : url;
    if(ID=="list"){
        $.ajax({
            url: BaseUrl+"Labor_Apply.aspx",
            cache: false
        })
        .done(function(data){
            if(data.search("登入")!=-1){
                $("#display h1").html("尚未登入學生資訊系統 ˋ_ˊ");
                _switch();
                return;
            }
            var table=$(data).find("#DG_Content");
            if(table.children("tr").length>=1){
                table.children("tr").each(function(){
                    var _url=BaseUrl+$(e).find("td:first-child a").prop("href"), _name=$(e).find("td:nth-child(2) font").text(), _id=md5(_name);
                    if(_name.search("限")!=-1) return;
                    if(_id in logData){
                        logData[_id]={url:_url,name:_name,stat:0};
                    }
                });
            } else {
                $("#display h1").html("暫無勞作，請稍後 030");
            }
            loading=false;
        })
        .fail(function(jqXHR, textStatus, errorThrown){
            log("取得清單失敗："+textStatus);
        });
    }else{
        if(post==false){
            var m="GET",d="";
        }else{
            var m="POST",d=post;
        }
        $.ajax({
            url: ((url!=null)?BaseUrl+logData[ID].url:url),
            method: m,
            data: d,
            cache: false
        })
        .done(function(data){
            var btn=$(data).find("#Btn_Join"), val=logData[ID];
            switch(btn.val()){
                case "取消參加此活動":
                    logData[ID].stat=1;
                    a(ID, val.name);
                    log("勞作「"+val.name+"」已報名完成。");
                    return;
                case "活動人數額滿":
                    logData[e].stat=0;
                    b(ID, val.name);
                    log("勞作「"+val.name+"」人數已額滿，重試中。");
                    return;
                default:
                    var data={__VIEWSTATE:$(data).find("[name='__VIEWSTATE']").val(),Btn_Join:$(data).find("#Btn_Join").val()},url=BaseUrl+$(data).find("#Labor_Apply_D").prop("action");
                    get(ID,data,url);
                    log("勞作「"+val.name+"」可以報名，嘗試中。");

            }
        })
        .fail(function(jqXHR, textStatus, errorThrown){
            log("取得活動狀態失敗："+textStatus);
        });
    }
}
function process(){
	if(!en){proc=false;return;}
	$.each(logData,function(e,val){
		if(val.stat==1) return;
        if(logData[e].stat==0){
            logData[e].stat=2;
            get(e);
        }
	});
	setTimeout("process();",iProc);
}
function getlist(){
	if(!en) return;
	if(!loading){
        get("list");
        loading=true;
    }
	if(!proc && logData.length>0){
		proc=true;
		$("#display h1").html("有勞作開放，正在爭取中 :3");
		process();
	}
	setTimeout("getlist();",iList);
}
function Interval(l,p){
	iList=l;
	iProc=p;
}
function _switch(e){
	en=!en;
    if(en){getlist();}
	var val=(en)?"結束":"啟動";
	$(e).text(val);
}<|endoftext|>


<commit_before>/**
 * Created by timfulmer on 7/26/15.
 */
var Promise=require('bluebird'),
  oauth2orize=require('oauth2orize'),
  crypto = require('crypto'),
  utils=require('../app/utils');

function initialize(options){
  options=options || {};
  function initializePromise(resolve,reject){

    // create OAuth 2.0 server
    var server = oauth2orize.createServer();

    //(De-)Serialization for clients
    server.serializeClient(function(client, done) {
      return done(null, client.clientId);
    });

    server.deserializeClient(function(id, done) {
      options.collections.client.findOne({clientId: id})
        .then(function(client) {
          return done(null, client);
        })
        .catch(function(err){
          return done(err);
        });
    });

    //Implicit grant
    if(!options.collections || !options.collections.accesstoken){
      return reject(new Error('Could not find AccessToken ORM from config.'));
    }
    var token=oauth2orize.grant.token(function (client, user, ares, done) {
      var token = utils.uid(256);
      var expirationDate = new Date(new Date().getTime() + (3600 * 1000));

      options.collections.accesstoken.create({token: token, expirationDate: expirationDate, userId: user.username, clientId: client.clientId})
        .then(function(accessToken) {
          return done(null, token, {expires_in: expirationDate.toISOString()});
        })
        .catch(function(err){
          return done(err);
        });
    });
    var response=token.response;
    token.response=function(txn, res, next){
      var fakeRes={
        redirect:function(url){
          if(url.indexOf('access_token')>-1){
            res.json({accessToken:url.substring(url.indexOf('access_token')+13,url.indexOf('&'))});
          }else{
            res.send(401,'Unauthorized');
          }
        }
      };
      response(txn,fakeRes,next);
    };
    server.grant(token);
    options.oauth2Server=server;
    resolve(options);
  }
  return new Promise(initializePromise);
}

module.exports={
  initialize:initialize
};<commit_msg>Formatting and cleanup.<commit_after>/**
 * Created by timfulmer on 7/26/15.
 */
var Promise=require('bluebird'),
  oauth2orize=require('oauth2orize'),
  utils=require('../app/utils');

function initialize(options){
  options=options || {};
  function initializePromise(resolve,reject){

    var server = oauth2orize.createServer();

    server.serializeClient(function(client, done) {
      return done(null, client.clientId);
    });
    server.deserializeClient(function(id, done) {
      options.collections.client.findOne({clientId: id})
        .then(function(client) {
          return done(null, client);
        })
        .catch(function(err){
          return done(err);
        });
    });

    if(!options.collections || !options.collections.accesstoken){
      return reject(new Error('Could not find AccessToken ORM from config.'));
    }
    //Implicit grant
    var token=oauth2orize.grant.token(function (client, user, ares, done) {
      var token = utils.uid(256);
      var expirationDate = new Date(new Date().getTime() + (3600 * 1000));
      options.collections.accesstoken.create({
          token: token,
          expirationDate: expirationDate,
          userId: user.username,
          clientId: client.clientId
        })
        .then(function(accessToken) {
          return done(null, token, {expires_in: expirationDate.toISOString()});
        })
        .catch(function(err){
          return done(err);
        });
    });
    var response=token.response;
    token.response=function(txn, res, next){
      var fakeRes={
        redirect:function(url){
          if(url.indexOf('access_token')>-1){
            var start=url.indexOf('access_token')+13,
              end=url.indexOf('&');
            res.json({accessToken:url.substring(start,end)});
          }else{
            res.send(401,'Unauthorized');
          }
        }
      };
      response(txn,fakeRes,next);
    };
    server.grant(token);
    options.oauth2Server=server;
    resolve(options);
  }
  return new Promise(initializePromise);
}

module.exports={
  initialize:initialize
};<|endoftext|>