<commit_before>var loaderUtils = require('loader-utils');
var stylus = require('stylus');
var nib = require('nib');
var path = require('path');
var fs = require('fs');

module.exports = function(source) {
  var self = this;
  this.cacheable && this.cacheable();
  var done = this.async();
  var options = loaderUtils.parseQuery(this.query);
  options.filename = options.filename || this.resourcePath;

  var styl = stylus(source);
  var paths = [path.dirname(options.filename)];

  function needsArray(value) {
    return (Array.isArray(value)) ? value : [value];
  }

  if (options.paths && !Array.isArray(options.paths)) {
    paths = paths.concat(options.paths);
    options.paths = [options.paths];
  }

  var manualImports = [];
  Object.keys(options).forEach(function(key) {
    var value = options[key];
    if (key === 'use') {
      needsArray(value).forEach(function(func) {
        if (typeof func === 'function') {
          styl.use(func());
        }
      });
    } else if (key === 'define') {
      for (var defineName in value) {
        styl.define(defineName, value[defineName]);
      }
    } else if (key === 'import') {
      needsArray(value).forEach(function(stylusModule) {
        styl.import(stylusModule);
        manualImports.push(stylusModule);
      });
    } else {
      styl.set(key, value);
    }
  });

  extractImports(source).concat(manualImports).map(function(dep) {
    var filepath = null;
    for (var i = 0; i < paths.length; i++) {
      filepath = path.resolve(paths[i], dep);
      if (!fs.existsSync(filepath)) {
        filepath = path.resolve(paths[i], dep + '.styl');
        if (fs.existsSync(filepath)) break;
      } else {
        break;
      }
    }
    return fs.existsSync(filepath) ? filepath : null;
  }).filter(function(dep) {
    return !!dep;
  }).forEach(function(dep) {
    self.addDependency(dep);
  });

  styl.use(nib());
  styl.render(function(err, css) {
    if (err) done(err);
    else done(null, css);
  });
}

