<commit_before>var AWS = require('../core');
var util = require('../util');
var QueryParamSerializer = require('../query/query_param_serializer');
var Shape = require('../model/shape');

function buildRequest(req) {
  var operation = req.service.api.operations[req.operation];
  var httpRequest = req.httpRequest;
  httpRequest.headers['Content-Type'] =
    'application/x-www-form-urlencoded; charset=utf-8';
  httpRequest.params = {
    Version: req.service.api.apiVersion,
    Action: operation.name
  };

  // convert the request parameters into a list of query params,
  // e.g. Deeply.NestedParam.0.Name=value
  var builder = new QueryParamSerializer();
  builder.serialize(req.params, operation.input, function(name, value) {
    httpRequest.params[name] = value;
  });
  httpRequest.body = util.queryParamsToString(httpRequest.params);
}

function extractError(resp) {
  var data, body = resp.httpResponse.body.toString();
  if (body.match('<UnknownOperationException')) {
    data = {
      Code: 'UnknownOperation',
      Message: 'Unknown operation ' + resp.request.operation
    };
  } else {
    data = new AWS.XML.Parser().parse(body);
  }

  if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
  if (data.Errors) data = data.Errors;
  if (data.Error) data = data.Error;
  if (data.Code) {
    resp.error = util.error(new Error(), {
      code: data.Code,
      message: data.Message
    });
  } else {
    resp.error = util.error(new Error(), {
      code: resp.httpResponse.statusCode,
      message: null
    });
  }
}

function extractData(resp) {
  var req = resp.request;
  var operation = req.service.api.operations[req.operation];
  var shape = operation.output || {};
  var origRules = shape;

  if (origRules.resultWrapper) {
    var tmp = Shape.create({type: 'structure'});
    tmp.members[origRules.resultWrapper] = shape;
    tmp.memberNames = [origRules.resultWrapper];
    util.property(shape, 'name', shape.resultWrapper);
    shape = tmp;
  }

  var parser = new AWS.XML.Parser();

  if (shape && shape.members && !shape.members._XAMZRequestId) {
    var requestIdShape = Shape.create(
      { type: 'string' },
      { api: { protocol: 'query' } },
      'requestId'
    );
    shape.members._XAMZRequestId = requestIdShape;
  }

  var data = parser.parse(resp.httpResponse.body.toString(), shape);
  resp.requestId = data._XAMZRequestId || data.requestId;

  if (data._XAMZRequestId) delete data._XAMZRequestId;

  if (origRules.resultWrapper) {
    if (data[origRules.resultWrapper]) {
      util.update(data, data[origRules.resultWrapper]);
      delete data[origRules.resultWrapper];
    }
  }

  resp.data = data;
}

module.exports = {
  buildRequest: buildRequest,
  extractError: extractError,
  extractData: extractData
};
<commit_msg>Add TODO to refactor XML Parser<commit_after>var AWS = require('../core');
var util = require('../util');
var QueryParamSerializer = require('../query/query_param_serializer');
var Shape = require('../model/shape');

function buildRequest(req) {
  var operation = req.service.api.operations[req.operation];
  var httpRequest = req.httpRequest;
  httpRequest.headers['Content-Type'] =
    'application/x-www-form-urlencoded; charset=utf-8';
  httpRequest.params = {
    Version: req.service.api.apiVersion,
    Action: operation.name
  };

  // convert the request parameters into a list of query params,
  // e.g. Deeply.NestedParam.0.Name=value
  var builder = new QueryParamSerializer();
  builder.serialize(req.params, operation.input, function(name, value) {
    httpRequest.params[name] = value;
  });
  httpRequest.body = util.queryParamsToString(httpRequest.params);
}

function extractError(resp) {
  var data, body = resp.httpResponse.body.toString();
  if (body.match('<UnknownOperationException')) {
    data = {
      Code: 'UnknownOperation',
      Message: 'Unknown operation ' + resp.request.operation
    };
  } else {
    data = new AWS.XML.Parser().parse(body);
  }

  if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
  if (data.Errors) data = data.Errors;
  if (data.Error) data = data.Error;
  if (data.Code) {
    resp.error = util.error(new Error(), {
      code: data.Code,
      message: data.Message
    });
  } else {
    resp.error = util.error(new Error(), {
      code: resp.httpResponse.statusCode,
      message: null
    });
  }
}

function extractData(resp) {
  var req = resp.request;
  var operation = req.service.api.operations[req.operation];
  var shape = operation.output || {};
  var origRules = shape;

  if (origRules.resultWrapper) {
    var tmp = Shape.create({type: 'structure'});
    tmp.members[origRules.resultWrapper] = shape;
    tmp.memberNames = [origRules.resultWrapper];
    util.property(shape, 'name', shape.resultWrapper);
    shape = tmp;
  }

  var parser = new AWS.XML.Parser();

  // TODO: Refactor XML Parser to parse RequestId from response.
  if (shape && shape.members && !shape.members._XAMZRequestId) {
    var requestIdShape = Shape.create(
      { type: 'string' },
      { api: { protocol: 'query' } },
      'requestId'
    );
    shape.members._XAMZRequestId = requestIdShape;
  }

  var data = parser.parse(resp.httpResponse.body.toString(), shape);
  resp.requestId = data._XAMZRequestId || data.requestId;

  if (data._XAMZRequestId) delete data._XAMZRequestId;

  if (origRules.resultWrapper) {
    if (data[origRules.resultWrapper]) {
      util.update(data, data[origRules.resultWrapper]);
      delete data[origRules.resultWrapper];
    }
  }

  resp.data = data;
}

module.exports = {
  buildRequest: buildRequest,
  extractError: extractError,
  extractData: extractData
};
<|endoftext|>


<commit_before>var request = require('request');
var q = require('queue-async');
var CacheOnDemand = require('cache-on-demand');

module.exports = RemoteProxy;
function RemoteProxy(raja, opts) {
	if (!(this instanceof RemoteProxy)) return new RemoteProxy(raja, opts);
	this.raja = raja;
	this.pollers = {};
	this.opts = opts || {};
	// default value
	if (this.opts.maxage == null) this.opts.maxage = Infinity;
	var self = this;
	raja.on('ready', function() {
		raja.store.lfu.on('eviction', function(url, resource) {
			var poller = self.pollers[url];
			if (!poller) return;
			delete self.pollers[url];
			// let it time out
		});
	});
}

RemoteProxy.prototype.get = function(url, opts, cb) {
	if (!cb && typeof opts == "function") {
		cb = opts;
		opts = null;
	}
	if (!opts) opts = {};
	var raja = this.raja;
	var poller = this.pollers[url] || {};
	if (opts.accept) poller.accept = opts.accept;
	if (poller.accept == "json") poller.accept = "application/json";

	raja.store.get(url, function(err, resource) {
		if (err) raja.error(err);
		if (!resource) resource = {url: url};
		if (!resource.maxage) resource.maxage = opts.maxage || this.opts.maxage;
		if (opts.preload) poller.preload = true;
		this.pollers[url] = poller;
		var delay = resource.mtime && (resource.maxage * 1000 - Date.now() + resource.mtime.getTime());
		if ((delay > 0 && resource.valid || poller.timeout || poller.preloading) && resource.data != null) {
			cb(null, resource);
			cb = null;
		}
		if (cb) {
			this.load(resource, poller, cb);
		} else if (!poller.timeout && !poller.preloading && delay > 0 && delay < Infinity) {
			poller.timeout = setTimeout(this.load.bind(this, resource, poller, raja.error), delay);
		}
	}.bind(this));
};

RemoteProxy.prototype.load = CacheOnDemand(function(resource, poller, cb) {
	var raja = this.raja;
	if (!cb) cb = raja.error;
	var obj = { url: resource.url, headers: {} };
	if (resource.headers && resource.headers.ETag) {
		obj.headers["If-None-Match"] = resource.headers.ETag;
	}
	if (poller.accept) obj.headers["Accept"] = poller.accept;
	poller.preloading = true;
	request(obj, function(err, res, body) {
		var code = res && res.statusCode;
		var foreign, msg;
		if (err) {
			if (cb) cb(err);
			if (!poller.preload) return;
		} else {
			foreign = res.headers['x-raja'] !== raja.opts.namespace;
			msg = { url: resource.url, mtime: new Date() };
		}

		if (code >= 500 || !code) {
			cb(code);
		} else if (code == 404) {
			raja.store.del(resource.url, function(err) {
				if (err) return raja.error(err);
				msg.method = 'delete';
				raja.send(msg);
			});
			// do not track
			return cb(code);
		} else if (code >= 400) {
			// do not track
			return cb(code);
		} else if (code == 304) {
			cb(null, resource);
		}	else if (code >= 200 && code < 300) {
			var dataStr = resource.data;
			if (dataStr && Buffer.isBuffer(dataStr)) dataStr = dataStr.toString();
			var bodyStr = body;
			if (body && Buffer.isBuffer(body)) bodyStr = body.toString();
			if (dataStr != bodyStr) {
				var invalidate = resource.data !== undefined;
				resource.data = body;
				resource.headers = {
					'Content-Type': res.headers['content-type'],
					'Etag': res.headers['etag'],
					'Vary': 'Content-Type'
				};
				resource.valid = true; // valid now
				raja.store.set(resource.url, {
					data: body,
					headers: resource.headers,
					maxage: resource.maxage
				}, function(err) {
					if (err) return raja.error(err);
					if (!invalidate) return;
					msg.method = 'put';
					raja.send(msg);
				});
			}
			cb(null, resource);
		} else {
			console.error("Error while trying to fetch remote resource", code, resource.url);
		}
		poller.preloading = false;
		if (!poller.timeout && resource.maxage < Infinity) {
			poller.timeout = setTimeout(function(resource, poller) {
				delete poller.timeout;
				if (poller.preload) {
					this.load(resource, poller);
				}	else if (resource.valid && !foreign) {
					raja.store.invalidate(resource.url, function(err) {
						if (err) return raja.error(err);
						// force parents to update on demand
						raja.send({ url: resource.url, mtime: new Date(), method: 'put' });
					});
				}
			}.bind(this, resource, poller), resource.maxage * 1000);
		}
	}.bind(this));
}, function(resource) {
	return resource.url;
});