// Not the best way but it works for now
function extractImports(source) {
  var imports = ['invalid'];
  var regex = /@import *[\'|\"]([^\'|\"]+)*/gi;
  var matches = regex.exec(source);
  if (matches) {
    imports.push(matches[1]);
    while (matches != null) {
      matches = regex.exec(source);
      if (matches) imports.push(matches[1]);
    }
  }
  return imports || [];
}
<commit_msg>Remove test code<commit_after>var loaderUtils = require('loader-utils');
var stylus = require('stylus');
var nib = require('nib');
var path = require('path');
var fs = require('fs');

module.exports = function(source) {
  var self = this;
  this.cacheable && this.cacheable();
  var done = this.async();
  var options = loaderUtils.parseQuery(this.query);
  options.filename = options.filename || this.resourcePath;

  var styl = stylus(source);
  var paths = [path.dirname(options.filename)];

  function needsArray(value) {
    return (Array.isArray(value)) ? value : [value];
  }

  if (options.paths && !Array.isArray(options.paths)) {
    paths = paths.concat(options.paths);
    options.paths = [options.paths];
  }

  var manualImports = [];
  Object.keys(options).forEach(function(key) {
    var value = options[key];
    if (key === 'use') {
      needsArray(value).forEach(function(func) {
        if (typeof func === 'function') {
          styl.use(func());
        }
      });
    } else if (key === 'define') {
      for (var defineName in value) {
        styl.define(defineName, value[defineName]);
      }
    } else if (key === 'import') {
      needsArray(value).forEach(function(stylusModule) {
        styl.import(stylusModule);
        manualImports.push(stylusModule);
      });
    } else {
      styl.set(key, value);
    }
  });

  extractImports(source).concat(manualImports).map(function(dep) {
    var filepath = null;
    for (var i = 0; i < paths.length; i++) {
      filepath = path.resolve(paths[i], dep);
      if (!fs.existsSync(filepath)) {
        filepath = path.resolve(paths[i], dep + '.styl');
        if (fs.existsSync(filepath)) break;
      } else {
        break;
      }
    }
    return fs.existsSync(filepath) ? filepath : null;
  }).filter(function(dep) {
    return !!dep;
  }).forEach(function(dep) {
    self.addDependency(dep);
  });

  styl.use(nib());
  styl.render(function(err, css) {
    if (err) done(err);
    else done(null, css);
  });
}

// Not the best way but it works for now
function extractImports(source) {
  var imports = [];
  var regex = /@import *[\'|\"]([^\'|\"]+)*/gi;
  var matches = regex.exec(source);
  if (matches) {
    imports.push(matches[1]);
    while (matches != null) {
      matches = regex.exec(source);
      if (matches) imports.push(matches[1]);
    }
  }
  return imports || [];
}
<|endoftext|>


<commit_before>var findXamlClasses = require(__dirname + '/lib/findXamlClasses'),
    rAppid = require(__dirname + '/rAppid.js'),
    TestRunner = require(__dirname + '/lib/TestRunner');

module.exports = {
    rAppid: rAppid,
    findXamlClasses: findXamlClasses,
    TestRunner: TestRunner,
    require: TestRunner.require
};

<commit_msg>new main module<commit_after>var findXamlClasses = require(__dirname + '/lib/findXamlClasses'),
    rAppid = require(__dirname + '/rAppid.js'),
    flow = require('flow.js').flow,
    TestRunner = require(__dirname + '/lib/TestRunner');

module.exports = {
    rAppid: rAppid,
    findXamlClasses: findXamlClasses,
    TestRunner: TestRunner,
    require: TestRunner.require,
    requireClasses: function(classes, target, done) {

        if (!(classes instanceof Object && target instanceof Object && done instanceof Function)) {
            throw "parameter missing";
        }

        flow()
            .parEach(classes, function(fqClassname, cb) {
                TestRunner.require([fqClassname], function(factory) {
                    cb(null, factory);
                })
            })
            .exec(function (err, results) {
                if (!err) {
                    for (var name in results) {
                        if (results.hasOwnProperty(name)) {
                            target[name] = results[name];
                        }
                    }
                }

                done(err);
            });
    }
};

<|endoftext|>


<commit_before>'use strict';

function extend(a, b) {
  for (var property in b) {
    if (b.hasOwnProperty(property)) {
      a[property] = b[property];
    }
  }

  return a;
}

function distance(s1, s2, options) {
  var m = 0;
  var defaults = { caseSensitive: true };
  var settings = extend(defaults, options);
  var i;
  var j;

  // Exit early if either are empty.
  if (s1.length === 0 || s2.length === 0) {
    return 0;
  }

  // Convert to upper if case-sensitive is false.
  if (!settings.caseSensitive) {
    s1 = s1.toUpperCase();
    s2 = s2.toUpperCase();
  }

  // Exit early if they're an exact match.
  if (s1 === s2) {
    return 1;
  }

  var range = (Math.floor(Math.max(s1.length, s2.length) / 2)) - 1;
  var s1Matches = new Array(s1.length);
  var s2Matches = new Array(s2.length);

  for (i = 0; i < s1.length; i++) {
    var low  = (i >= range) ? i - range : 0;
    var high = (i + range <= s2.length) ? (i + range) : (s2.length - 1);

    for (j = low; j <= high; j++) {
      if (s1Matches[i] !== true && s2Matches[j] !== true && s1[i] === s2[j]) {
        ++m;
        s1Matches[i] = s2Matches[j] = true;
        break;
      }
    }
  }

  // Exit early if no matches were found.
  if (m === 0) {
    return 0;
  }

  // Count the transpositions.
  var k = 0;
  var numTrans = 0;

  for (i = 0; i < s1.length; i++) {
    if (s1Matches[i] === true) {
      for (j = k; j < s2.length; j++) {
        if (s2Matches[j] === true) {
          k = j + 1;
          break;
        }
      }

      if (s1[i] !== s2[j]) {
        ++numTrans;
      }
    }
  }

  var weight = (m / s1.length + m / s2.length + (m - (numTrans / 2)) / m) / 3;
  var l = 0;
  var p = 0.1;

  if (weight > 0.7) {
    while (s1[l] === s2[l] && l < 4) {
      ++l;
    }

    weight = weight + l * p * (1 - weight);
  }

  return weight;
}

module.exports = distance;
<commit_msg>Adds UMD wrapper.<commit_after>'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.distance = factory();
  }
}(this, function () {
  function extend(a, b) {
    for (var property in b) {
      if (b.hasOwnProperty(property)) {
        a[property] = b[property];
      }
    }

    return a;
  }

  function distance(s1, s2, options) {
    var m = 0;
    var defaults = { caseSensitive: true };
    var settings = extend(defaults, options);
    var i;
    var j;

    // Exit early if either are empty.
    if (s1.length === 0 || s2.length === 0) {
      return 0;
    }

    // Convert to upper if case-sensitive is false.
    if (!settings.caseSensitive) {
      s1 = s1.toUpperCase();
      s2 = s2.toUpperCase();
    }

    // Exit early if they're an exact match.
    if (s1 === s2) {
      return 1;
    }

    var range = (Math.floor(Math.max(s1.length, s2.length) / 2)) - 1;
    var s1Matches = new Array(s1.length);
    var s2Matches = new Array(s2.length);

    for (i = 0; i < s1.length; i++) {
      var low  = (i >= range) ? i - range : 0;
      var high = (i + range <= s2.length) ? (i + range) : (s2.length - 1);

      for (j = low; j <= high; j++) {
        if (s1Matches[i] !== true && s2Matches[j] !== true && s1[i] === s2[j]) {
          ++m;
          s1Matches[i] = s2Matches[j] = true;
          break;
        }
      }
    }

    // Exit early if no matches were found.
    if (m === 0) {
      return 0;
    }

    // Count the transpositions.
    var k = 0;
    var numTrans = 0;

    for (i = 0; i < s1.length; i++) {
      if (s1Matches[i] === true) {
        for (j = k; j < s2.length; j++) {
          if (s2Matches[j] === true) {
            k = j + 1;
            break;
          }
        }

        if (s1[i] !== s2[j]) {
          ++numTrans;
        }
      }
    }

    var weight = (m / s1.length + m / s2.length + (m - (numTrans / 2)) / m) / 3;
    var l = 0;
    var p = 0.1;

    if (weight > 0.7) {
      while (s1[l] === s2[l] && l < 4) {
        ++l;
      }

      weight = weight + l * p * (1 - weight);
    }

    return weight;
  }

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


<commit_before>var routes = require('routes');
var EventEmitter = require('events').EventEmitter;
var loc = new (require('location-bar'))();
var noop = function() {};

function router(settings) {

	if( !( this instanceof router ) ) {

		return new router(settings);
	}

	var s = this.s = settings || {};

	s.postHash = s.postHash || '!';

	this.lastRoute = null;
	this.childRouter = null;
	this.childFullRoute = null;
	this.childBaseRoute = null;
	this.router = routes();

	EventEmitter.call(this);
}

var p = router.prototype = Object.create(EventEmitter.prototype);

p.init = function() {

	var s = this.s;
	var i;

	// figure out a start section
	if( s[ '/' ] === undefined ) {

		// find the first path which would be a section
		for(i in s) {

			if( i[ 0 ] == '/' ) {

				s.start = i;

				break;
			}
		}
	} else {

		s.start = '/';
	}

	// now setup routes
	for(i in s) {

		if( i[ 0 ] == '/' || i == '404') {

			this.router.addRoute(i, noop);
		}
	}

	this.onURL = this.onURL.bind(this);

	if( global.location ) {
		loc.start({pushState: this.s.pushState!==undefined ? this.s.pushState : true});
		this.hasPushState = loc.hasPushState();
		loc.onChange(this.onURL);
		loc.loadUrl();
	} else {
		this.onURL();
	}

	return this;
};

p.destroy = function() {

	if(global.location) {
		loc.stop();
	}
};

p.add = function(route, section) {

	var s = this.s;

	s[ route ] = section;

	return this;
};

p.go = function(routeStr,options) {

	var routeData;
	var section;
	var newURL;
	var doURLChange;

	if( routeStr.charAt(0) != '/' ) {
		routeStr = '/' + routeStr;
	}

	newURL = (this.hasPushState ? '' : this.s.postHash) + routeStr;
	routeData = this.getRouteData(routeStr) || this.getRouteData('404');
	section = this.getSection(routeData);
	doURLChange = this.useURL(section);

	// if this is not a section descriptor or it is a descriptor and we should updateURL
	if( global.location && doURLChange ) {
		var url = this.hasPushState ? global.location.pathname : global.location.hash.replace(/^#/, '');
		if(url != newURL) {
			loc.update(newURL,{
				trigger: (options && options.silent) ? false : true,
				replace: (options && options.replace) ? true : false
			});
		} else if(section.duplicate || !section.useURL) {
			// Check if duplicate is set. The check is done here since, onhashchange event triggers
			// only when url changes and therefore cannot check to allow duplicate/repeating route

			// Additionally check if useURL is set to false. If not, the route is not triggered by
			// url changes
			this.doRoute(routeData, section, routeStr);
		}
	} else if( !global.location || !doURLChange ) {
		this.doRoute(routeData, section, routeStr);
	}
};

p.doRoute = function(routeData, section, path) {

	var s = this.s;

	// check if this is a redirect
	if( typeof section == 'string' ) {

		this.go(section);
	} else {

		if(routeData.route !== this.lastResolvedRoute || section.duplicate) {

			this.lastResolvedRoute = routeData.route;

			// otherwise treat it as a regular section
			// if this is a object definition vs a section definition (regular section or array)
			this.emit('route', {
				section: section,
				route: routeData,
				path: path
			});
		}
	}
};

p.getRouteData = function(routeStr) {

	var routeData = this.router.match(routeStr);

	if(routeData) {
		this.lastRoute = routeData.route;
	}

	return routeData;
};

p.getSection = function(routeData) {

	if(routeData) {
		var hasWildcard = routeData.route && (routeData.route.match(/.*[\[\]@!$&:'()*+,;=].*/g) || routeData.route instanceof RegExp);
		var sec = this.s[ routeData.route ];
		if (hasWildcard && sec.duplicate===undefined) {
			if (!sec.section) {
				return {section: sec, duplicate: true};
			} else {
				sec.duplicate = true;
				return sec;
			}
		}	else {
			return sec;
		}
	} else {

		return null;
	}
};

p.useURL = function(section) {

	return section &&
		   ( section.section === undefined ||  // if this is not a section descriptor update url
		   ( section.section && section.useURL || section.useURL === undefined ) ); //is descriptor and has useURL or undefined
};

p.onURL = function(url) {
	var routeStr = '/';
	var routeData;
	var section;

	if( global.location && url!==undefined && url!==null ) {

		if (url.charAt(0) != '/') url = '/' + url;
		// if we've already looked at this url then just get out of this function
		if(url === this.resolved) {
			return;
		}

		this.resolved = url;
		routeStr = (this.hasPushState || url.length<2) ? url : url.substr(1 + this.s.postHash.length);
	}

	routeData = this.getRouteData(routeStr) || this.getRouteData('404');
	section = this.getSection(routeData);

	// see if we can deep link into this section (either normal or 404 section)
	if( this.useURL(section) ) {
		this.doRoute(routeData, section, routeStr);
	// else check if there's a 404 if so then go there
	} else if( this.s['404'] ){

		routeData = this.getRouteData('404');
		section = this.getSection(routeData);
		this.doRoute(routeData, section, routeStr);
	}
};

module.exports = router;<commit_msg>Added root path support<commit_after>var routes = require('routes');
var EventEmitter = require('events').EventEmitter;
var loc = new (require('location-bar'))();
var noop = function() {};

function router(settings) {

	if( !( this instanceof router ) ) {

		return new router(settings);
	}

	var s = this.s = settings || {};

	s.postHash = s.postHash || '!';

	this.lastRoute = null;
	this.childRouter = null;
	this.childFullRoute = null;
	this.childBaseRoute = null;
	this.router = routes();

	EventEmitter.call(this);
}

var p = router.prototype = Object.create(EventEmitter.prototype);

p.init = function() {

	var s = this.s;
	var i;

	// figure out a start section
	if( s[ '/' ] === undefined ) {

		// find the first path which would be a section
		for(i in s) {

			if( i[ 0 ] == '/' ) {

				s.start = i;

				break;
			}
		}
	} else {

		s.start = '/';
	}

	// now setup routes
	for(i in s) {

		if( i[ 0 ] == '/' || i == '404') {

			this.router.addRoute(i, noop);
		}
	}

	this.onURL = this.onURL.bind(this);

	if( global.location ) {
		loc.start({pushState: this.s.pushState!==undefined ? this.s.pushState : true, root: this.s.root || '/'});
		this.hasPushState = loc.hasPushState();
		loc.onChange(this.onURL);
		loc.loadUrl();
	} else {
		this.onURL();
	}

	return this;
};

p.destroy = function() {

	if(global.location) {
		loc.stop();
	}
};

p.add = function(route, section) {

	var s = this.s;

	s[ route ] = section;

	return this;
};

p.go = function(routeStr,options) {

	var routeData;
	var section;
	var newURL;
	var doURLChange;

	if( routeStr.charAt(0) != '/' ) {
		routeStr = '/' + routeStr;
	}

	newURL = (this.hasPushState ? '' : this.s.postHash) + routeStr;
	routeData = this.getRouteData(routeStr) || this.getRouteData('404');
	section = this.getSection(routeData);
	doURLChange = this.useURL(section);

	// if this is not a section descriptor or it is a descriptor and we should updateURL
	if( global.location && doURLChange ) {
		var url = this.hasPushState ? global.location.pathname : global.location.hash.replace(/^#/, '');
		if(url != newURL) {
			loc.update(newURL,{
				trigger: (options && options.silent) ? false : true,
				replace: (options && options.replace) ? true : false
			});
		} else if(section.duplicate || !section.useURL) {
			// Check if duplicate is set. The check is done here since, onhashchange event triggers
			// only when url changes and therefore cannot check to allow duplicate/repeating route

			// Additionally check if useURL is set to false. If not, the route is not triggered by
			// url changes
			this.doRoute(routeData, section, routeStr);
		}
	} else if( !global.location || !doURLChange ) {
		this.doRoute(routeData, section, routeStr);
	}
};

p.doRoute = function(routeData, section, path) {

	var s = this.s;

	// check if this is a redirect
	if( typeof section == 'string' ) {

		this.go(section);
	} else {

		if(routeData.route !== this.lastResolvedRoute || section.duplicate) {

			this.lastResolvedRoute = routeData.route;

			// otherwise treat it as a regular section
			// if this is a object definition vs a section definition (regular section or array)
			this.emit('route', {
				section: section,
				route: routeData,
				path: path
			});
		}
	}
};

p.getRouteData = function(routeStr) {

	var routeData = this.router.match(routeStr);

	if(routeData) {
		this.lastRoute = routeData.route;
	}

	return routeData;
};

p.getSection = function(routeData) {

	if(routeData) {
		var hasWildcard = routeData.route && (routeData.route.match(/.*[\[\]@!$&:'()*+,;=].*/g) || routeData.route instanceof RegExp);
		var sec = this.s[ routeData.route ];
		if (hasWildcard && sec.duplicate===undefined) {
			if (!sec.section) {
				return {section: sec, duplicate: true};
			} else {
				sec.duplicate = true;
				return sec;
			}
		}	else {
			return sec;
		}
	} else {

		return null;
	}
};

p.useURL = function(section) {

	return section &&
		   ( section.section === undefined ||  // if this is not a section descriptor update url
		   ( section.section && section.useURL || section.useURL === undefined ) ); //is descriptor and has useURL or undefined
};

p.onURL = function(url) {
	var routeStr = '/';
	var routeData;
	var section;

	if( global.location && url!==undefined && url!==null ) {

		if (url.charAt(0) != '/') url = '/' + url;
		// if we've already looked at this url then just get out of this function
		if(url === this.resolved) {
			return;
		}

		this.resolved = url;
		routeStr = (this.hasPushState || url.length<2) ? url : url.substr(1 + this.s.postHash.length);
	}

	routeData = this.getRouteData(routeStr) || this.getRouteData('404');
	section = this.getSection(routeData);

	// see if we can deep link into this section (either normal or 404 section)
	if( this.useURL(section) ) {
		this.doRoute(routeData, section, routeStr);
	// else check if there's a 404 if so then go there
	} else if( this.s['404'] ){

		routeData = this.getRouteData('404');
		section = this.getSection(routeData);
		this.doRoute(routeData, section, routeStr);
	}
};

module.exports = router;<|endoftext|>


<commit_before>import Future from 'fibers/future'
import Fiber from 'fibers'

const SYNC_COMMANDS = ['domain', '_events', '_maxListeners', 'setMaxListeners', 'emit',
    'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'listeners']

let commandIsRunning = false

/**
 * helper method to execute a row of hooks with certain parameters
 * @param  {Function|Function[]} hooks  list of hooks
 * @param  {Object[]} args  list of parameter for hook functions
 * @return {Promise}  promise that gets resolved once all hooks finished running
 */
let executeHooksWithArgs = (hooks, args) => {
    /**
     * make sure hooks are an array of functions
     */
    if (typeof hooks === 'function') {
        hooks = [hooks]
    }

    /**
     * make sure args is an array since we are calling apply
     */
    if (!Array.isArray(args)) {
        args = [args]
    }

    hooks = hooks.map((hook) => new Promise((resolve) => {
        let _commandIsRunning = commandIsRunning
        try {
            /**
             * after command hooks require additional Fiber environment
             */
            return Fiber(() => {
                commandIsRunning = true
                resolve(hook.apply(null, args))
                commandIsRunning = _commandIsRunning
            }).run()
        } catch (e) {
            console.error(e.stack)
        }

        resolve()
    }))

    return Promise.all(hooks)
}

/**
 * global function to wrap callbacks into Fiber context
 * @param  {Function} fn  function to wrap around
 * @return {Function}     wrapped around function
 */
global.wdioSync = function (fn) {
    return function (...args) {
        return Fiber(() => {
            fn.apply(this, args)
        }).run()
    }
}

/**
 * wraps a function into a Fiber ready context to enable sync execution and hooks
 * @param  {Function}   fn             function to be executed
 * @param  {String}     commandName    name of that function
 * @param  {Function[]} beforeCommand  method to be executed before calling the actual function
 * @param  {Function[]} afterCommand   method to be executed after calling the actual function
 * @return {Function}   actual wrapped function
 */
let wrapCommand = function (fn, commandName, beforeCommand, afterCommand) {
    return function (...commandArgs) {
        let future = new Future()
        let futureFailed = false

        /**
         * don't execute [before/after]Command hook if a command was executed
         * in these hooks
         */
        if (commandIsRunning) {
            let commandPromise = fn.apply(this, commandArgs)

            /**
             * try to execute with Fibers and fall back if can't
             */
            try {
                commandPromise.then(future.return.bind(future), future.throw.bind(future))
                return future.wait()
            } catch (e) {
                return commandIsRunning
            }
        }

        commandIsRunning = true
        let commandResult, commandError
        new Promise((r) => r(beforeCommand(commandName, commandArgs)))
            .then(() => {
                /**
                 * actual function was already executed in desired catch block
                 */
                if (futureFailed) {
                    return
                }

                return fn.apply(this, commandArgs)
            })
            .then(
                (result) => {
                    commandResult = result
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, result])
                },
                (e) => {
                    commandError = e
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, null, e])
                }
            )
            .then(() => {
                commandIsRunning = false

                if (commandError) {
                    return future.throw(commandError)
                }
                return future.return(commandResult)
            })

        /**
         * try to execute with Fibers and fall back if can't
         */
        try {
            return future.wait()
        } catch (e) {
            futureFailed = true
            return fn.apply(this, commandArgs)
        }
    }
}

/**
 * wraps all WebdriverIO commands
 * @param  {Object}     instance       WebdriverIO client instance (browser)
 * @param  {Function[]} beforeCommand  before command hook
 * @param  {Function[]} afterCommand   after command hook
 */
let wrapCommands = function (instance, beforeCommand, afterCommand) {
    Object.keys(Object.getPrototypeOf(instance)).forEach((commandName) => {
        if (SYNC_COMMANDS.indexOf(commandName) > -1) {
            return
        }

        let origFn = instance[commandName]
        instance[commandName] = wrapCommand(origFn, commandName, beforeCommand, afterCommand)
    })

    /**
     * Adding a command within fiber context doesn't require a special routine
     * since everything runs sync. There is no need to promisify the command.
     */
    instance.addCommand = function (fnName, fn, forceOverwrite) {
        let commandGroup = instance
        let namespace

        if (typeof fn === 'string') {
            namespace = arguments[0]
            fnName = arguments[1]
            fn = arguments[2]
            forceOverwrite = arguments[3]

            switch (typeof commandGroup[namespace]) {
            case 'function':
                throw new Error(`Command namespace "${namespace}" is used internally, and can't be overwritten!`)
            case 'undefined':
                commandGroup[namespace] = {}
                break
            }

            commandGroup = commandGroup[namespace]
        }

        if (commandGroup[fnName] && !forceOverwrite) {
            throw new Error(`Command ${fnName} is already defined!`)
        }

        commandGroup[fnName] = wrapCommand(fn, fnName, beforeCommand, afterCommand)
    }
}

/**
 * [runInFiberContext description]
 * @param  {[type]} testInterfaceFnName  global command that runs specs
 * @param  {[type]} before               before hook hook
 * @param  {[type]} after                after hook hook
 * @param  {[type]} fnName               test interface command to wrap
 */
let runInFiberContext = function (testInterfaceFnName, before, after, fnName) {
    let origFn = global[fnName]

    let runSpec = function (specTitle, specFn) {
        return origFn(specTitle, function (done) {
            Fiber(() => {
                specFn.call(this)
                done()
            }).run()
        })
    }

    let runHook = function (hookFn) {
        return origFn(function (done) {
            Fiber(() => {
                executeHooksWithArgs(before)
                    .then(() => hookFn.call(this))
                    .then(() => executeHooksWithArgs(after))
                    .then(() => done(), () => done())
            }).run()
        })
    }

    global[fnName] = function (...specArguments) {
        let specFn = typeof specArguments[0] === 'function' ? specArguments.shift() : specArguments.pop()
        let specTitle = specArguments[0]

        /**
         * if specFn is undefined we are dealing with a pending function
         */
        if (fnName === testInterfaceFnName && arguments.length === 1) {
            return origFn(specTitle)
        }

        if (fnName === testInterfaceFnName) {
            return runSpec(specTitle, specFn)
        }

        return runHook(specFn)
    }

    if (fnName === testInterfaceFnName) {
        global[fnName].skip = origFn.skip
        global[fnName].only = origFn.only
    }
}

export { wrapCommand, wrapCommands, runInFiberContext, executeHooksWithArgs }
<commit_msg>run also beforeCommand hook using executeHooksWithArgs<commit_after>import Future from 'fibers/future'
import Fiber from 'fibers'

const SYNC_COMMANDS = ['domain', '_events', '_maxListeners', 'setMaxListeners', 'emit',
    'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'listeners']

let commandIsRunning = false

/**
 * helper method to execute a row of hooks with certain parameters
 * @param  {Function|Function[]} hooks  list of hooks
 * @param  {Object[]} args  list of parameter for hook functions
 * @return {Promise}  promise that gets resolved once all hooks finished running
 */
let executeHooksWithArgs = (hooks, args) => {
    /**
     * make sure hooks are an array of functions
     */
    if (typeof hooks === 'function') {
        hooks = [hooks]
    }

    /**
     * make sure args is an array since we are calling apply
     */
    if (!Array.isArray(args)) {
        args = [args]
    }

    hooks = hooks.map((hook) => new Promise((resolve) => {
        let _commandIsRunning = commandIsRunning
        try {
            /**
             * after command hooks require additional Fiber environment
             */
            return Fiber(() => {
                commandIsRunning = true
                resolve(hook.apply(null, args))
                commandIsRunning = _commandIsRunning
            }).run()
        } catch (e) {
            console.error(e.stack)
        }

        resolve()
    }))

    return Promise.all(hooks)
}

/**
 * global function to wrap callbacks into Fiber context
 * @param  {Function} fn  function to wrap around
 * @return {Function}     wrapped around function
 */
global.wdioSync = function (fn) {
    return function (...args) {
        return Fiber(() => {
            fn.apply(this, args)
        }).run()
    }
}

/**
 * wraps a function into a Fiber ready context to enable sync execution and hooks
 * @param  {Function}   fn             function to be executed
 * @param  {String}     commandName    name of that function
 * @param  {Function[]} beforeCommand  method to be executed before calling the actual function
 * @param  {Function[]} afterCommand   method to be executed after calling the actual function
 * @return {Function}   actual wrapped function
 */
let wrapCommand = function (fn, commandName, beforeCommand, afterCommand) {
    return function (...commandArgs) {
        let future = new Future()
        let futureFailed = false

        /**
         * don't execute [before/after]Command hook if a command was executed
         * in these hooks
         */
        if (commandIsRunning) {
            let commandPromise = fn.apply(this, commandArgs)

            /**
             * try to execute with Fibers and fall back if can't
             */
            try {
                commandPromise.then(future.return.bind(future), future.throw.bind(future))
                return future.wait()
            } catch (e) {
                return commandIsRunning
            }
        }

        commandIsRunning = true
        let commandResult, commandError
        new Promise((r) => r(executeHooksWithArgs(beforeCommand, [commandName, commandArgs])))
            .then(() => {
                /**
                 * actual function was already executed in desired catch block
                 */
                if (futureFailed) {
                    return
                }

                return fn.apply(this, commandArgs)
            })
            .then(
                (result) => {
                    commandResult = result
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, result])
                },
                (e) => {
                    commandError = e
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, null, e])
                }
            )
            .then(() => {
                commandIsRunning = false

                if (commandError) {
                    return future.throw(commandError)
                }
                return future.return(commandResult)
            })

        /**
         * try to execute with Fibers and fall back if can't
         */
        try {
            return future.wait()
        } catch (e) {
            futureFailed = true
            return fn.apply(this, commandArgs)
        }
    }
}

/**
 * wraps all WebdriverIO commands
 * @param  {Object}     instance       WebdriverIO client instance (browser)
 * @param  {Function[]} beforeCommand  before command hook
 * @param  {Function[]} afterCommand   after command hook
 */
let wrapCommands = function (instance, beforeCommand, afterCommand) {
    Object.keys(Object.getPrototypeOf(instance)).forEach((commandName) => {
        if (SYNC_COMMANDS.indexOf(commandName) > -1) {
            return
        }

        let origFn = instance[commandName]
        instance[commandName] = wrapCommand(origFn, commandName, beforeCommand, afterCommand)
    })

    /**
     * Adding a command within fiber context doesn't require a special routine
     * since everything runs sync. There is no need to promisify the command.
     */
    instance.addCommand = function (fnName, fn, forceOverwrite) {
        let commandGroup = instance
        let namespace

        if (typeof fn === 'string') {
            namespace = arguments[0]
            fnName = arguments[1]
            fn = arguments[2]
            forceOverwrite = arguments[3]

            switch (typeof commandGroup[namespace]) {
            case 'function':
                throw new Error(`Command namespace "${namespace}" is used internally, and can't be overwritten!`)
            case 'undefined':
                commandGroup[namespace] = {}
                break
            }

            commandGroup = commandGroup[namespace]
        }

        if (commandGroup[fnName] && !forceOverwrite) {
            throw new Error(`Command ${fnName} is already defined!`)
        }

        commandGroup[fnName] = wrapCommand(fn, fnName, beforeCommand, afterCommand)
    }
}

/**
 * [runInFiberContext description]
 * @param  {[type]} testInterfaceFnName  global command that runs specs
 * @param  {[type]} before               before hook hook
 * @param  {[type]} after                after hook hook
 * @param  {[type]} fnName               test interface command to wrap
 */
let runInFiberContext = function (testInterfaceFnName, before, after, fnName) {
    let origFn = global[fnName]

    let runSpec = function (specTitle, specFn) {
        return origFn(specTitle, function (done) {
            Fiber(() => {
                specFn.call(this)
                done()
            }).run()
        })
    }

    let runHook = function (hookFn) {
        return origFn(function (done) {
            Fiber(() => {
                executeHooksWithArgs(before)
                    .then(() => hookFn.call(this))
                    .then(() => executeHooksWithArgs(after))
                    .then(() => done(), () => done())
            }).run()
        })
    }

    global[fnName] = function (...specArguments) {
        let specFn = typeof specArguments[0] === 'function' ? specArguments.shift() : specArguments.pop()
        let specTitle = specArguments[0]

        /**
         * if specFn is undefined we are dealing with a pending function
         */
        if (fnName === testInterfaceFnName && arguments.length === 1) {
            return origFn(specTitle)
        }

        if (fnName === testInterfaceFnName) {
            return runSpec(specTitle, specFn)
        }

        return runHook(specFn)
    }

    if (fnName === testInterfaceFnName) {
        global[fnName].skip = origFn.skip
        global[fnName].only = origFn.only
    }
}

export { wrapCommand, wrapCommands, runInFiberContext, executeHooksWithArgs }
<|endoftext|>


<commit_before>'use strict';

const fetch = require('node-fetch');
const chalk = require('chalk');
const zeroPad = require('zero-pad');
const argv = require('minimist')(process.argv.slice(2));

const log = console.log;

// Set a default limit to 5.
if (!argv.l) {
    argv.l = 5;
}

function getDate() {
    const d = new Date();

    const date = zeroPad([
        d.getDate(),
        d.getMonth() + 1,
        d.getFullYear()
    ]).join('.');

    const time = zeroPad([
        d.getHours(),
        d.getMinutes(),
        d.getSeconds()
    ]).join(':');

    return date + ' ' + time;
}

function handleResponse(item, key) {
    if (key !== 0) {
        log('\n');
    }

    if (argv.l && +argv.l === key) {
        return true;
    }

    const {
        title,
        published,
        persistentUrl,
        preamble
    } = item;

    log(' ' + chalk.bold(title));
    log(' ' + chalk.dim(published.niceformat + ' - ' + persistentUrl));
    log(' ' + preamble);
}

function header() {
    return '\n ' + chalk.white.bgRed.bold(` VG.no - https://www.vg.no - ${getDate()} `) + ' \n';
}

function footer() {
    return "\n " + chalk.white.bgBlack.bold(` Ans. redaktør og adm. direktør: Gard Steiro `) + " \n";
}

async function main() {
    const data = await fetch('https://www.vg.no/rss/feed/?format=json');
    const json = await data.json();

    log(header());

    json.some(handleResponse);

    log(footer());
}

try {
    main();
} catch (e) {
    console.error('Something happened. Please try again.');
    console.error(e);
}
<commit_msg>use single quotes<commit_after>'use strict';

const fetch = require('node-fetch');
const chalk = require('chalk');
const zeroPad = require('zero-pad');
const argv = require('minimist')(process.argv.slice(2));

const log = console.log;

// Set a default limit to 5.
if (!argv.l) {
    argv.l = 5;
}

function getDate() {
    const d = new Date();

    const date = zeroPad([
        d.getDate(),
        d.getMonth() + 1,
        d.getFullYear()
    ]).join('.');

    const time = zeroPad([
        d.getHours(),
        d.getMinutes(),
        d.getSeconds()
    ]).join(':');

    return date + ' ' + time;
}

function handleResponse(item, key) {
    if (key !== 0) {
        log('\n');
    }

    if (argv.l && +argv.l === key) {
        return true;
    }

    const {
        title,
        published,
        persistentUrl,
        preamble
    } = item;

    log(' ' + chalk.bold(title));
    log(' ' + chalk.dim(published.niceformat + ' - ' + persistentUrl));
    log(' ' + preamble);
}

function header() {
    return '\n ' + chalk.white.bgRed.bold(` VG.no - https://www.vg.no - ${getDate()} `) + ' \n';
}

function footer() {
    return '\n ' + chalk.white.bgBlack.bold(' Ans. redaktør og adm. direktør: Gard Steiro ') + ' \n';
}

async function main() {
    const data = await fetch('https://www.vg.no/rss/feed/?format=json');
    const json = await data.json();

    log(header());

    json.some(handleResponse);

    log(footer());
}

try {
    main();
} catch (e) {
    console.error('Something happened. Please try again.');
    console.error(e);
}
<|endoftext|>


<commit_before>'use strict'

// pickup - transform RSS or Atom XML to JSON

exports = module.exports = Pickup

const attribute = require('./lib/attribute')
const debug = require('util').debuglog('pickup')
const mappings = require('./lib/mappings')
const os = require('os')
const sax = require('saxes')
const util = require('util')
const { StringDecoder } = require('string_decoder')
const { Transform } = require('readable-stream')

function Entry (
  author,
  duration,
  enclosure,
  id,
  image,
  link,
  originalURL,
  subtitle,
  summary,
  title,
  updated,
  url
) {
  this.author = author
  this.duration = duration
  this.enclosure = enclosure
  this.id = id
  this.image = image
  this.link = link
  this.originalURL = originalURL
  this.subtitle = subtitle
  this.summary = summary
  this.title = title
  this.updated = updated
  this.url = url
}

function Feed (
  author,
  copyright,
  id,
  image,
  language,
  link,
  originalURL,
  payment,
  subtitle,
  summary,
  title,
  ttl,
  updated,
  url
) {
  this.author = author
  this.copyright = copyright
  this.id = id
  this.image = image
  this.language = language
  this.link = link
  this.originalURL = originalURL
  this.payment = payment
  this.subtitle = subtitle
  this.summary = summary
  this.title = title
  this.ttl = ttl
  this.updated = updated
  this.url = url
}

function State (entry, feed, image, map, name, precedence) {
  this.entry = entry
  this.feed = feed
  this.image = image
  this.map = map
  this.name = name
  this.precedence = precedence
}

State.prototype.setName = function (name) {
  this.map = mappings[name] || this.map
  this.name = name
}

State.prototype.key = function () {
  return this.map.get(this.name)
}

State.prototype.takesPrecedence = function () {
  return this.precedence.has(this.name)
}

function OpenHandlers (t) {
  this.channel = t.feedopen
  this.feed = t.feedopen
  this.item = t.entryopen
  this.entry = t.entryopen
  this.image = t.imageopen
}

function CloseHandlers (t) {
  this.channel = t.feedclose
  this.feed = t.feedclose
  this.item = t.entryclose
  this.entry = t.entryclose
  this.image = t.imageclose
}

function encodingFromString (str) {
  if (str.match(/utf-8/i)) {
    return 'utf8'
  } else if (str.match(/iso-8859-1/i)) {
    return 'binary'
  }
  return 'utf8'
}

function encodingFromOpts (opts) {
  const str = opts ? opts.charset : null
  if (typeof str !== 'string') return null
  return encodingFromString(str)
}

util.inherits(Pickup, Transform)
function Pickup (opts) {
  if (!(this instanceof Pickup)) return new Pickup(opts)
  Transform.call(this, opts)

  if (!Pickup.openHandlers) {
    Pickup.openHandlers = new OpenHandlers(Pickup.prototype)
    Pickup.closeHandlers = new CloseHandlers(Pickup.prototype)
  }

  this.encoding = encodingFromOpts(opts)
  this.decoder = new StringDecoder(this.encoding)

  this.eventMode = opts && opts.eventMode

  this.state = new State(
    null,
    null,
    false,
    new Map(),
    '',
    new Set(['content:encoded', 'pubDate'])
  )

  const parser = new sax.SaxesParser(opts ? opts.parser : null)

  parser.ontext = (t) => {
    const state = this.state
    const current = state.entry || state.feed
    if (!current || !state.map) return

    let key = state.key()
    if (key === undefined) return

    if (state.image && state.name === 'url') key = 'image'

    const isSet = current[key] !== undefined

    if (isSet) {
      if (!state.takesPrecedence()) {
        return
      } else if (state.name === 'content:encoded' && t.length > 4096) {
        return
      }
    }

    current[key] = t
  }

  parser.oncdata = (d) => {
    parser.ontext(d)
  }

  parser.onerror = (er) => {
    debug('error: %s', er)

    this.emit('error', er)
  }

  const handle = (name, handlers) => {
    if (handlers.hasOwnProperty(name)) {
      handlers[name].apply(this)
    }
  }

  parser.onopentag = (node) => {
    this.state.setName(node.name)
    handle(node.name, Pickup.openHandlers)

    const current = this.state.entry || this.state.feed

    if (current) {
      const key = this.state.key(node.name)

      if (key) {
        const keys = Object.keys(node.attributes)

        if (keys.length) {
          const kv = attribute(key, node.attributes, current)

          if (kv) {
            current[kv[0]] = kv[1]
          }
        }
      }
    }
  }

  parser.onclosetag = (node) => {
    handle(node.name, Pickup.closeHandlers)
    this.state.setName()
  }

  this.parser = parser
}

Pickup.prototype.objectMode = function () {
  return this._readableState.objectMode
}

Pickup.prototype.feedopen = function () {
  this.state.feed = new Feed()
}

Pickup.prototype.entryopen = function () {
  this.state.entry = new Entry()
}

Pickup.prototype.imageopen = function () {
  this.state.image = true
}

Pickup.prototype.entryclose = function () {
  const entry = this.state.entry
  if (!entry) return

  debug('entry: %o', entry)

  if (!this.eventMode) {
    if (this.objectMode()) {
      this.push(entry)
    } else {
      this.push(JSON.stringify(entry) + os.EOL)
    }
  } else {
    this.emit('entry', entry)
  }

  this.state.entry = null
}

Pickup.prototype.feedclose = function () {
  const feed = this.state.feed
  if (!feed) return

  debug('feed: %O', feed)

  if (!this.eventMode) {
    if (this.objectMode()) {
      this.push(feed)
    } else {
      this.push(JSON.stringify(feed) + os.EOL)
    }
  } else {
    this.emit('feed', feed)
  }

  this.state.feed = null
}

Pickup.prototype.imageclose = function () {
  this.state.image = false
}

function free (parser) {
  parser.oncdata = null
  parser.onclosetag = null
  parser.onopentag = null
  parser.ontext = null
}

Pickup.prototype._flush = function (cb) {
  this.parser.close()
  free(this.parser)

  this._decoder = null

  this.encoding = null
  this.parser = null

  this.state = null

  cb()
}

function cribEncoding (str) {
  const enc = str.split('encoding')[1]
  const def = 'utf8'
  if (!enc) return def

  if (enc.trim()[0] === '=') {
    return encodingFromString(enc)
  }

  return def
}

Pickup.prototype._transform = function (chunk, enc, cb) {
  if (!this._decoder) {
    if (!this.encoding) {
      // This, of course, fails--yielding 'utf8'--if the first chunk is too
      // short to contain the encoding tag.
      const t = chunk.toString('ascii', 0, 128)

      this.encoding = cribEncoding(t)
    }

    this.emit('encoding', this.encoding)
  }

  const str = this.decoder.write(chunk)

  this.parser.write(str)

  cb()
}

// Exports

exports.Pickup = Pickup
exports.Feed = Feed
exports.Entry = Entry

// Extending surface area for testing.

if (process.mainModule.filename.match(/test/) !== null) {
  exports.extend = function (origin, add) {
    return Object.assign(origin, add || Object.create(null))
  }

  exports.entry = function (obj) {
    return exports.extend(new Entry(), obj)
  }

  exports.feed = function (obj) {
    return exports.extend(new Feed(), obj)
  }

  exports.cribEncoding = cribEncoding

  exports.EVENTS = [
    'data',
    'drain',
    'readable',
    'end',
    'entry',
    'error',
    'feed',
    'finish'
  ]
}
<commit_msg>Trim text and cdata<commit_after>'use strict'

// pickup - transform RSS or Atom XML to JSON

exports = module.exports = Pickup

const attribute = require('./lib/attribute')
const mappings = require('./lib/mappings')
const os = require('os')
const sax = require('saxes')
const { debuglog, inherits } = require('util')
const { StringDecoder } = require('string_decoder')
const { Transform } = require('readable-stream')

const debug = debuglog('pickup')

function Entry (
  author,
  duration,
  enclosure,
  id,
  image,
  link,
  originalURL,
  subtitle,
  summary,
  title,
  updated,
  url
) {
  this.author = author
  this.duration = duration
  this.enclosure = enclosure
  this.id = id
  this.image = image
  this.link = link
  this.originalURL = originalURL
  this.subtitle = subtitle
  this.summary = summary
  this.title = title
  this.updated = updated
  this.url = url
}

function Feed (
  author,
  copyright,
  id,
  image,
  language,
  link,
  originalURL,
  payment,
  subtitle,
  summary,
  title,
  ttl,
  updated,
  url
) {
  this.author = author
  this.copyright = copyright
  this.id = id
  this.image = image
  this.language = language
  this.link = link
  this.originalURL = originalURL
  this.payment = payment
  this.subtitle = subtitle
  this.summary = summary
  this.title = title
  this.ttl = ttl
  this.updated = updated
  this.url = url
}

function State (entry, feed, image, map, name, precedence) {
  this.entry = entry
  this.feed = feed
  this.image = image
  this.map = map
  this.name = name
  this.precedence = precedence
}

State.prototype.setName = function (name) {
  this.map = mappings[name] || this.map
  this.name = name
}

State.prototype.key = function () {
  return this.map.get(this.name)
}

State.prototype.takesPrecedence = function () {
  return this.precedence.has(this.name)
}

function OpenHandlers (t) {
  this.channel = t.feedopen
  this.feed = t.feedopen
  this.item = t.entryopen
  this.entry = t.entryopen
  this.image = t.imageopen
}

function CloseHandlers (t) {
  this.channel = t.feedclose
  this.feed = t.feedclose
  this.item = t.entryclose
  this.entry = t.entryclose
  this.image = t.imageclose
}

function encodingFromString (str) {
  if (str.match(/utf-8/i)) {
    return 'utf8'
  } else if (str.match(/iso-8859-1/i)) {
    return 'binary'
  }
  return 'utf8'
}

function encodingFromOpts (opts) {
  const str = opts ? opts.charset : null
  if (typeof str !== 'string') return null
  return encodingFromString(str)
}

function Pickup (opts) {
  if (!(this instanceof Pickup)) return new Pickup(opts)
  Transform.call(this, opts)

  if (!Pickup.openHandlers) {
    Pickup.openHandlers = new OpenHandlers(Pickup.prototype)
    Pickup.closeHandlers = new CloseHandlers(Pickup.prototype)
  }

  this.encoding = encodingFromOpts(opts)
  this.decoder = new StringDecoder(this.encoding)

  this.eventMode = opts && opts.eventMode

  this.state = new State(
    null,
    null,
    false,
    new Map(),
    '',
    new Set(['content:encoded', 'pubDate'])
  )

  const parser = new sax.SaxesParser(opts ? opts.parser : null)

  parser.ontext = (t) => {
    const state = this.state
    const current = state.entry || state.feed

    if (!current || !state.map) return

    let key = state.key()

    if (key === undefined) return

    if (state.image && state.name === 'url') key = 'image'

    const isSet = current[key] !== undefined

    const trimmed = t.trim()

    if (trimmed.length === 0) {
      debug('%s: discarding text: whitespace', state.name)
      return
    }

    if (isSet) {
      if (!state.takesPrecedence()) {
        return
      } else if (state.name === 'content:encoded' && t.length > 4096) {
        debug('%s: discarding text: too long', state.name)
        return
      }

      debug('%s: taking precedence: ( %s, %s )', state.name, key, t)
    }

    current[key] = t
  }

  // Not differentiating between cdata and text, whichever comes first wins.
  // This might be a mistake, but I don’t see a clear-cut alternative.

  parser.oncdata = parser.ontext

  parser.onerror = (er) => {
    debug('error: %s', er)

    this.emit('error', er)
  }

  const handle = (name, handlers) => {
    if (handlers.hasOwnProperty(name)) {
      handlers[name].apply(this)
    }
  }

  parser.onopentag = (node) => {
    this.state.setName(node.name)
    handle(node.name, Pickup.openHandlers)

    const current = this.state.entry || this.state.feed

    if (current) {
      const key = this.state.key(node.name)

      if (key) {
        const keys = Object.keys(node.attributes)

        if (keys.length) {
          const kv = attribute(key, node.attributes, current)

          if (kv) {
            current[kv[0]] = kv[1]
          }
        }
      }
    }
  }

  parser.onclosetag = (node) => {
    handle(node.name, Pickup.closeHandlers)
    this.state.setName()
  }

  this.parser = parser
}

inherits(Pickup, Transform)

Pickup.prototype.objectMode = function () {
  return this._readableState.objectMode
}

Pickup.prototype.feedopen = function () {
  this.state.feed = new Feed()
}

Pickup.prototype.entryopen = function () {
  this.state.entry = new Entry()
}

Pickup.prototype.imageopen = function () {
  this.state.image = true
}

Pickup.prototype.entryclose = function () {
  const entry = this.state.entry

  if (!entry) return

  if (!this.eventMode) {
    if (this.objectMode()) {
      this.push(entry)
    } else {
      this.push(JSON.stringify(entry) + os.EOL)
    }
  } else {
    this.emit('entry', entry)
  }

  this.state.entry = null
}

Pickup.prototype.feedclose = function () {
  const feed = this.state.feed

  if (!feed) return

  if (!this.eventMode) {
    if (this.objectMode()) {
      this.push(feed)
    } else {
      this.push(JSON.stringify(feed) + os.EOL)
    }
  } else {
    this.emit('feed', feed)
  }

  this.state.feed = null
}

Pickup.prototype.imageclose = function () {
  this.state.image = false
}

function free (parser) {
  parser.oncdata = null
  parser.onclosetag = null
  parser.onopentag = null
  parser.ontext = null
}

Pickup.prototype._flush = function (cb) {
  debug('flushing')
  this.parser.close()
  free(this.parser)

  this._decoder = null

  this.encoding = null
  this.parser = null

  this.state = null

  cb()
}

function cribEncoding (str) {
  const enc = str.split('encoding')[1]
  const def = 'utf8'

  if (!enc) return def

  if (enc.trim()[0] === '=') {
    return encodingFromString(enc)
  }

  return def
}

Pickup.prototype._transform = function (chunk, enc, cb) {
  if (!this._decoder) {
    if (!this.encoding) {
      // This, of course, fails--yielding 'utf8'--if the first chunk is too
      // short to contain the encoding tag.
      const t = chunk.toString('ascii', 0, 128)

      this.encoding = cribEncoding(t)
    }

    this.emit('encoding', this.encoding)
  }

  const str = this.decoder.write(chunk)

  this.parser.write(str)

  cb()
}

// Exports

exports.Pickup = Pickup
exports.Feed = Feed
exports.Entry = Entry

// Extending surface area when testing.

if (process.mainModule.filename.match(/test/) !== null) {
  exports.extend = function (origin, add) {
    return Object.assign(origin, add || Object.create(null))
  }

  exports.entry = function (obj) {
    return exports.extend(new Entry(), obj)
  }

  exports.feed = function (obj) {
    return exports.extend(new Feed(), obj)
  }

  exports.cribEncoding = cribEncoding

  exports.EVENTS = [
    'data',
    'drain',
    'readable',
    'end',
    'entry',
    'error',
    'feed',
    'finish'
  ]
}
<|endoftext|>


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

var matches = require('matches-selector')
  , event = require('event');

/**
 * Delegate event `type` to `selector`
 * and invoke `fn(e)`. A callback function
 * is returned which may be passed to `.unbind()`.
 *
 * @param {Element} el
 * @param {String} selector
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @return {Function}
 * @api public
 */

exports.bind = function(el, selector, type, fn, capture){
  return event.bind(el, type, function(e){
    if (matches(e.target, selector)) fn(e);
  }, capture);
};

/**
 * Unbind event `type`'s callback `fn`.
 *
 * @param {Element} el
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @api public
 */

exports.unbind = function(el, type, fn, capture){
  event.unbind(el, type, fn, capture);
};
<commit_msg>Use `call()` to correctly assign `this` in handler<commit_after>
/**
 * Module dependencies.
 */

var matches = require('matches-selector')
  , event = require('event');

/**
 * Delegate event `type` to `selector`
 * and invoke `fn(e)`. A callback function
 * is returned which may be passed to `.unbind()`.
 *
 * @param {Element} el
 * @param {String} selector
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @return {Function}
 * @api public
 */

exports.bind = function(el, selector, type, fn, capture){
  return event.bind(el, type, function(e){
    if (matches(e.target, selector)) fn.call(el, e);
  }, capture);
};

/**
 * Unbind event `type`'s callback `fn`.
 *
 * @param {Element} el
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @api public
 */

exports.unbind = function(el, type, fn, capture){
  event.unbind(el, type, fn, capture);
};
<|endoftext|>


<commit_before>// Simple persistence driver that saves data to plain text files

'use strict';

var aFrom             = require('es5-ext/array/from')
  , group             = require('es5-ext/array/#/group')
  , assign            = require('es5-ext/object/assign')
  , forEach           = require('es5-ext/object/for-each')
  , setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , toArray           = require('es5-ext/object/to-array')
  , ensureObject      = require('es5-ext/object/valid-object')
  , ensureString      = require('es5-ext/object/validate-stringifiable-value')
  , d                 = require('d')
  , lazy              = require('d/lazy')
  , memoizeMethods    = require('memoizee/methods')
  , Set               = require('es6-set')
  , deferred          = require('deferred')
  , resolve           = require('path').resolve
  , mkdir             = require('fs2/mkdir')
  , readFile          = require('fs2/read-file')
  , readdir           = require('fs2/readdir')
  , writeFile         = require('fs2/write-file')
  , serialize         = require('dbjs/_setup/serialize/value')
  , PersistenceDriver = require('./abstract')

  , isArray = Array.isArray, push = Array.prototype.push, keys = Object.keys
  , isId = RegExp.prototype.test.bind(/^[a-z0-9][a-z0-9A-Z]*$/)
  , byStamp = function (a, b) { return this[a].stamp - this[b].stamp; }
  , create = Object.create, parse = JSON.parse, stringify = JSON.stringify;

var TextFileDriver = module.exports = function (dbjs, data) {
	if (!(this instanceof TextFileDriver)) return new TextFileDriver(dbjs, data);
	ensureObject(data);
	this.dirPath = resolve(ensureString(data.path));
	PersistenceDriver.call(this, dbjs, data);
	this.dbDir = mkdir(this.dirPath, { intermediate: true }).aside(null, function (err) {
		this.isClosed = true;
		this.emitError(err);
	}.bind(this));
};
setPrototypeOf(TextFileDriver, PersistenceDriver);

TextFileDriver.prototype = Object.create(PersistenceDriver.prototype, assign({
	constructor: d(TextFileDriver),
	_getCustom: d(function (key) { return this._custom(function (data) { return data[key]; }); }),
	_loadValue: d(function (id) {
		var objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			if (!map.regular[id]) return null;
			return this._importValue(id, map.regular[id].value, map.stamp);
		}.bind(this));
	}),
	_loadObject: d(function (objId) {
		return this._getObjectFile(objId)(function (map) {
			var result = [];
			forEach(map.regular, function (data, id) {
				var event = this._importValue(id, data.value, data.stamp);
				if (event) result.push(event);
			}, this, byStamp);
			return result;
		}.bind(this));
	}),
	_loadAll: d(function () {
		var promise = this.dbDir()(function () {
			return this._allObjectsIds(function (data) {
				var result = [], progress = 1;
				return deferred.map(aFrom(data), function (id) {
					return this._loadObject(id).aside(function (events) {
						push.apply(result, events);
						if (events.length > (progress * 1000)) {
							++progress;
							promise.emit('progress');
						}
					});
				}, this)(result);
			}.bind(this));
		}.bind(this));
		return promise;
	}),
	_storeCustom: d(function (key, value) {
		return this._custom(function (data) {
			if (value === undefined) {
				if (!data.hasOwnProperty(key)) return;
				delete data[key];
			} else {
				if (data[key] === value) return;
				data[key] = value;
			}
			return writeFile(resolve(this.dirPath, '_custom'), stringify(data));
		}.bind(this));
	}),
	_storeEvent: d(function (event) {
		var id = event.object.master.__id__;
		return this._getObjectFile(id)(function (map) {
			map.regular[event.object.__valueId__] = {
				stamp: event.stamp,
				value: serialize(event.value)
			};
			return this._writeObjectFile(map, id);
		}.bind(this));
	}),
	_storeEvents: d(function (events) {
		var data = group.call(events, function (event) { return event.object.master.__id__; });
		return deferred.map(keys(data), function (id) {
			var events = data[id];
			return this._getObjectFile(id)(function (map) {
				events.forEach(function (event) {
					map.regular[event.object.__valueId__] = {
						stamp: event.stamp,
						value: serialize(event.value)
					};
				});
				return this._writeObjectFile(map, id);
			}.bind(this));
		}, this);
	}),
	_close: d(function () {
		// Nothing to do
	}),
	_getComputed: d(function (id) {
		return this._getObjectFile(id.split('/', 1)[0])(function (map) {
			return map.computed[id] || null;
		});
	}),
	_getAllComputed: d(function (keyPath) {
		var map = create(null);
		return this._allObjectsIds.map(function (id) {
			return this._getObjectFile(id)(function (objectMap) {
				if (objectMap['=' + keyPath]) map[id] = objectMap['=' + keyPath];
			});
		}, this)(map);
	}),
	_storeComputed: d(function (id, value, stamp) {
		var objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			var old = map.computed[id];
			if (old) {
				old.stamp = stamp;
				old.value = value;
			} else {
				map.computed[id] = {
					value: value,
					stamp: stamp
				};
			}
			return this._writeObjectFile(map, objId);
		}.bind(this));
	}),
	_writeObjectFile: d(function (map, objId) {
		this._allObjectsIds.aside(function (set) { set.add(objId); });
		return writeFile(resolve(this.dirPath, objId), toArray(map.regular, function (data, id) {
			return id + '\n' + data.stamp + '\n' + ((data.value === '') ? '-' : data.value);
		}, this, byStamp).concat(toArray(map.computed, function (data, id) {
			return '=' + id + '\n' + data.stamp + '\n' +
				(isArray(data.value) ? stringify(data.value) : ((data.value === '') ? '-' : data.value));
		}, this, byStamp)).join('\n\n'));
	}),
	_storeRaw: d(function (id, data) {
		var objId;
		if (id[0] === '_') return this._storeCustom(id.slice(1), data);
		if (id[0] === '=') objId = id.slice(1).split('/', 1)[0];
		else objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			if (id[0] === '=') map.computed[id.slice(1)] = data;
			else map.regular[id] = data;
			return this._writeObjectFile(map, objId);
		}.bind(this));
	}),
	_exportAll: d(function (destDriver) {
		var count = 0;
		var promise = this.dbDir()(function () {
			return deferred(
				this._allObjectsIds(function (data) {
					return deferred.map(aFrom(data), function (objId) {
						return this._getObjectFile(objId)(function (map) {
							return deferred(
								deferred.map(keys(map.regular), function (id) {
									if (!(++count % 1000)) promise.emit('progress');
									return destDriver._storeRaw(id, this[id]);
								}, map.regular),
								deferred.map(keys(map.computed), function (id) {
									if (!(++count % 1000)) promise.emit('progress');
									return destDriver._storeRaw('=' + id, this[id]);
								}, map.computed)
							);
						}.bind(this));
					}, this);
				}.bind(this)),
				this._custom(function (custom) {
					return deferred.map(keys(custom), function (key) {
						if (!(++count % 1000)) promise.emit('progress');
						return destDriver._storeRaw('_' + key, custom[key]);
					});
				})
			);
		}.bind(this));
		return promise;
	})
}, lazy({
	_allObjectsIds: d(function () {
		return readdir(this.dirPath, { type: { file: true } })(function (data) {
			return new Set(data.filter(isId));
		});
	}),
	_custom: d(function () {
		return this.dbDir()(function () {
			return readFile(resolve(this.dirPath, '_custom'))(function (str) {
				try {
					return parse(String(str));
				} catch (e) { return {}; }
			}, function (err) {
				if (err.code !== 'ENOENT') throw err;
				return {};
			});
		}.bind(this));
	})
}), memoizeMethods({
	_getObjectFile: d(function (id) {
		return this.dbDir()(function () {
			var map = { regular: create(null), computed: create(null) };
			return readFile(resolve(this.dirPath, id))(function (data) {
				var value;
				try {
					String(data).split('\n\n').forEach(function (data) {
						data = data.split('\n');
						if (data[0][0] === '=') {
							value = data[2];
							if (value[0] === '[') value = parse(data[2]);
							else if (value === '-') value = '';
							map.computed[data[0].slice(1)] = {
								stamp: Number(data[1]),
								value: value
							};
						} else {
							value = data[2];
							if (value === '-') value = '';
							map.regular[data[0]] = {
								stamp: Number(data[1]),
								value: value
							};
						}
					});
				} catch (ignore) {}
				return map;
			}, function (err) {
				if (err.code !== 'ENOENT') throw err;
				return map;
			});
		}.bind(this));
	}, { primitive: true })
})));
<commit_msg>Fix emit of progress events<commit_after>// Simple persistence driver that saves data to plain text files