<commit_msg>Remote proxy: CacheOnDemand uses arguments.length<commit_after>var request = require('request');
var q = require('queue-async');
var CacheOnDemand = require('cache-on-demand');

module.exports = RemoteProxy;
function RemoteProxy(raja, opts) {
	if (!(this instanceof RemoteProxy)) return new RemoteProxy(raja, opts);
	this.raja = raja;
	this.pollers = {};
	this.opts = opts || {};
	// default value
	if (this.opts.maxage == null) this.opts.maxage = Infinity;
	var self = this;
	raja.on('ready', function() {
		raja.store.lfu.on('eviction', function(url, resource) {
			var poller = self.pollers[url];
			if (!poller) return;
			delete self.pollers[url];
			// let it time out
		});
	});
}

RemoteProxy.prototype.get = function(url, opts, cb) {
	if (!cb && typeof opts == "function") {
		cb = opts;
		opts = null;
	}
	if (!opts) opts = {};
	var raja = this.raja;
	var poller = this.pollers[url] || {};
	if (opts.accept) poller.accept = opts.accept;
	if (poller.accept == "json") poller.accept = "application/json";

	raja.store.get(url, function(err, resource) {
		if (err) raja.error(err);
		if (!resource) resource = {url: url};
		if (!resource.maxage) resource.maxage = opts.maxage || this.opts.maxage;
		if (opts.preload) poller.preload = true;
		this.pollers[url] = poller;
		var delay = resource.mtime && (resource.maxage * 1000 - Date.now() + resource.mtime.getTime());
		if ((delay > 0 && resource.valid || poller.timeout || poller.preloading) && resource.data != null) {
			cb(null, resource);
			cb = null;
		}
		if (cb) {
			this.load(resource, poller, cb);
		} else if (!poller.timeout && !poller.preloading && delay > 0 && delay < Infinity) {
			poller.timeout = setTimeout(this.load.bind(this, resource, poller, raja.error), delay);
		}
	}.bind(this));
};

RemoteProxy.prototype.load = CacheOnDemand(function(resource, poller, cb) {
	var raja = this.raja;
	var obj = { url: resource.url, headers: {} };
	if (resource.headers && resource.headers.ETag) {
		obj.headers["If-None-Match"] = resource.headers.ETag;
	}
	if (poller.accept) obj.headers["Accept"] = poller.accept;
	poller.preloading = true;
	request(obj, function(err, res, body) {
		var code = res && res.statusCode;
		var foreign, msg;
		if (err) {
			cb(err);
			if (!poller.preload) return;
		} else {
			foreign = res.headers['x-raja'] !== raja.opts.namespace;
			msg = { url: resource.url, mtime: new Date() };
		}

		if (code >= 500 || !code) {
			cb(code);
		} else if (code == 404) {
			raja.store.del(resource.url, function(err) {
				if (err) return raja.error(err);
				msg.method = 'delete';
				raja.send(msg);
			});
			// do not track
			return cb(code);
		} else if (code >= 400) {
			// do not track
			return cb(code);
		} else if (code == 304) {
			cb(null, resource);
		}	else if (code >= 200 && code < 300) {
			var dataStr = resource.data;
			if (dataStr && Buffer.isBuffer(dataStr)) dataStr = dataStr.toString();
			var bodyStr = body;
			if (body && Buffer.isBuffer(body)) bodyStr = body.toString();
			if (dataStr != bodyStr) {
				var invalidate = resource.data !== undefined;
				resource.data = body;
				resource.headers = {
					'Content-Type': res.headers['content-type'],
					'Etag': res.headers['etag'],
					'Vary': 'Content-Type'
				};
				resource.valid = true; // valid now
				raja.store.set(resource.url, {
					data: body,
					headers: resource.headers,
					maxage: resource.maxage
				}, function(err) {
					if (err) return raja.error(err);
					if (!invalidate) return;
					msg.method = 'put';
					raja.send(msg);
				});
			}
			cb(null, resource);
		} else {
			console.error("Error while trying to fetch remote resource", code, resource.url);
		}
		poller.preloading = false;
		if (!poller.timeout && resource.maxage < Infinity) {
			poller.timeout = setTimeout(function(resource, poller) {
				delete poller.timeout;
				if (poller.preload) {
					this.load(resource, poller);
				}	else if (resource.valid && !foreign) {
					raja.store.invalidate(resource.url, function(err) {
						if (err) return raja.error(err);
						// force parents to update on demand
						raja.send({ url: resource.url, mtime: new Date(), method: 'put' });
					});
				}
			}.bind(this, resource, poller), resource.maxage * 1000);
		}
	}.bind(this));
}, function(resource) {
	return resource.url;
});

<|endoftext|>


<commit_before>var Promise = require('bluebird')
Promise.config({
  cancellation: true
})

function AsyncQueue () {
  this._queue = Array.isArray(arguments[0]) ? arguments[0] : []
  this.options = {timeout: 60000}
  var passedOptions = (this._queue.length || arguments[1] ? arguments[1] : arguments[0]) || []
  for (var key in passedOptions) {
    this.options[key] = passedOptions[key]
  }

  this.enqueue = enqueue.bind(this)
  this._dequeue = dequeue.bind(this)
  this.start = start.bind(this)
  this.stop = stop.bind(this)
  this.peek = peek.bind(this)
  this.on = on.bind(this)
}

function enqueue (func) {
  var that = this
  if (that.enqueueEvent) {
    that.enqueueEvent(func, that)
  }

  if (typeof func !== 'function') {
    throw new Error('AsyncQueue accepts only functions')
  }

  that._queue.push(func)
  that.length = that._queue.length

  return new Promise(function (resolve, reject) {
    func.resolve = resolve
    func.reject = reject
    func.pending = true

    that._dequeue()
  })
}

function dequeue () {
  if (this._stopped) {
    return
  }

  var that = this
  var func = that._queue[0]

  if (func && that.dequeueEvent) {
    that.dequeueEvent(func, that)
  }

  if (func && func.pending) {
    func.pending = false
    Promise.resolve(func())
    .timeout(that.options.timeout)
    .then(function (res) {
      that._queue.shift()
      that.length = that._queue.length
      return func.resolve(res)
    })
    .catch(function (err) {
      that._queue.shift()
      that.length = that._queue.length
      return func.reject(err)
    })
    .finally(function () {
      if (!that.length && that.emptyEvent) {
        that.emptyEvent()
      } else if (that.length) {
        that._dequeue()
      }
    })
  }
}

function peek (index) {
  return this._queue[index]
}

function stop () {
  this._stopped = true
  if (this.stopEvent) {
    this.stopEvent(this)
  }
}

function start () {
  this._stopped = false
  if (this.startEvent) {
    this.startEvent(this)
  }
  this._dequeue()
}

function on (event, cb) {
  this[event + 'Event'] = cb
}

module.exports = AsyncQueue
<commit_msg>fix: remove possibility to pass queue<commit_after>var Promise = require('bluebird')
Promise.config({
  cancellation: true
})

function AsyncQueue (options) {
  this._queue = []
  this.options = {timeout: 60000}
  if (options) {
    for (var key in options) {
      this.options[key] = options[key]
    }
  }

  this.enqueue = enqueue.bind(this)
  this._dequeue = dequeue.bind(this)
  this.start = start.bind(this)
  this.stop = stop.bind(this)
  this.peek = peek.bind(this)
  this.on = on.bind(this)
}

function enqueue (func) {
  var that = this
  if (that.enqueueEvent) {
    that.enqueueEvent(func, that)
  }

  if (typeof func !== 'function') {
    throw new Error('AsyncQueue accepts only functions')
  }

  that._queue.push(func)
  that.length = that._queue.length

  return new Promise(function (resolve, reject) {
    func.resolve = resolve
    func.reject = reject
    func.pending = true

    that._dequeue()
  })
}

function dequeue () {
  if (this._stopped) {
    return
  }

  var that = this
  var func = that._queue[0]

  if (func && that.dequeueEvent) {
    that.dequeueEvent(func, that)
  }

  if (func && func.pending) {
    func.pending = false
    Promise.resolve(func())
    .timeout(that.options.timeout)
    .then(function (res) {
      that._queue.shift()
      that.length = that._queue.length
      return func.resolve(res)
    })
    .catch(function (err) {
      that._queue.shift()
      that.length = that._queue.length
      return func.reject(err)
    })
    .finally(function () {
      if (!that.length && that.emptyEvent) {
        that.emptyEvent()
      } else if (that.length) {
        that._dequeue()
      }
    })
  }
}

function peek (index) {
  return this._queue[index]
}

function stop () {
  this._stopped = true
  if (this.stopEvent) {
    this.stopEvent(this)
  }
}

function start () {
  this._stopped = false
  if (this.startEvent) {
    this.startEvent(this)
  }
  this._dequeue()
}

function on (event, cb) {
  this[event + 'Event'] = cb
}

module.exports = AsyncQueue
<|endoftext|>


<commit_before>'use strict';

const Autoprefixer = require('broccoli-autoprefixer');
const fs = require('fs');

const treesToProcess = ['css', 'less', 'styl', 'scss', 'sass'];

module.exports = {
  name: require('./package').name,
  included: function(app) {
    this.app = app;

    if (typeof app.import !== 'function' && app.app) {
      this.app = app = app.app;
    }

    this._super.included.apply(this, arguments);

    var browserOptions = {};

    var root = this.project.root;
    var hasRCFile = !!fs.existsSync(`${root}/.browserlistrc`);
    var hasPkgBrowserList = !!require('./package').browserslist;

    if (!hasRCFile && !hasPkgBrowserList) {
      var addonOptions = this.app.options || {};
      var config = addonOptions[this.name] || {};

      browserOptions.overrideBrowsersList = config['autoprefixer'] && config['autoprefixer'].overrideBrowsersList;
    }

    this.options = Object.assign(
      {
        enabled: true
      },
      browserOptions,
      this.app.options.autoprefixer || {}
    );

    this.enabled = this.options.enabled;
    delete this.options.enabled;
  },

  postprocessTree: function(type, tree) {
    if (this.enabled && treesToProcess.includes(type)) {
      tree = new Autoprefixer(tree, this.options);
    }

    return tree;
  }
};
<commit_msg>existsSync returns a boolean<commit_after>'use strict';

const Autoprefixer = require('broccoli-autoprefixer');
const fs = require('fs');

const treesToProcess = ['css', 'less', 'styl', 'scss', 'sass'];

module.exports = {
  name: require('./package').name,
  included: function(app) {
    this.app = app;

    if (typeof app.import !== 'function' && app.app) {
      this.app = app = app.app;
    }

    this._super.included.apply(this, arguments);

    var browserOptions = {};

    var root = this.project.root;
    var hasRCFile = fs.existsSync(`${root}/.browserlistrc`);
    var hasPkgBrowserList = !!require('./package').browserslist;

    if (!hasRCFile && !hasPkgBrowserList) {
      var addonOptions = this.app.options || {};
      var config = addonOptions[this.name] || {};

      browserOptions.overrideBrowsersList = config['autoprefixer'] && config['autoprefixer'].overrideBrowsersList;
    }

    this.options = Object.assign(
      {
        enabled: true
      },
      browserOptions,
      this.app.options.autoprefixer || {}
    );

    this.enabled = this.options.enabled;
    delete this.options.enabled;
  },

  postprocessTree: function(type, tree) {
    if (this.enabled && treesToProcess.includes(type)) {
      tree = new Autoprefixer(tree, this.options);
    }

    return tree;
  }
};
<|endoftext|>


<commit_before>/* globals process */
'use strict'

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

const bigInt = require('big-integer')

client.on('error', (error) => {
  console.log(error)
})

app.use(bodyParser.json())

app.post('/', (req, res) => {
  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
    } else if (access) {
      console.log('t: ' + access.token)
      console.log('ts: ' + access.tokenSecret)
      twitter.search(
        {
          q: req.body.text,
          max_id: bigInt(twitterId).minus(1).toString()
        },
        access.token,
        access.tokenSecret,
        (error, data, response) => {
          if (error) {
            console.log(error)
          }
          else if (data && data.statuses && data.statuses[0]) {
            twitter.statuses(
              'update',
              {
                status: 'ney ' + data.statuses[0].id_str // '@horse_js @' + data.statuses[0].user.screen_name + ' https://twitter.com/' + data.statuses[0].user.screen_name + '/status/' + data.statuses[0].id_str,
              // in_reply_to_status_id: twitterId
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                }
              }
            )
          }
        })
    }
  })
  res.end()
})

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })

    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      console.log('t: ' + request.token)
      console.log('ts: ' + request.tokenSecret)
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<commit_msg>remove existing keys<commit_after>/* globals process */
'use strict'

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

const bigInt = require('big-integer')

client.on('error', (error) => {
  console.log(error)
})

app.use(bodyParser.json())

app.post('/', (req, res) => {
  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
    } else if (access) {
      console.log('t: ' + access.token)
      console.log('ts: ' + access.tokenSecret)
      twitter.search(
        {
          q: req.body.text,
          max_id: bigInt(twitterId).minus(1).toString()
        },
        access.token,
        access.tokenSecret,
        (error, data, response) => {
          if (error) {
            console.log(error)
          }
          else if (data && data.statuses && data.statuses[0]) {
            twitter.statuses(
              'update',
              {
                status: 'ney ' + data.statuses[0].id_str // '@horse_js @' + data.statuses[0].user.screen_name + ' https://twitter.com/' + data.statuses[0].user.screen_name + '/status/' + data.statuses[0].id_str,
              // in_reply_to_status_id: twitterId
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                }
              }
            )
          }
        })
    }
  })
  res.end()
})

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.del('request');
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })

    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      console.log('t: ' + request.token)
      console.log('ts: ' + request.tokenSecret)
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.del('access');
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<|endoftext|>


<commit_before>
function head (a) {
  return a[0]
}

function last (a) {
  return a[a.length - 1]
}

function tail(a) {
  return a.slice(1)
}

function retreat (e) {
  return e.pop()
}

function hasLength (e) {
  return e.length
}

function any(ary, test) {
  for(var i in ary)
    if(test(ary[i]))
      return true
  return false
}

function equal(a, b) {
  if(a.length != b.length) return false
  for(var i in a) {
    if(a[i] !== b[i]) return false
  }
  return true
}

function getArgs(args) {
  return args.length == 1 ? args[0] : [].slice.call(args)
}

// return the index of the element not like the others, or -1
function oddElement(ary, cmp) {
  var c
  function guess(a) {
    var odd = -1
    c = 0
    for (var i = a; i < ary.length; i ++) {
      if(!cmp(ary[a], ary[i])) {
        odd = i, c++
      }
    }
    return c > 1 ? -1 : odd
  }
  //assume that it is the first element.
  var g = guess(0)
  if(-1 != g) return g
  //0 was the odd one, then all the other elements are equal
  //else there more than one different element
  guess(1)
  return c == 0 ? 0 : -1
}

exports.lcs =
function lcs(a, b) {
  var cache = {}
  var args = [].slice.call(arguments)
  var lcses = []

  function key (a,b){
    return a.length + ':' + b.length
  }

  function recurse (a, b) {

    if(!a.length || !b.length) return []
    //avoid exponential time by caching the results
    if(cache[key(a, b)]) return cache[key(a, b)]

    if(a[0] == b[0])
      return [head(a)].concat(recurse(tail(a), tail(b)))
    else {
      var _a = recurse(tail(a), b)
      var _b = recurse(a, tail(b))
      return cache[key(a,b)] = _a.length > _b.length ? _a : _b
    }
  }

  if(!args.length) return []
  if(args.length == 1) return args.shift()
  if(args.length > 2) {
    //if called with multiple sequences
    //recurse, since lcs(a, b, c, d) == lcs(lcs(a,b), lcs(c,d))
    args.push(lcs(args.shift(), args.shift()))
    return lcs.apply(null, args)
  }
  return recurse.apply(null, args)
}

// given n sequences, calc the lcs, and then chunk strings into stable and unstable sections.
// chunk(sequences, build)
// build should be (stable, unstable)
// either stable or unstable will be passed. but never both.
exports.chunk =
function (q, build) {
  var q = q.map(function (e) { return e.slice() })
  var lcs = exports.lcs.apply(null, q)
  var all = [lcs].concat(q)

  function matchLcs (e) {
    return last(e) == last(lcs) || ((e.length + lcs.length) === 0)
  }

  while(any(q, hasLength)) {
    //if each element is at the lcs then this chunk is stable.
    while(q.every(matchLcs) && q.every(hasLength))
      all.forEach(retreat)

    //collect the changes in each array upto the next match with the lcs
    var c = false
    var unstable = q.map(function (e) {
      var change = []
      while(!matchLcs(e)) {
        change.unshift(retreat(e))
        c = true
      }
      return change
    })
    if(c) build(q[0].length, unstable)
  }
}

exports.diff =
function (a, b) {
  var changes = []
  exports.chunk([a, b], function (index, unstable) {
    if(unstable) {
      var del = unstable.shift().length
      var insert = unstable.shift()
      changes.push([index, del].concat(insert))
    }
  })
  return changes
}

exports.patch = function (a, changes, mutate) {
  if(mutate !== true) a = a.slice(a)//copy a
  changes.forEach(function (change) {
    [].splice.apply(a, change)
  })
  return a
}

// http://en.wikipedia.org/wiki/Concestor
// me, concestor, you...
exports.merge = function () {
  var args = getArgs(arguments)
  var patch = exports.diff3(args)
  return exports.patch(args[0], patch)
}

exports.diff3 = function () {
  var args = getArgs(arguments)
  var r = []
  exports.chunk(args, function (index, unstable) {
    if(unstable) {
      unstable = unstable.slice()
    //  var _o = unstable.splice(1, 1)[0]
      var mine = unstable[0]
      var insert = resolve(unstable)
      del = mine.length
      if(equal(mine, insert))
        return
      r.push([index, del].concat(insert))
    }
  })
  return r
}

var rules = [
  function oddOneOut (changes) {
    changes = changes.slice()
    //put the concestor first
    changes.unshift(changes.splice(1,1)[0])
    var oddi = oddElement(changes, equal)
    if(oddi == 0) {// concestor was different
      return changes[1]
    }
    else if (oddi == -1) {
      //if there is only one non empty change thats okay.
      //else full confilct
      for (var i = 1, nonempty; i < changes.length; i++)
        if(changes[i].length)
          if(!nonempty) nonempty = changes[i]
          else return // full conflict
      return nonempty
    } else
      return changes[oddi]
 }
]

function resolve (changes) {
  var l = rules.length
  for (var i in rules) {
    var c = rules[i](changes)
    if(c) return c
  }
  changes.splice(1,1) // remove concestor
  return {'?': changes}
}

<commit_msg>wow, down to 200 lines<commit_after>function head (a) {
  return a[0]
}

function last (a) {
  return a[a.length - 1]
}

function tail(a) {
  return a.slice(1)
}

function retreat (e) {
  return e.pop()
}

function hasLength (e) {
  return e.length
}

function any(ary, test) {
  for(var i in ary)
    if(test(ary[i]))
      return true
  return false
}

function equal(a, b) {
  if(a.length != b.length) return false
  for(var i in a)
    if(a[i] !== b[i]) return false
  return true
}

function getArgs(args) {
  return args.length == 1 ? args[0] : [].slice.call(args)
}

// return the index of the element not like the others, or -1
function oddElement(ary, cmp) {
  var c
  function guess(a) {
    var odd = -1
    c = 0
    for (var i = a; i < ary.length; i ++) {
      if(!cmp(ary[a], ary[i])) {
        odd = i, c++
      }
    }
    return c > 1 ? -1 : odd
  }
  //assume that it is the first element.
  var g = guess(0)
  if(-1 != g) return g
  //0 was the odd one, then all the other elements are equal
  //else there more than one different element
  guess(1)
  return c == 0 ? 0 : -1
}