'use strict';

var aFrom             = require('es5-ext/array/from')
  , group             = require('es5-ext/array/#/group')
  , assign            = require('es5-ext/object/assign')
  , forEach           = require('es5-ext/object/for-each')
  , setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , toArray           = require('es5-ext/object/to-array')
  , ensureObject      = require('es5-ext/object/valid-object')
  , ensureString      = require('es5-ext/object/validate-stringifiable-value')
  , d                 = require('d')
  , lazy              = require('d/lazy')
  , memoizeMethods    = require('memoizee/methods')
  , Set               = require('es6-set')
  , deferred          = require('deferred')
  , resolve           = require('path').resolve
  , mkdir             = require('fs2/mkdir')
  , readFile          = require('fs2/read-file')
  , readdir           = require('fs2/readdir')
  , writeFile         = require('fs2/write-file')
  , serialize         = require('dbjs/_setup/serialize/value')
  , PersistenceDriver = require('./abstract')

  , isArray = Array.isArray, push = Array.prototype.push, keys = Object.keys
  , isId = RegExp.prototype.test.bind(/^[a-z0-9][a-z0-9A-Z]*$/)
  , byStamp = function (a, b) { return this[a].stamp - this[b].stamp; }
  , create = Object.create, parse = JSON.parse, stringify = JSON.stringify;