exports.lcs =
function lcs() {
  var cache = {}
  var args = getArgs(arguments)

  function key (a,b){
    return a.length + ':' + b.length
  }

  function recurse (a, b) {

    if(!a.length || !b.length) return []
    //avoid exponential time by caching the results
    if(cache[key(a, b)]) return cache[key(a, b)]

    if(a[0] == b[0])
      return [head(a)].concat(recurse(tail(a), tail(b)))
    else {
      var _a = recurse(tail(a), b)
      var _b = recurse(a, tail(b))
      return cache[key(a,b)] = _a.length > _b.length ? _a : _b
    }
  }

  if(args.length > 2) {
    //if called with multiple sequences
    //recurse, since lcs(a, b, c, d) == lcs(lcs(a,b), lcs(c,d))
    args.push(lcs(args.shift(), args.shift()))
    return lcs(args)
  }
  return recurse(args[0], args[1])
}

// given n sequences, calc the lcs, and then chunk strings into stable and unstable sections.
// unstable chunks are passed to build
exports.chunk =
function (q, build) {
  var q = q.map(function (e) { return e.slice() })
  var lcs = exports.lcs.apply(null, q)
  var all = [lcs].concat(q)

  function matchLcs (e) {
    return last(e) == last(lcs) || ((e.length + lcs.length) === 0)
  }

  while(any(q, hasLength)) {
    //if each element is at the lcs then this chunk is stable.
    while(q.every(matchLcs) && q.every(hasLength))
      all.forEach(retreat)

    //collect the changes in each array upto the next match with the lcs
    var c = false
    var unstable = q.map(function (e) {
      var change = []
      while(!matchLcs(e)) {
        change.unshift(retreat(e))
        c = true
      }
      return change
    })
    if(c) build(q[0].length, unstable)
  }
}

exports.diff =
function (a, b) {
  var changes = []
  exports.chunk([a, b], function (index, unstable) {
    var del = unstable.shift().length
    var insert = unstable.shift()
    changes.push([index, del].concat(insert))
  })
  return changes
}

exports.patch = function (a, changes, mutate) {
  if(mutate !== true) a = a.slice(a)//copy a
  changes.forEach(function (change) {
    [].splice.apply(a, change)
  })
  return a
}

// http://en.wikipedia.org/wiki/Concestor
// me, concestor, you...
exports.merge = function () {
  var args = getArgs(arguments)
  var patch = exports.diff3(args)
  return exports.patch(args[0], patch)
}

exports.diff3 = function () {
  var args = getArgs(arguments)
  var r = []
  exports.chunk(args, function (index, unstable) {
    var mine = unstable[0]
    var insert = resolve(unstable)
    if(equal(mine, insert)) return
    r.push([index, mine.length].concat(insert))
  })
  return r
}

var rules = [
  function oddOneOut (changes) {
    changes = changes.slice()
    //put the concestor first
    changes.unshift(changes.splice(1,1)[0])
    var oddi = oddElement(changes, equal)
    if(oddi == 0) // concestor was different
      return changes[1]
    if (~oddi)
      return changes[oddi]
  },
  //i've implemented this as a seperate rule,
  //because I had second thoughts about this.
  function insertMergeOverDelete (changes) {
    changes = changes.slice()
    changes.splice(1,1)// remove concestor

    //if there is only one non empty change thats okay.
    //else full confilct
    for (var i = 0, nonempty; i < changes.length; i++)
      if(changes[i].length)
        if(!nonempty) nonempty = changes[i]
        else return // full conflict
    return nonempty
  }
]

function resolve (changes) {
  var l = rules.length
  for (var i in rules) { // first
    var c = rules[i](changes)
    if(c) return c
  }
  changes.splice(1,1) // remove concestor
  return {'?': changes}
}

<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var SourceMap = require("source-map");
var fs = require("fs");
var path = require("path");
var async = require("async");
var loaderUtils = require("loader-utils");

var baseRegex = "\\s*[@#]\\s*sourceMappingURL\\s*=\\s*(.*)",
	// Matches /* ... */ comments
	regex1 = new RegExp("/\\*"+baseRegex+"\\s*\\*/"),
	// Matches // .... comments
	regex2 = new RegExp("//"+baseRegex+"($|\n|\r\n?)"),
	// Matches DataUrls
	regexDataUrl = /data:[^;\n]+;base64,(.*)/;

module.exports = function(input, inputMap) {
	this.cacheable && this.cacheable();
	var resolve = this.resolve;
	var addDependency = this.addDependency;
	var emitWarning = this.emitWarning || function() {};
	var match = input.match(regex1) || input.match(regex2);
	if(match) {
		var url = match[1];
		var dataUrlMatch = regexDataUrl.exec(url);
		var callback = this.async();
		if(dataUrlMatch) {
			processMap(JSON.parse((new Buffer(dataUrlMatch[1], "base64")).toString()), this.context, callback);
		} else {
			resolve(this.context, loaderUtils.urlToRequest(url), function(err, result) {
				if(err) {
					emitWarning("Cannot find SourceMap '" + url + "': " + err);
					return untouched();
				}
				addDependency(result);
				fs.readFile(result, "utf-8", function(err, content) {
					if(err) {
						emitWarning("Cannot open SourceMap '" + result + "': " + err);
						return untouched();
					}
					processMap(JSON.parse(content), path.dirname(result), callback);
				});
			}.bind(this));
			return;
		}
	} else {
		var callback = this.callback;
		return untouched();
	}
	function untouched() {
		callback(null, input, inputMap);
	}
	function processMap(map, context, callback) {
		if(!map.sourcesContent || map.sourcesContent.length < map.sources.length) {
			var sourcePrefix = map.sourceRoot ? map.sourceRoot + "/" : "";
			map.sources = map.sources.map(function(s) { return sourcePrefix + s; });
			map.sourceRoot = undefined;
			var missingSources = map.sourcesContent ? map.sources.slice(map.sourcesContent.length) : map.sources;
			async.map(missingSources, function(source, callback) {
				resolve(context, loaderUtils.urlToRequest(source), function(err, result) {
					if(err) {
						emitWarning("Cannot find source file '" + source + "': " + err);
						return callback(null, null);
					}
					addDependency(result);
					fs.readFile(result, "utf-8", function(err, content) {
						if(err) {
							emitWarning("Cannot open source file '" + result + "': " + err);
							return callback(null, null);
						}
						callback(null, {
							source: result,
							content: content
						});
					});
				});
			}, function(err, info) {
				map.sourcesContent = map.sourcesContent || [];
				info.forEach(function(res) {
					if(res) {
						map.sources[map.sourcesContent.length] = res.source;
						map.sourcesContent.push(res.content);
					} else {
						map.sourcesContent.push(null);
					}
				});
				processMap(map, context, callback);
			});
			return;
		}
		callback(null, input.replace(match[0], match[2]), map);
	}
}
<commit_msg>fixed tests<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var SourceMap = require("source-map");
var fs = require("fs");
var path = require("path");
var async = require("async");
var loaderUtils = require("loader-utils");

var baseRegex = "\\s*[@#]\\s*sourceMappingURL\\s*=\\s*(.*)",
	// Matches /* ... */ comments
	regex1 = new RegExp("/\\*"+baseRegex+"\\s*\\*/"),
	// Matches // .... comments
	regex2 = new RegExp("//"+baseRegex+"($|\n|\r\n?)"),
	// Matches DataUrls
	regexDataUrl = /data:[^;\n]+;base64,(.*)/;

module.exports = function(input, inputMap) {
	this.cacheable && this.cacheable();
	var resolve = this.resolve;
	var addDependency = this.addDependency;
	var emitWarning = this.emitWarning || function() {};
	var match = input.match(regex1) || input.match(regex2);
	if(match) {
		var url = match[1];
		var dataUrlMatch = regexDataUrl.exec(url);
		var callback = this.async();
		if(dataUrlMatch) {
			processMap(JSON.parse((new Buffer(dataUrlMatch[1], "base64")).toString()), this.context, callback);
		} else {
			resolve(this.context, loaderUtils.urlToRequest(url), function(err, result) {
				if(err) {
					emitWarning("Cannot find SourceMap '" + url + "': " + err);
					return untouched();
				}
				addDependency(result);
				fs.readFile(result, "utf-8", function(err, content) {
					if(err) {
						emitWarning("Cannot open SourceMap '" + result + "': " + err);
						return untouched();
					}
					processMap(JSON.parse(content), path.dirname(result), callback);
				});
			}.bind(this));
			return;
		}
	} else {
		var callback = this.callback;
		return untouched();
	}
	function untouched() {
		callback(null, input, inputMap);
	}
	function processMap(map, context, callback) {
		if(!map.sourcesContent || map.sourcesContent.length < map.sources.length) {
			var sourcePrefix = map.sourceRoot ? map.sourceRoot + "/" : "";
			map.sources = map.sources.map(function(s) { return sourcePrefix + s; });
			delete map.sourceRoot;
			var missingSources = map.sourcesContent ? map.sources.slice(map.sourcesContent.length) : map.sources;
			async.map(missingSources, function(source, callback) {
				resolve(context, loaderUtils.urlToRequest(source), function(err, result) {
					if(err) {
						emitWarning("Cannot find source file '" + source + "': " + err);
						return callback(null, null);
					}
					addDependency(result);
					fs.readFile(result, "utf-8", function(err, content) {
						if(err) {
							emitWarning("Cannot open source file '" + result + "': " + err);
							return callback(null, null);
						}
						callback(null, {
							source: result,
							content: content
						});
					});
				});
			}, function(err, info) {
				map.sourcesContent = map.sourcesContent || [];
				info.forEach(function(res) {
					if(res) {
						map.sources[map.sourcesContent.length] = res.source;
						map.sourcesContent.push(res.content);
					} else {
						map.sourcesContent.push(null);
					}
				});
				processMap(map, context, callback);
			});
			return;
		}
		callback(null, input.replace(match[0], match[2]), map);
	}
}
<|endoftext|>


<commit_before>"use strict";

function randomGuid(numberOfBlocks) {
    num = numberOfBlocks || 4;

    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }
    return output;
}
module.exports = randomGuid;

//generate a guid that is tested unique against id's on the current doc
function domSafeRandomGuid(numberOfBlocks) {
    num = numberOfBlocks || 4;

    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }

    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }

    if (null === document.getElementById(output)) {
        randomSafeGuid(numberOfBlocks);
    } else {
        return output;
    }
}
module.exports = domSafeRandomGuid;<commit_msg>cleaned out a bug, should have had tests....<commit_after>"use strict";

function randomGuid(numberOfBlocks) {
    num = numberOfBlocks || 4;

    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }
    return output;
}
module.exports = randomGuid;

//generate a guid that is tested unique against id's on the current doc
function domSafeRandomGuid(numberOfBlocks) {
    num = numberOfBlocks || 4;

    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }

    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }

    if (null === document.getElementById(output)) {
        domSafeRandomGuid(numberOfBlocks);
    } else {
        return output;
    }
}
module.exports = domSafeRandomGuid;<|endoftext|>


<commit_before>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

'use strict';

const fs = require('fs');

const local = require('./utils/local');

const config = {
	env: {
		es6: true,
	},
	extends: ['eslint:recommended', require.resolve('eslint-config-prettier')],
	parserOptions: {
		ecmaVersion: 2017,
		sourceType: 'module',
	},
	plugins: [
		local('liferay'),
		'no-for-of-loops',
		'no-only-tests',
		'notice',
		'sort-destructure-keys',
	],
	rules: {
		'default-case': 'error',
		'liferay/destructure-requires': 'error',
		'liferay/group-imports': 'error',
		'liferay/imports-first': 'error',
		'liferay/no-absolute-import': 'error',
		'liferay/no-duplicate-imports': 'error',
		'liferay/no-dynamic-require': 'error',
		'liferay/no-it-should': 'error',
		'liferay/no-require-and-call': 'error',
		'liferay/padded-test-blocks': 'error',
		'liferay/sort-imports': 'error',
		'no-console': ['error', {allow: ['warn', 'error']}],
		'no-constant-condition': ['error', {checkLoops: false}],
		'no-control-regex': 'off',
		'no-for-of-loops/no-for-of-loops': 'error',
		'no-only-tests/no-only-tests': 'error',
		'no-return-assign': ['error', 'always'],
		'no-unused-expressions': 'error',
		'no-unused-vars': ['error', {argsIgnorePattern: '^_'}],
		'object-shorthand': 'error',
		'prefer-arrow-callback': ['error', {allowNamedFunctions: true}],
		'prefer-const': 'error',
		'prefer-object-spread': 'error',
		'quote-props': ['error', 'as-needed'],
		radix: 'error',
		'sort-destructure-keys/sort-destructure-keys': [
			'error',
			{caseSensitive: true},
		],
		'sort-keys': ['error', 'asc', {caseSensitive: true, natural: true}],
	},
};

if (fs.existsSync('copyright.js')) {
	config.rules['notice/notice'] = [
		'error',
		{
			templateFile: 'copyright.js',
		},
	];
}

module.exports = config;
<commit_msg>feat: bump ecmaVersion to 2018<commit_after>/**
 * © 2017 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: MIT
 */

'use strict';

const fs = require('fs');

const local = require('./utils/local');

const config = {
	env: {
		es6: true,
	},
	extends: ['eslint:recommended', require.resolve('eslint-config-prettier')],
	parserOptions: {
		ecmaVersion: 2018,
		sourceType: 'module',
	},
	plugins: [
		local('liferay'),
		'no-for-of-loops',
		'no-only-tests',
		'notice',
		'sort-destructure-keys',
	],
	rules: {
		'default-case': 'error',
		'liferay/destructure-requires': 'error',
		'liferay/group-imports': 'error',
		'liferay/imports-first': 'error',
		'liferay/no-absolute-import': 'error',
		'liferay/no-duplicate-imports': 'error',
		'liferay/no-dynamic-require': 'error',
		'liferay/no-it-should': 'error',
		'liferay/no-require-and-call': 'error',
		'liferay/padded-test-blocks': 'error',
		'liferay/sort-imports': 'error',
		'no-console': ['error', {allow: ['warn', 'error']}],
		'no-constant-condition': ['error', {checkLoops: false}],
		'no-control-regex': 'off',
		'no-for-of-loops/no-for-of-loops': 'error',
		'no-only-tests/no-only-tests': 'error',
		'no-return-assign': ['error', 'always'],
		'no-unused-expressions': 'error',
		'no-unused-vars': ['error', {argsIgnorePattern: '^_'}],
		'object-shorthand': 'error',
		'prefer-arrow-callback': ['error', {allowNamedFunctions: true}],
		'prefer-const': 'error',
		'prefer-object-spread': 'error',
		'quote-props': ['error', 'as-needed'],
		radix: 'error',
		'sort-destructure-keys/sort-destructure-keys': [
			'error',
			{caseSensitive: true},
		],
		'sort-keys': ['error', 'asc', {caseSensitive: true, natural: true}],
	},
};

if (fs.existsSync('copyright.js')) {
	config.rules['notice/notice'] = [
		'error',
		{
			templateFile: 'copyright.js',
		},
	];
}

module.exports = config;
<|endoftext|>