var TextFileDriver = module.exports = function (dbjs, data) {
	if (!(this instanceof TextFileDriver)) return new TextFileDriver(dbjs, data);
	ensureObject(data);
	this.dirPath = resolve(ensureString(data.path));
	PersistenceDriver.call(this, dbjs, data);
	this.dbDir = mkdir(this.dirPath, { intermediate: true }).aside(null, function (err) {
		this.isClosed = true;
		this.emitError(err);
	}.bind(this));
};
setPrototypeOf(TextFileDriver, PersistenceDriver);

TextFileDriver.prototype = Object.create(PersistenceDriver.prototype, assign({
	constructor: d(TextFileDriver),
	_getCustom: d(function (key) { return this._custom(function (data) { return data[key]; }); }),
	_loadValue: d(function (id) {
		var objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			if (!map.regular[id]) return null;
			return this._importValue(id, map.regular[id].value, map.stamp);
		}.bind(this));
	}),
	_loadObject: d(function (objId) {
		return this._getObjectFile(objId)(function (map) {
			var result = [];
			forEach(map.regular, function (data, id) {
				var event = this._importValue(id, data.value, data.stamp);
				if (event) result.push(event);
			}, this, byStamp);
			return result;
		}.bind(this));
	}),
	_loadAll: d(function () {
		var promise = this.dbDir()(function () {
			return this._allObjectsIds(function (data) {
				var result = [], progress = 1;
				return deferred.map(aFrom(data), function (id) {
					return this._loadObject(id).aside(function (events) {
						push.apply(result, events);
						if (result.length > (progress * 1000)) {
							++progress;
							promise.emit('progress');
						}
					});
				}, this)(result);
			}.bind(this));
		}.bind(this));
		return promise;
	}),
	_storeCustom: d(function (key, value) {
		return this._custom(function (data) {
			if (value === undefined) {
				if (!data.hasOwnProperty(key)) return;
				delete data[key];
			} else {
				if (data[key] === value) return;
				data[key] = value;
			}
			return writeFile(resolve(this.dirPath, '_custom'), stringify(data));
		}.bind(this));
	}),
	_storeEvent: d(function (event) {
		var id = event.object.master.__id__;
		return this._getObjectFile(id)(function (map) {
			map.regular[event.object.__valueId__] = {
				stamp: event.stamp,
				value: serialize(event.value)
			};
			return this._writeObjectFile(map, id);
		}.bind(this));
	}),
	_storeEvents: d(function (events) {
		var data = group.call(events, function (event) { return event.object.master.__id__; });
		return deferred.map(keys(data), function (id) {
			var events = data[id];
			return this._getObjectFile(id)(function (map) {
				events.forEach(function (event) {
					map.regular[event.object.__valueId__] = {
						stamp: event.stamp,
						value: serialize(event.value)
					};
				});
				return this._writeObjectFile(map, id);
			}.bind(this));
		}, this);
	}),
	_close: d(function () {
		// Nothing to do
	}),
	_getComputed: d(function (id) {
		return this._getObjectFile(id.split('/', 1)[0])(function (map) {
			return map.computed[id] || null;
		});
	}),
	_getAllComputed: d(function (keyPath) {
		var map = create(null);
		return this._allObjectsIds.map(function (id) {
			return this._getObjectFile(id)(function (objectMap) {
				if (objectMap['=' + keyPath]) map[id] = objectMap['=' + keyPath];
			});
		}, this)(map);
	}),
	_storeComputed: d(function (id, value, stamp) {
		var objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			var old = map.computed[id];
			if (old) {
				old.stamp = stamp;
				old.value = value;
			} else {
				map.computed[id] = {
					value: value,
					stamp: stamp
				};
			}
			return this._writeObjectFile(map, objId);
		}.bind(this));
	}),
	_writeObjectFile: d(function (map, objId) {
		this._allObjectsIds.aside(function (set) { set.add(objId); });
		return writeFile(resolve(this.dirPath, objId), toArray(map.regular, function (data, id) {
			return id + '\n' + data.stamp + '\n' + ((data.value === '') ? '-' : data.value);
		}, this, byStamp).concat(toArray(map.computed, function (data, id) {
			return '=' + id + '\n' + data.stamp + '\n' +
				(isArray(data.value) ? stringify(data.value) : ((data.value === '') ? '-' : data.value));
		}, this, byStamp)).join('\n\n'));
	}),
	_storeRaw: d(function (id, data) {
		var objId;
		if (id[0] === '_') return this._storeCustom(id.slice(1), data);
		if (id[0] === '=') objId = id.slice(1).split('/', 1)[0];
		else objId = id.split('/', 1)[0];
		return this._getObjectFile(objId)(function (map) {
			if (id[0] === '=') map.computed[id.slice(1)] = data;
			else map.regular[id] = data;
			return this._writeObjectFile(map, objId);
		}.bind(this));
	}),
	_exportAll: d(function (destDriver) {
		var count = 0;
		var promise = this.dbDir()(function () {
			return deferred(
				this._allObjectsIds(function (data) {
					return deferred.map(aFrom(data), function (objId) {
						return this._getObjectFile(objId)(function (map) {
							return deferred(
								deferred.map(keys(map.regular), function (id) {
									if (!(++count % 1000)) promise.emit('progress');
									return destDriver._storeRaw(id, this[id]);
								}, map.regular),
								deferred.map(keys(map.computed), function (id) {
									if (!(++count % 1000)) promise.emit('progress');
									return destDriver._storeRaw('=' + id, this[id]);
								}, map.computed)
							);
						}.bind(this));
					}, this);
				}.bind(this)),
				this._custom(function (custom) {
					return deferred.map(keys(custom), function (key) {
						if (!(++count % 1000)) promise.emit('progress');
						return destDriver._storeRaw('_' + key, custom[key]);
					});
				})
			);
		}.bind(this));
		return promise;
	})
}, lazy({
	_allObjectsIds: d(function () {
		return readdir(this.dirPath, { type: { file: true } })(function (data) {
			return new Set(data.filter(isId));
		});
	}),
	_custom: d(function () {
		return this.dbDir()(function () {
			return readFile(resolve(this.dirPath, '_custom'))(function (str) {
				try {
					return parse(String(str));
				} catch (e) { return {}; }
			}, function (err) {
				if (err.code !== 'ENOENT') throw err;
				return {};
			});
		}.bind(this));
	})
}), memoizeMethods({
	_getObjectFile: d(function (id) {
		return this.dbDir()(function () {
			var map = { regular: create(null), computed: create(null) };
			return readFile(resolve(this.dirPath, id))(function (data) {
				var value;
				try {
					String(data).split('\n\n').forEach(function (data) {
						data = data.split('\n');
						if (data[0][0] === '=') {
							value = data[2];
							if (value[0] === '[') value = parse(data[2]);
							else if (value === '-') value = '';
							map.computed[data[0].slice(1)] = {
								stamp: Number(data[1]),
								value: value
							};
						} else {
							value = data[2];
							if (value === '-') value = '';
							map.regular[data[0]] = {
								stamp: Number(data[1]),
								value: value
							};
						}
					});
				} catch (ignore) {}
				return map;
			}, function (err) {
				if (err.code !== 'ENOENT') throw err;
				return map;
			});
		}.bind(this));
	}, { primitive: true })
})));
<|endoftext|>


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

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express()