<commit_before>module.exports = {
	/**
	 * Convert architectural measurement to decimal notation.
	 *
	 * @param {String} architectural
	 * @param {String} units
	 * @param {String} precision
	 * @return {Number}
	 */

	toDecimal: function(architectural, units, precision) {
		if (typeof architectural !== "string" && !(architectural instanceof String))
			return;
		if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null)
			return;
		if(["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision) < 0)
			return;
		if(["inches", "feet"].indexOf(units) < 0)
			return;

		var decimal = 0;

		var feet = architectural.match(/^([0-9]+)\'[-\s]*/);
		if(feet !== null)
			decimal += parseInt(feet[1]) * 12;

		var inches = architectural.match(/([-\s\']+([0-9]+)|^([0-9]+))[-\s\"]+/);
		if(inches !== null) {
			if(feet !== null)
				decimal += parseInt(inches[2]);
			else
				decimal += parseInt(inches[3]);
		}

		var fraction = architectural.match(/([-\s\']+([0-9]+\/[0-9]+)|(^[0-9]+\/[0-9]+))\"/);
		if(fraction !== null) {
			if(feet !== null || inches !== null)
				decimal += divideFraction(fraction[2]);
			else
				decimal += divideFraction(fraction[3]);
		}

		if(units !== "inches")
			decimal = decimal / 12;

		decimal = roundNumber(decimal, ["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision));

		return decimal;
	},

	/**
	 * Convert decimal measurement to architectural notation.
	 *
	 * @param {Number} decimal
	 * @param {String} units
	 * @param {String} precision
	 * @return {String}
	 */

	toArchitectural: function(decimal, units, precision) {
		if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal))
			return;
		if(["inches", "feet"].indexOf(units) < 0)
			return;
		if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0)
			return;

		var architectural = "";

		var precision = parseFloat(precision.replace("1/", ""));

		if(units !== "inches")
			decimal = decimal * 12;

		if(decimal < 0) {
			decimal = Math.abs(decimal);
			architectural += "-";
		}

		var feet = Math.floor(decimal / 12);
		architectural += feet + "' ";

		var inches = Math.floor(decimal - (feet * 12));
		architectural += inches + "\"";

		var fraction = Math.floor((decimal - (feet * 12) - inches) * precision);
		if(fraction > 0)
			architectural += architectural.replace("\"", " " + reduceFraction(fraction, precision) + "\"");

		return architectural;
	}
};

var divideFraction = function(fraction) {
	var bits = fraction.split("/");
	return parseInt(bits[0], 10) / parseInt(bits[1], 10);
};

var roundNumber = function(n, decimalPlaces) {
	return Math.floor(n * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
};

var reduceFraction = function(numerator, denominator) {
	var gcd = greatestCommonDenominator(numerator, denominator);
	return (numerator / gcd) + "/" + (denominator / gcd);
};

var greatestCommonDenominator = function(a, b) {
	return b ? greatestCommonDenominator(b, a % b) : Math.abs(a);
};

var isNumber = function(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
};<commit_msg>fixed bug in toArchitectural method<commit_after>module.exports = {
	/**
	 * Convert architectural measurement to decimal notation.
	 *
	 * @param {String} architectural
	 * @param {String} units
	 * @param {String} precision
	 * @return {Number}
	 */

	toDecimal: function(architectural, units, precision) {
		if (typeof architectural !== "string" && !(architectural instanceof String))
			return;
		if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null)
			return;
		if(["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision) < 0)
			return;
		if(["inches", "feet"].indexOf(units) < 0)
			return;

		var decimal = 0;

		var feet = architectural.match(/^([0-9]+)\'[-\s]*/);
		if(feet !== null)
			decimal += parseInt(feet[1]) * 12;

		var inches = architectural.match(/([-\s\']+([0-9]+)|^([0-9]+))[-\s\"]+/);
		if(inches !== null) {
			if(feet !== null)
				decimal += parseInt(inches[2]);
			else
				decimal += parseInt(inches[3]);
		}

		var fraction = architectural.match(/([-\s\']+([0-9]+\/[0-9]+)|(^[0-9]+\/[0-9]+))\"/);
		if(fraction !== null) {
			if(feet !== null || inches !== null)
				decimal += divideFraction(fraction[2]);
			else
				decimal += divideFraction(fraction[3]);
		}

		if(units !== "inches")
			decimal = decimal / 12;

		decimal = roundNumber(decimal, ["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision));

		return decimal;
	},

	/**
	 * Convert decimal measurement to architectural notation.
	 *
	 * @param {Number} decimal
	 * @param {String} units
	 * @param {String} precision
	 * @return {String}
	 */

	toArchitectural: function(decimal, units, precision) {
		if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal))
			return;
		if(["inches", "feet"].indexOf(units) < 0)
			return;
		if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0)
			return;

		var architectural = "";

		var precision = parseFloat(precision.replace("1/", ""));

		if(units !== "inches")
			decimal = decimal * 12;

		if(decimal < 0) {
			decimal = Math.abs(decimal);
			architectural += "-";
		}

		var feet = Math.floor(decimal / 12);
		architectural += feet + "' ";

		var inches = Math.floor(decimal - (feet * 12));
		architectural += inches + "\"";

		var fraction = Math.floor((decimal - (feet * 12) - inches) * precision);
		if(fraction > 0)
			architectural = architectural.replace("\"", " " + reduceFraction(fraction, precision) + "\"");

		return architectural;
	}
};

var divideFraction = function(fraction) {
	var bits = fraction.split("/");
	return parseInt(bits[0], 10) / parseInt(bits[1], 10);
};

var roundNumber = function(n, decimalPlaces) {
	return Math.floor(n * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
};

var reduceFraction = function(numerator, denominator) {
	var gcd = greatestCommonDenominator(numerator, denominator);
	return (numerator / gcd) + "/" + (denominator / gcd);
};

var greatestCommonDenominator = function(a, b) {
	return b ? greatestCommonDenominator(b, a % b) : Math.abs(a);
};

var isNumber = function(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
};<|endoftext|>


<commit_before>'use strict';

var through = require('through2'),
  gutil = require('gulp-util'),
  spawn = require('child_process').spawn,
  builtin_gae = require('google-app-engine')(),
  objectAssign = require('object-assign'),
  PluginError = gutil.PluginError,
  File = gutil.File;

module.exports = function (script, options, callback) {
  var defaults = {
    commands: [],
    gae_dir: builtin_gae
  }

  const conf = objectAssign({}, defaults, options);

  var proc;

  if (['dev_appserver.py', 'appcfg.py'].indexOf(script) == -1) {
    throw new PluginError('gulp-gae', 'Invalid script ' + script + '. Supported scripts are dev_appserver.py and appcfg.py');
  }

  function parseParams(params) {
    var p = [];
    for (var key in params) {
      if (key === 'commands') continue;
      if (key === 'gae_dir') continue;

      var value = params[key];
      if (value === undefined) {
        // Value-less parameters.
        p.push('--' + key);
      } else {
        p.push('--' + key + '=' + value);
      }
    }
    return p;
  }

  function runScript(file, args, params, cb) {
    var scriptArgs = args.concat(parseParams(params));
    gutil.log('[gulp-gae-improved]', scriptArgs);
    proc = spawn(conf.gae_dir + '/' + file, scriptArgs);
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    cb && cb();
  }

  function stopScript() {
    gutil.log('[gulp-gae-improved]', 'stopping script');
    proc && proc.kill('SIGHUP');
    proc = null;
    callback && callback();
  }

  function bufferContents(file, enc, cb) {
    var appYamlPath = file.path,
      shouldWait = false;

    if (script == 'dev_appserver.py') {
      args = [appYamlPath];
    } else if (script == 'appcfg.py') {
      args = conf.commands.concat([appYamlPath]);
      shouldWait = true;
    }

    runScript(script, args, conf, cb);

    process.on('exit', stopScript);
  }

  function endStream(cb) {
    cb();
    return;
  }

  return through.obj(bufferContents, endStream);
};
<commit_msg>fix missing args variable<commit_after>'use strict';

var through = require('through2'),
  gutil = require('gulp-util'),
  spawn = require('child_process').spawn,
  builtin_gae = require('google-app-engine')(),
  objectAssign = require('object-assign'),
  PluginError = gutil.PluginError,
  File = gutil.File;

module.exports = function (script, options, callback) {
  var defaults = {
    commands: [],
    gae_dir: builtin_gae
  }

  const conf = objectAssign({}, defaults, options);

  var proc;

  if (['dev_appserver.py', 'appcfg.py'].indexOf(script) == -1) {
    throw new PluginError('gulp-gae', 'Invalid script ' + script + '. Supported scripts are dev_appserver.py and appcfg.py');
  }

  function parseParams(params) {
    var p = [];
    for (var key in params) {
      if (key === 'commands') continue;
      if (key === 'gae_dir') continue;

      var value = params[key];
      if (value === undefined) {
        // Value-less parameters.
        p.push('--' + key);
      } else {
        p.push('--' + key + '=' + value);
      }
    }
    return p;
  }

  function runScript(file, args, params, cb) {
    var scriptArgs = args.concat(parseParams(params));
    gutil.log('[gulp-gae-improved]', scriptArgs);
    proc = spawn(conf.gae_dir + '/' + file, scriptArgs);
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    cb && cb();
  }

  function stopScript() {
    gutil.log('[gulp-gae-improved]', 'stopping script');
    proc && proc.kill('SIGHUP');
    proc = null;
    callback && callback();
  }

  function bufferContents(file, enc, cb) {
    var appYamlPath = file.path,
      shouldWait = false,
      args;

    if (script == 'dev_appserver.py') {
      args = [appYamlPath];
    } else if (script == 'appcfg.py') {
      args = conf.commands.concat([appYamlPath]);
      shouldWait = true;
    }

    runScript(script, args, conf, cb);

    process.on('exit', stopScript);
  }

  function endStream(cb) {
    cb();
    return;
  }

  return through.obj(bufferContents, endStream);
};
<|endoftext|>


<commit_before>/* eslint strict: 0 */

'use strict';

/**
 * Proxy
 *
 * @external Proxy
 * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy}
 */

/**
 * Nuonce exports four functions: `default`, `stripped`, `copied` and `proxied`.
 *
 * @exports nuonce
 * @see {@link module:nuonce.default}, {@link module:nuonce.stripped}, {@link module:nuonce.copied}, {@link module:nuonce.proxied}
 */
module.exports = {
	/**
	 * Returns a function that will call the `fn` function just once.
	 * Every next time the returned function is called, it will return value from the first call.
	 *
	 * The returned function does not keep properties or `length` of target function, so if
	 * callers depend on its decorations and/or specific `length`, use the `{@link module:nuonce.copied}` method instead.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {Function}
	 */
	stripped: _nuonce,

	/**
	 * Returns a function that will call the `fn` function just once.
	 * Every next time the returned function is called, it will return value from the first call.
	 *
	 * The returned function has enumerable properties and `length` (number of declared arguments)
	 * copied from the target function.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {Function}
	 */
	copied: _nuonceWithCopiedProperties,

	/**
	 * Returns a callable Proxy object that will call the `fn` function just once.
	 * Every next time the returned object is called, it will return value from the first call.
	 *
	 * The returned Proxy object points to the target function.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {external:Proxy}
	 */
	proxied: _nuonceWithProxyES6,

	/**
	 * Currently it simply points to the `{@link module:nuonce.proxied}` for greatest compatibility.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {external:Proxy|Function}
	 */
	default: _nuonceWithProxyES6
};

/**
 * List of `_nuonce` versions for different lengths of arguments.
 *
 * @private
 * @type {Function[]}
 */
var _nuonces = [
	_nuonce
];

/**
 * Source code cache of the `_nuonce` function for faster creation of different lengths variations.
 *
 * @private
 */
var _nuonceSource = _nuonce.toString().replace(/^function[^{]*{|}$/g, '');

// Strip coverage stuff, to prevent test failures
_nuonceSource = _nuonceSource.replace(/__cov_[^+]+\+\+;/g, '');
// Prepare it for injecting arguments
_nuonceSource = _nuonceSource.replace(/_f\s*\(\)/, '_f (...args)');

/**
 * Creates a new variation of `_nuonce` for specified length of arguments and stores it in `_nuonces` cache.
 *
 * @private
 * @param {Number} length
 * @return {Function}
 */
function _nuoncesPrepare (length) {
	var src = _nuonceSource;
	var args = new Array(length);

	for (var i = length - 1; i > -1; i--) {
		args[i] = 'a' + i;
	}

	var argv = args.join(', ');

	/* eslint-disable no-new-func */
	_nuonces[length] = new Function('fn', 'cb', src.replace('...args', argv));
	/* eslint-enable no-new-func */

	return _nuonces[length];
}

/**
 * Creates a Function wrapper that stores result of a target function after it is called for the first time.
 * Every next time it is called, it will simply return the first result, without calling the target function ever again.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {Function}
 */
function _nuonce (fn, cb) {
	if (typeof fn !== 'function') {
		throw new Error('argument must be a function');
	}

	if (cb && typeof cb !== 'function') {
		throw new Error('callback must be a function');
	}

	var r;

	/**
	 * @private
	 * @return {any} whatever was returned by cb
	 */
	function _f () {
		if (fn) {
			// Use `...args` in future, when it's not so much slower than `arguments`.
			r = fn.apply(this, arguments);

			// Free any references to the target function
			fn = null;

			if (cb) {
				cb(r);
				cb = null;
			}
		}

		return r;
	}

	return _f;
}

/**
 * Creates a `_nuonce` and adds copies of enumerable properties from the target function.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {Function}
 */
function _nuonceWithCopiedProperties (fn, cb) {
	var l = fn.length;
	var f = (_nuonces[l] || _nuoncesPrepare(l))(fn, cb);

	var keys = Object.keys(fn);
	var k;
	for (var i = 0, imax = keys.length; i < imax; i++) {
		k = keys[i];
		f[k] = fn[k];
	}

	return f;
}

/**
 * Creates a Proxy (ES6) function pointing to a target function.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {external:Proxy}
 */
function _nuonceWithProxyES6 (fn, cb) {
	var r;

	if (cb && typeof cb !== 'function') {
		throw new Error('callback must be a function');
	}

	return new Proxy(fn, {
		apply: function (_, ctx, args) {
			if (fn) {
				r = _.apply(ctx, args);
				fn = null;
				if (cb) {
					cb(r);
					cb = null;
				}
			}

			return r;
		},
		construct: function (_, args) {
			if (fn) {
				r = new _(...args);
				fn = null;
				if (cb) {
					cb(r);
					cb = null;
				}
			}

			return r;
		}
	});
}
<commit_msg>refactor: remove line that was needed to make things work in `istanbul`, but is not needed for `c8` (or native node coverage reporting)<commit_after>/* eslint strict: 0 */

'use strict';

/**
 * Proxy
 *
 * @external Proxy
 * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy}
 */

/**
 * Nuonce exports four functions: `default`, `stripped`, `copied` and `proxied`.
 *
 * @exports nuonce
 * @see {@link module:nuonce.default}, {@link module:nuonce.stripped}, {@link module:nuonce.copied}, {@link module:nuonce.proxied}
 */
module.exports = {
	/**
	 * Returns a function that will call the `fn` function just once.
	 * Every next time the returned function is called, it will return value from the first call.
	 *
	 * The returned function does not keep properties or `length` of target function, so if
	 * callers depend on its decorations and/or specific `length`, use the `{@link module:nuonce.copied}` method instead.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {Function}
	 */
	stripped: _nuonce,

	/**
	 * Returns a function that will call the `fn` function just once.
	 * Every next time the returned function is called, it will return value from the first call.
	 *
	 * The returned function has enumerable properties and `length` (number of declared arguments)
	 * copied from the target function.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {Function}
	 */
	copied: _nuonceWithCopiedProperties,

	/**
	 * Returns a callable Proxy object that will call the `fn` function just once.
	 * Every next time the returned object is called, it will return value from the first call.
	 *
	 * The returned Proxy object points to the target function.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {external:Proxy}
	 */
	proxied: _nuonceWithProxyES6,

	/**
	 * Currently it simply points to the `{@link module:nuonce.proxied}` for greatest compatibility.
	 *
	 * @function
	 * @param {Function} fn
	 * @param {Function} [cb]   call back once with result, right after first call
	 * @return {external:Proxy|Function}
	 */
	default: _nuonceWithProxyES6
};

/**
 * List of `_nuonce` versions for different lengths of arguments.
 *
 * @private
 * @type {Function[]}
 */
var _nuonces = [
	_nuonce
];

/**
 * Source code cache of the `_nuonce` function for faster creation of different lengths variations.
 *
 * @private
 */
var _nuonceSource = _nuonce.toString().replace(/^function[^{]*{|}$/g, '');

// Prepare it for injecting arguments
_nuonceSource = _nuonceSource.replace(/_f\s*\(\)/, '_f (...args)');

/**
 * Creates a new variation of `_nuonce` for specified length of arguments and stores it in `_nuonces` cache.
 *
 * @private
 * @param {Number} length
 * @return {Function}
 */
function _nuoncesPrepare (length) {
	var src = _nuonceSource;
	var args = new Array(length);

	for (var i = length - 1; i > -1; i--) {
		args[i] = 'a' + i;
	}

	var argv = args.join(', ');

	/* eslint-disable no-new-func */
	_nuonces[length] = new Function('fn', 'cb', src.replace('...args', argv));
	/* eslint-enable no-new-func */

	return _nuonces[length];
}

/**
 * Creates a Function wrapper that stores result of a target function after it is called for the first time.
 * Every next time it is called, it will simply return the first result, without calling the target function ever again.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {Function}
 */
function _nuonce (fn, cb) {
	if (typeof fn !== 'function') {
		throw new Error('argument must be a function');
	}

	if (cb && typeof cb !== 'function') {
		throw new Error('callback must be a function');
	}

	var r;

	/**
	 * @private
	 * @return {any} whatever was returned by cb
	 */
	function _f () {
		if (fn) {
			// Use `...args` in future, when it's not so much slower than `arguments`.
			r = fn.apply(this, arguments);

			// Free any references to the target function
			fn = null;

			if (cb) {
				cb(r);
				cb = null;
			}
		}

		return r;
	}

	return _f;
}

/**
 * Creates a `_nuonce` and adds copies of enumerable properties from the target function.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {Function}
 */
function _nuonceWithCopiedProperties (fn, cb) {
	var l = fn.length;
	var f = (_nuonces[l] || _nuoncesPrepare(l))(fn, cb);

	var keys = Object.keys(fn);
	var k;
	for (var i = 0, imax = keys.length; i < imax; i++) {
		k = keys[i];
		f[k] = fn[k];
	}

	return f;
}

/**
 * Creates a Proxy (ES6) function pointing to a target function.
 *
 * @private
 * @param {Function} fn
 * @param {Function} [cb]   call back once with result, right after first call
 * @return {external:Proxy}
 */
function _nuonceWithProxyES6 (fn, cb) {
	var r;

	if (cb && typeof cb !== 'function') {
		throw new Error('callback must be a function');
	}

	return new Proxy(fn, {
		apply: function (_, ctx, args) {
			if (fn) {
				r = _.apply(ctx, args);
				fn = null;
				if (cb) {
					cb(r);
					cb = null;
				}
			}

			return r;
		},
		construct: function (_, args) {
			if (fn) {
				r = new _(...args);
				fn = null;
				if (cb) {
					cb(r);
					cb = null;
				}
			}

			return r;
		}
	});
}
<|endoftext|>


<commit_before>'use strict';

let creds = require('./creds.js').creds;
let Promise = require('bluebird');
let evernote = require('./base.js').Evernote;
evernote.Client = require('./client.js').Client;
let enml = require('enml-js');
let authToken;
let client;
let noteStore;

function tagsNotebook(notebookguid) {
  // get tags of notebook
  let prms = Promise.promisify(noteStore.listTagsByNotebook);
  return prms(notebookguid)
}
function count(noteFilter) {
  // get count of notes of notebook
  let prms = Promise.promisify(noteStore.findNoteCounts);
  return prms(noteFilter, false)
}
function listNote(offset, count, noteFilter, notesMetadataResultSpec) {
  // get the guids of notes
  let prms = Promise.promisify(noteStore.findNotesMetadata);
  return prms(noteFilter, offset, count, notesMetadataResultSpec)
}
function listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults) {
  // get as many guids of notes as evernote will return and continue until the end
  return listNote(offset, count, noteFilter, notesMetadataResultSpec)
    .then(response => {
      // add new results to result set
      for (let index = 0; index < response.notes.length; index++) {
        noteResults.push(response.notes[index]);
      }
      if (offset < count) {
        // there are still more notes, continue
        offset += response.notes.length;
        return listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults);
      } else {
        return noteResults;
      }
    });
}
function notes(notebookguid) {
  // get note guids of notebook
  let notesMetadataResultSpec = new evernote.NotesMetadataResultSpec;
  notesMetadataResultSpec.includeTitle = true;
  notesMetadataResultSpec.includeContentLength = true;
  notesMetadataResultSpec.includeCreated = true;
  notesMetadataResultSpec.includeUpdated = true;
  notesMetadataResultSpec.includeTagGuids = true;
  let noteFilter = new evernote.NoteFilter;
  noteFilter.notebookGuid = notebookguid;
  noteFilter.ascending = false;
  noteFilter.order = 1;
  let noteResults = [];

  return count(noteFilter)
    .then(response => listMoreNotes(0, response.notebookCounts[notebookguid], noteFilter, notesMetadataResultSpec, noteResults));
}
function notebook(notebookguid) {
  // get tags and note guids of notebook
  return Promise.all([tagsNotebook(notebookguid), notes(notebookguid)])
}
function tagsNote(noteguid) {
  // get tags of note
  let prms = Promise.promisify(noteStore.getNoteTagNames);
  return prms(noteguid);
}
function selectpic(res) {
  // select a usable pic resource
  let lsindex = 0;
  let lsvalue = 0;
  let usableResources = [];

  if (res.resources) {
    // find out which resources have a non-empty sourceUrl
    for (let i = 0; i < res.resources.length; i++) {
      if (res.resources[i].attributes.sourceURL) usableResources.push(res.resources[i]);
    }
    if (usableResources.length > 0) {
      // select a resource using evernote's 'largest-smallest' algorithm
      for (let i = 0; i < usableResources.length; i++) {
        let temp = Math.min(usableResources[i].width, usableResources[i].height);
        if (temp === 0) { continue; }
        if (temp > lsvalue) {
          lsindex = i;
          lsvalue = temp;
        }
      }
      return usableResources[lsindex].attributes.sourceURL;
    } else {
      return '';
    }
  }
}
function notecontent(noteguid) {
  // get content of note
  // let prms = Promise.promisify(noteStore.getNoteContent); // this works
  // return prms(noteguid); // this works
  return new Promise((resolve, reject) => {
    noteStore.getNote(noteguid, true, true, true, true, function(err, note) {
      if (err) { reject(err) }
      else { resolve(enml.HTMLOfENML(note.content, note.resources)) }
    })
  });
}
function note(noteguid) {
  // get tags and content of note of notebook
  return Promise.all([tagsNote(noteguid), notecontent(noteguid)])
}

exports.handler = (event, context, callback) => {
  // if no command was specified, then exit
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else {
    // init evernote api
    authToken = creds.token;
    client = new evernote.Client({
      token: authToken,
      sandbox: false
    });
    noteStore = client.getNoteStore();
    // main switch
    switch (event.cmd) {
    case 'getNotebooks':
      // get all notebooks of the authenticated user
      let prms = Promise.promisify(noteStore.listNotebooks);
      prms(authToken)
        .then(response => callback(null, response))
        .catch(error => callback(error));
      break;
    case 'getNotebook':
      // get info on a notebook
      // if no notebook guid was provided, then exit
      if (event.notebookguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        notebook(event.notebookguid)
          .then(response => callback(null, {tags: response[0], notes: response[1]}))
          .catch(error => callback(error));
      }
     break;
    case 'getNote':
      // get info on a note
      // if no note guid was provided, then exit
      if (event.noteguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        note(event.noteguid)
          .then(response => callback(null, {tags: response[0], note: response[1]}))
          .catch(error => callback(error));
      }
      break;
    default:
    }
  }
}

// exports.handler({
//   'cmd': 'getNote',
//   // 'notebookguid': 'bf0ff626-e6e1-4bcb-bdfd-07f9c318cb76'
//   // 'noteguid': '6b415a9c-2666-4cd8-8be1-0a3d615aca65'
//   'noteguid': 'a969ad1e-1e1a-4ae7-8410-19069fd17c8b'
// });
<commit_msg>removed some old comments<commit_after>'use strict';

let creds = require('./creds.js').creds;
let Promise = require('bluebird');
let evernote = require('./base.js').Evernote;
evernote.Client = require('./client.js').Client;
let enml = require('enml-js');
let authToken;
let client;
let noteStore;

function tagsNotebook(notebookguid) {
  // get tags of notebook
  let prms = Promise.promisify(noteStore.listTagsByNotebook);
  return prms(notebookguid)
}
function count(noteFilter) {
  // get count of notes of notebook
  let prms = Promise.promisify(noteStore.findNoteCounts);
  return prms(noteFilter, false)
}
function listNote(offset, count, noteFilter, notesMetadataResultSpec) {
  // get the guids of notes
  let prms = Promise.promisify(noteStore.findNotesMetadata);
  return prms(noteFilter, offset, count, notesMetadataResultSpec)
}
function listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults) {
  // get as many guids of notes as evernote will return and continue until the end
  return listNote(offset, count, noteFilter, notesMetadataResultSpec)
    .then(response => {
      // add new results to result set
      for (let index = 0; index < response.notes.length; index++) {
        noteResults.push(response.notes[index]);
      }
      if (offset < count) {
        // there are still more notes, continue
        offset += response.notes.length;
        return listMoreNotes(offset, count, noteFilter, notesMetadataResultSpec, noteResults);
      } else {
        return noteResults;
      }
    });
}
function notes(notebookguid) {
  // get note guids of notebook
  let notesMetadataResultSpec = new evernote.NotesMetadataResultSpec;
  notesMetadataResultSpec.includeTitle = true;
  notesMetadataResultSpec.includeContentLength = true;
  notesMetadataResultSpec.includeCreated = true;
  notesMetadataResultSpec.includeUpdated = true;
  notesMetadataResultSpec.includeTagGuids = true;
  let noteFilter = new evernote.NoteFilter;
  noteFilter.notebookGuid = notebookguid;
  noteFilter.ascending = false;
  noteFilter.order = 1;
  let noteResults = [];

  return count(noteFilter)
    .then(response => listMoreNotes(0, response.notebookCounts[notebookguid], noteFilter, notesMetadataResultSpec, noteResults));
}
function notebook(notebookguid) {
  // get tags and note guids of notebook
  return Promise.all([tagsNotebook(notebookguid), notes(notebookguid)])
}
function tagsNote(noteguid) {
  // get tags of note
  let prms = Promise.promisify(noteStore.getNoteTagNames);
  return prms(noteguid);
}
function selectpic(res) {
  // select a usable pic resource
  let lsindex = 0;
  let lsvalue = 0;
  let usableResources = [];

  if (res.resources) {
    // find out which resources have a non-empty sourceUrl
    for (let i = 0; i < res.resources.length; i++) {
      if (res.resources[i].attributes.sourceURL) usableResources.push(res.resources[i]);
    }
    if (usableResources.length > 0) {
      // select a resource using evernote's 'largest-smallest' algorithm
      for (let i = 0; i < usableResources.length; i++) {
        let temp = Math.min(usableResources[i].width, usableResources[i].height);
        if (temp === 0) { continue; }
        if (temp > lsvalue) {
          lsindex = i;
          lsvalue = temp;
        }
      }
      return usableResources[lsindex].attributes.sourceURL;
    } else {
      return '';
    }
  }
}
function notecontent(noteguid) {
  // get content of note
  return new Promise((resolve, reject) => {
    noteStore.getNote(noteguid, true, true, true, true, function(err, note) {
      if (err) { reject(err) }
      else { resolve(enml.HTMLOfENML(note.content, note.resources)) }
    })
  });
}
function note(noteguid) {
  // get tags and content of note of notebook
  return Promise.all([tagsNote(noteguid), notecontent(noteguid)])
}

exports.handler = (event, context, callback) => {
  // if no command was specified, then exit
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else {
    // init evernote api
    authToken = creds.token;
    client = new evernote.Client({
      token: authToken,
      sandbox: false
    });
    noteStore = client.getNoteStore();
    // main switch
    switch (event.cmd) {
    case 'getNotebooks':
      // get all notebooks of the authenticated user
      let prms = Promise.promisify(noteStore.listNotebooks);
      prms(authToken)
        .then(response => callback(null, response))
        .catch(error => callback(error));
      break;
    case 'getNotebook':
      // get info on a notebook
      // if no notebook guid was provided, then exit
      if (event.notebookguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        notebook(event.notebookguid)
          .then(response => callback(null, {tags: response[0], notes: response[1]}))
          .catch(error => callback(error));
      }
     break;
    case 'getNote':
      // get info on a note
      // if no note guid was provided, then exit
      if (event.noteguid === undefined) {
        callback(new Error('Missing notebook guid parameter'))
      } else {
        note(event.noteguid)
          .then(response => callback(null, {tags: response[0], note: response[1]}))
          .catch(error => callback(error));
      }
      break;
    default:
    }
  }
}

// exports.handler({
//   'cmd': 'getNote',
//   // 'notebookguid': 'bf0ff626-e6e1-4bcb-bdfd-07f9c318cb76'
//   // 'noteguid': '6b415a9c-2666-4cd8-8be1-0a3d615aca65'
//   'noteguid': 'a969ad1e-1e1a-4ae7-8410-19069fd17c8b'
// });
<|endoftext|>


<commit_before>// Dependencies
var path = require('path');
var sassLint = require('sass-lint');
var loaderUtils = require('loader-utils');
var assign = require('object-assign');

// Helper Utilities
var formatter = require('./lib/formatter');

/**
 * Linter
 *
 * @param {String|Buffer} input Javascript string
 * @param {Object} config scsslint configuration
 * @param {Object} webpack webpack instance
 * @param {Function} callback optional callback for async loader
 * @return {void}
 */
function lint(input, options, webpack, callback) {
  // Run sassLint
  var report = sassLint.lintText({
    'text': input,
    'format': path.extname(webpack.resourcePath).replace('.',  ''),
    'filename': path.relative(process.cwd(), webpack.resourcePath)
  }, {}, options.configFile);

  if (report.messages.length) {

    if (report.warningCount && options.quiet) {
      report.warningCount = 0;
      report.messages = report.messages
        .filter(function(message) {
          return message.severity !== 1;
        });
    }

    if (report.errorCount || report.warningCount) {
      var messages = formatter(report.messages, webpack.resourcePath);

      // Default emitter behavior
      var emitter = report.errorCount ? webpack.emitError : webpack.emitWarning;

      // Force emitError or emitWarning by setting option
      if (options.emitError) {
        emitter = webpack.emitError;
      } else if (options.emitWarning) {
        emitter = webpack.emitWarning;
      }

      if (emitter) {
        emitter(messages);
        if (options.failOnError && report.errorCount) {
          throw new Error('Module failed because of a sasslint error.\n' + messages);
        } else if (options.failOnWarning && report.warningCount) {
          throw new Error('Module failed because of a sasslint warning.\n' + messages);
        }
      } else {
        throw new Error(
          'Your module system doesn\'t support emitWarning.' +
          'Update available? \n' +
          messages
        );
      }
    }
  }

  if (callback) {
    callback(null, input);
  }
}

/**
 * Webpack Loader
 *
 * @param {String|Buffer} input JavaScript string
 * @returns {String|Buffer} original input
 */
module.exports = function(input) {
  var options = assign(
    {
      configFile: '.scss-lint.yml'
    },
    // User defaults
    this.options.sasslint || {},
    // loader query string
    loaderUtils.parseQuery(this.query)
  );

  this.cacheable();

  var callback = this.async();

  if (!callback) { // sync
    lint(input, options, this);

    return input;
  } else { // async
    try {
      lint(input, options, this, callback);
    } catch(e) {
      callback(e);
    }
  }
};
<commit_msg>Removed some whitespace<commit_after>// Dependencies
var path = require('path');
var sassLint = require('sass-lint');
var loaderUtils = require('loader-utils');
var assign = require('object-assign');

// Helper Utilities
var formatter = require('./lib/formatter');

/**
 * Linter
 *
 * @param {String|Buffer} input Javascript string
 * @param {Object} config scsslint configuration
 * @param {Object} webpack webpack instance
 * @param {Function} callback optional callback for async loader
 * @return {void}
 */
function lint(input, options, webpack, callback) {
  // Run sassLint
  var report = sassLint.lintText({
    'text': input,
    'format': path.extname(webpack.resourcePath).replace('.',  ''),
    'filename': path.relative(process.cwd(), webpack.resourcePath)
  }, {}, options.configFile);

  if (report.messages.length) {

    if (report.warningCount && options.quiet) {
      report.warningCount = 0;
      report.messages = report.messages
        .filter(function(message) {
          return message.severity !== 1;
        });
    }

    if (report.errorCount || report.warningCount) {
      var messages = formatter(report.messages, webpack.resourcePath);

      // Default emitter behavior
      var emitter = report.errorCount ? webpack.emitError : webpack.emitWarning;

      // Force emitError or emitWarning by setting option
      if (options.emitError) {
        emitter = webpack.emitError;
      } else if (options.emitWarning) {
        emitter = webpack.emitWarning;
      }

      if (emitter) {
        emitter(messages);
        if (options.failOnError && report.errorCount) {
          throw new Error('Module failed because of a sasslint error.\n' + messages);
        } else if (options.failOnWarning && report.warningCount) {
          throw new Error('Module failed because of a sasslint warning.\n' + messages);
        }
      } else {
        throw new Error(
          'Your module system doesn\'t support emitWarning.' +
          'Update available? \n' +
          messages
        );
      }
    }
  }

  if (callback) {
    callback(null, input);
  }
}

/**
 * Webpack Loader
 *
 * @param {String|Buffer} input JavaScript string
 * @returns {String|Buffer} original input
 */
module.exports = function(input) {
  var options = assign(
    {
      configFile: '.scss-lint.yml'
    },
    // User defaults
    this.options.sasslint || {},
    // loader query string
    loaderUtils.parseQuery(this.query)
  );

  this.cacheable();

  var callback = this.async();

  if (!callback) { // sync
    lint(input, options, this);
    return input;
  } else { // async
    try {
      lint(input, options, this, callback);
    } catch(e) {
      callback(e);
    }
  }
};
<|endoftext|>