// all environments
app.set('port', process.env.PORT || 4000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

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

app.get('/', user.list);
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>fixed CI issue<commit_after>
/**
 * Module dependencies.
 * Express > 4.0
 *
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 4000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

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

app.get('/', user.list);
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>var request = require('request-promise');

module.exports = function (options) {

  if (!options) {
    throw new Error('Options are required!');
  }

  if (!options.clientId) {
    throw new Error('Client ID is required');
  }

  if (!options.clientSecret) {
    throw new Error('Client Secret is required');
  }

  var _options = {
    client_id: options.clientId,
    client_secret: options.clientSecret
  };

  return {
    getTokens: function (authCode, callback) {
      if (!callback || (typeof(callback) !== 'function')) {
        throw new Error('Callback must be a function');
      }
      if (!authCode) {
        return callback({ code: 400, message: "Missing authCode" });
      }
      requset({
        method: 'POST',
        uri: 'https://www.googleapis.com/oauth2/v4/token',
        form: {
          code: authCode,
          client_id: _options.client_id,
          client_secret: _options.client_secret,
          grant_type: 'authorization_code'
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(function (body) {
        if (!body.access_token) {
          return callback({ code: 422, message: "Got no access_token from Google Fitness" })
        }
        if (!body.refresh_token) {
          return callback({ code: 422, message: "Got no refresh_token from Google Fitness" });
        }
        return callback(null, { accessToken: body.accessToken, refreshToken: body.refreshToken });
      }).catch(function (response) {
        response = response || {};
        var message;
        if (response.error) {
          message - response.error.error_description;
        }
        return callback({ code: response.statusCode || 400, message: message || "Error while requesting Google Fitness API" });
      });
    },
    getSteps: function (params, callback) {
      if (!callback || (typeof(callback) !== 'function')) {
        throw new Error('Callback must be a function');
      }
      if (!params) {
        return callback({ code: 400, message: "Missing params" });
      }
      if (!params.accessToken) {
        return callabck({ code: 400, message: "Missing accessToken parameter" });
      }
      if (!params.startTime) {
        return callabck({ code: 400, message: "Missing startTime parameter" });
      }
      if (!params.endTime) {
        return callabck({ code: 400, message: "Missing endTime parameter" });
      }
      requset({
        method: 'POST',
        uri: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
        body: {
          "aggregateBy": [{
          "dataTypeName": "com.google.step_count.delta",
          "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
        }],
        "startTimeMillis": params.startTime,
        "endTimeMillis": params.endTime
        },
        headers: {
          'Content-Type': 'application/json;encoding=utf-8',
          'Authorization': 'Bearer' + params.accessToken
        }
      }).then(function (body) {
        console.log(body);
        return callback(null, { body: body });
      }).catch(function (response) {
        response = response || {};
        var message;
        if (response.error) {
          message - response.error.error_description;
        }
        return callback({ code: response.statusCode || 400, message: message || "Error while requesting Google Fitness API" });
      });
    }
  };
};
<commit_msg>callback fix<commit_after>var request = require('request-promise');

module.exports = function (options) {

  if (!options) {
    throw new Error('Options are required!');
  }

  if (!options.clientId) {
    throw new Error('Client ID is required');
  }

  if (!options.clientSecret) {
    throw new Error('Client Secret is required');
  }

  var _options = {
    client_id: options.clientId,
    client_secret: options.clientSecret
  };

  return {
    getTokens: function (authCode, callback) {
      if (!callback || (typeof(callback) !== 'function')) {
        throw new Error('Callback must be a function');
      }
      if (!authCode) {
        return callback({ code: 400, message: "Missing authCode" });
      }
      requset({
        method: 'POST',
        uri: 'https://www.googleapis.com/oauth2/v4/token',
        form: {
          code: authCode,
          client_id: _options.client_id,
          client_secret: _options.client_secret,
          grant_type: 'authorization_code'
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(function (body) {
        if (!body.access_token) {
          return callback({ code: 422, message: "Got no access_token from Google Fitness" })
        }
        if (!body.refresh_token) {
          return callback({ code: 422, message: "Got no refresh_token from Google Fitness" });
        }
        return callback(null, { accessToken: body.accessToken, refreshToken: body.refreshToken });
      }).catch(function (response) {
        response = response || {};
        var message;
        if (response.error) {
          message - response.error.error_description;
        }
        return callback({ code: response.statusCode || 400, message: message || "Error while requesting Google Fitness API" });
      });
    },
    getSteps: function (params, callback) {
      if (!callback || (typeof(callback) !== 'function')) {
        throw new Error('Callback must be a function');
      }
      if (!params) {
        return callback({ code: 400, message: "Missing params" });
      }
      if (!params.accessToken) {
        return callback({ code: 400, message: "Missing accessToken parameter" });
      }
      if (!params.startTime) {
        return callback({ code: 400, message: "Missing startTime parameter" });
      }
      if (!params.endTime) {
        return callback({ code: 400, message: "Missing endTime parameter" });
      }
      requset({
        method: 'POST',
        uri: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
        body: {
          "aggregateBy": [{
          "dataTypeName": "com.google.step_count.delta",
          "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
        }],
        "startTimeMillis": params.startTime,
        "endTimeMillis": params.endTime
        },
        headers: {
          'Content-Type': 'application/json;encoding=utf-8',
          'Authorization': 'Bearer' + params.accessToken
        }
      }).then(function (body) {
        console.log(body);
        return callback(null, { body: body });
      }).catch(function (response) {
        response = response || {};
        var message;
        if (response.error) {
          message - response.error.error_description;
        }
        return callback({ code: response.statusCode || 400, message: message || "Error while requesting Google Fitness API" });
      });
    }
  };
};
<|endoftext|>


<commit_before>var dgram = require('dgram'),
    server = dgram.createSocket('udp4'),
    dns = require('dns')
    //keypress = require('keypress')

var stdin = process.openStdin(),
    require('tty').setRawMode(true);

var url = 'vincentdefeo.me',
    port = 8080

var clients = []

stdin.on('keypress', function() {
    console.log("\nGot Keypress\n", clients)

    for (var i = 0; i < clients.length; i++)
        server.send('data from netherlands', 0, clients[i].port, clients[i].addresses)
})

dns.lookup(url, function resolved(err, addresses){
    if (err) throw err
    console.log('\nSTARTING...\n' + url + ' RESOLVED TO: ' + addresses)
    server.bind(port, addresses)
})

server.on('listening', function(){
    var address = server.address()
    console.log('Listening on : ' + address.address + ':' + address.port)
})

server.on('message', function (msg, r){
    clients.push({'ip': r.address, 'port' : r.port})

    console.log('\n==========GOT MESSAGE==========\n' + msg + '\nFROM: ' + r.address + ':' + r.port)
    console.log('\nON: ' + Date.now())

    server.send(msg, 0, msg.length, r.port, r.address)
})

server.on('error', function (err){
	console.log("\n[!!] ERROR: " + err);
})
<commit_msg>keypress fix<commit_after>var dgram = require('dgram'),
    server = dgram.createSocket('udp4'),
    dns = require('dns'),
    keypress = require('keypress')

var url = 'vincentdefeo.me',
    port = 8080

var clients = []

keypress(process.stdin)
process.stdin.setRawMode(true)

process.stdin.on('keypress', function(c, k) {
    if (c == 'c')
        process.stdin.pause()
    else {
        console.log("\nGot Keypress\n", clients)

        for (var i = 0; i < clients.length; i++)
            server.send('data from netherlands', 0, clients[i].port, clients[i].addresses)
    }
})

dns.lookup(url, function resolved(err, addresses){
    if (err) throw err
    console.log('\nSTARTING...\n' + url + ' RESOLVED TO: ' + addresses)
    server.bind(port, addresses)
})

server.on('listening', function(){
    var address = server.address()
    console.log('Listening on : ' + address.address + ':' + address.port)
})

server.on('message', function (msg, r){
    clients.push({'ip': r.address, 'port' : r.port})

    console.log('\n==========GOT MESSAGE==========\n' + msg + '\nFROM: ' + r.address + ':' + r.port)
    console.log('\nON: ' + Date.now())

    server.send(msg, 0, msg.length, r.port, r.address)
})

server.on('error', function (err){
	console.log("\n[!!] ERROR: " + err);
})
<|endoftext|>