<commit_before>'use strict';

var request = require('request')
, qs = require('qs');

var slice = Array.prototype.slice;

/**
 * Create new FullContact instance.
 *
 * @constructor
 * @param {String} api The API key for the Full Contact service.
 * @api public
 */
function FullContact(api) {
  if (!(this instanceof FullContact)) {
    return new FullContact(api);
  }

  this.key = api;         // API key
  this.version = 'v2';    // API version

  this.remaining = 0;     // How many API calls are remaining
  this.ratelimit = 0;     // The amount of API calls allowed
  this.ratereset = 0;     // In how many seconds is the rate limit reset

  this.queueing = false;  // Should we be queueing requests
  this.requests = [];     // Stores all queued commands

  if (!this.key) {
    throw new Error('Missing API key');
  }
}

/**
 * Process the requests before sending, queueing, or what evering
 *
 * @param {Mixed} api Reference to the Person/WhatEver API.
 * @param {Object} query Query string object that should be send.
 * @param {Object} args Arguments.
 * @api private
 */
FullContact.prototype.process = function req(api, query, args) {
  query.apiKey = query.apiKey || this.key;

  //
  // Add some addition properties
  //
  if (args.queue) {
    query.queue = args.queue;
  }
  if (args.casing) {
    query.casing = args.casing;
  }
  if (args.population) {
    query.includeZeroPopulation = !!args.population;
  }

  if (args.webhookUrl) {
    query.webhookUrl = args.webhookUrl;
  }
  if (args.webhookId) {
    query.webhookId = args.webhookId;
  }

  //
  // The packet that is send to the server or queued when we are in queuing
  // mode.
  //
  var packet = {
    method: 'GET',
    uri: args.endpoint || api.endpoint,
    qs: query
  };

  if (this.queueing) {
    return this.queue(packet, args);
  }

  return this.request(packet, args);
};

/**
 * Send a GET request to the FullContact servers using given packet.
 *
 * @param {Object} packet Request packet.
 * @param {Object} args API arguments.
 * @api private
 */
FullContact.prototype.request = function req(packet, args) {
  var fn = args.fn
  , self = this;

  request(packet, function requested(err, res, body) {
    if (err) {
      return fn(err);
    }

    self.ratereset = +res.headers['x-rate-limit-reset'] || self.ratereset;
    self.ratelimit = +res.headers['x-rate-limit-limit'] || self.ratelimit;
    self.remaining = +res.headers['x-rate-limit-remaining'] || self.remaining;

    //
    // Parse response to JSON.
    //
    if (typeof body === 'string') {
      try { body = JSON.parse(body); }
      catch (e) {
        return fn(new Error('Failed to parse API response (' + e.message + ')'));
      }
    }

    //
    // Handle API errors, FullContact adds a "status" key to the JSON response
    // it will have a "message" property when it's a failed request so we can
    // leverage that to return a nice error.
    //
    if (body.status !== 200 && body.status !== 202) {
      err = new Error(body.message);
      err.status = body.status;

      return fn(err);
    }

    fn(undefined, body);
  });

  return this;
};

/**
 * Start a multi/batch request to the API.
 *
 * @api public
 */
FullContact.prototype.multi = function multi() {
  var queued = new FullContact(this.key);

  //
  // Force queueing mode on the newly generated API
  //
  queued.queueing = true;

  return queued;
};

/**
 * Queue up requests so they can be send as a batch.
 *
 * @param {Object} packet The object that would be send using .request
 * @param {Object} args The arguments;
 * @api private
 */
FullContact.prototype.queue = function queue(packet, args) {
  this.requests.push({
    url: packet.uri + '?' + qs.stringify(packet.qs),
    fn: args.fn
  });

  return this;
};

/**
 * Send all the batched requests to the server.
 *
 * @param {Function} fn The callback.
 * @api public
 */
FullContact.prototype.exec = function exec(fn) {
  fn = fn || function noop() {};

  var requests = this.requests.splice(0);

  /**
   * Handle errors easily and ensure that all callbacks are called that were
   * queued in the process.
   *
   * @param {Error} err The exception that occured
   */
  function bailout(err) {
    requests.forEach(function cb(data) {
      if (data.fn) {
        data.fn(err);
      }
    });

    fn(err);
  }

  //
  // We are no longer queing requests.
  //
  this.queueing = false;

  request({
    method: 'POST',
    uri: 'https://api.fullcontact.com/' + this.version + '/batch.json',
    qs: { apiKey: this.key },
    json: {
      requests: requests.map(function urlsonly(data) {
        return data.url;
      })
    }
  }, function requested(err, res, body) {
    if (err) {
      return bailout(err);
    }

    fn(err, body.responses);
  });
};

/**
 * Parse the given arguments because we don't want to do an optional queue check
 * for every single API endpoint.
 *
 * @param {Arguments} args Arguments
 * @returns {Object}
 * @api private
 */
FullContact.prototype.args = function parser(args) {
  var optional = slice.call(arguments, 1);
  args = slice.call(args, 0);

  return optional.reduce(function optional(data, key, index) {
    data[key] = args[index];
    return data;
  }, { value: args.shift(), fn: args.pop() });
};

/**
 * Define an lazyload new API's.
 *
 * @param {Object} where Where should we define the property
 * @param {String} name The name of the property
 * @param {Function} fn The function that returns the new value
 * @api private
 */
FullContact.define = function define(where, name, fn) {
  Object.defineProperty(where, name, {
    configurable: true,
    get: function get() {
      return Object.defineProperty(this, name, {
        value: fn.call(this)
      })[name];
    },
    set: function set(value) {
      return Object.defineProperty(this, name, {
        value: value
      })[name];
    }
  });
};

/**
 * Have a Node API compatible client interface.
 *
 * @param {String} api The API key for full contact
 * @returns {FullContact}
 * @api public
 */
FullContact.createClient = function createClient(api) {
  return new FullContact(api);
};

//
// Expose the endpoints.
//
FullContact.Location = require('./endpoints/location');
FullContact.Person = require('./endpoints/person');
FullContact.Email = require('./endpoints/email');
FullContact.Name = require('./endpoints/name');
FullContact.Company = require('./endpoints/company');

//
// Lazy load the various of endpoints so they only get initialized when we
// actually need them.
//
FullContact.define(FullContact.prototype, 'location', function define() {
  return new FullContact.Location(this);
});

FullContact.define(FullContact.prototype, 'email', function define() {
  return new FullContact.Email(this);
});

FullContact.define(FullContact.prototype, 'person', function define() {
  return new FullContact.Person(this);
});

FullContact.define(FullContact.prototype, 'name', function define() {
  return new FullContact.Name(this);
});

FullContact.define(FullContact.prototype, 'company', function define() {
  return new FullContact.Company(this);
});

//
// Expose the FullContact API.
//
module.exports = FullContact;
<commit_msg>Added webhookBody arg<commit_after>'use strict';

var request = require('request')
, qs = require('qs');

var slice = Array.prototype.slice;

/**
 * Create new FullContact instance.
 *
 * @constructor
 * @param {String} api The API key for the Full Contact service.
 * @api public
 */
function FullContact(api) {
  if (!(this instanceof FullContact)) {
    return new FullContact(api);
  }

  this.key = api;         // API key
  this.version = 'v2';    // API version

  this.remaining = 0;     // How many API calls are remaining
  this.ratelimit = 0;     // The amount of API calls allowed
  this.ratereset = 0;     // In how many seconds is the rate limit reset

  this.queueing = false;  // Should we be queueing requests
  this.requests = [];     // Stores all queued commands

  if (!this.key) {
    throw new Error('Missing API key');
  }
}

/**
 * Process the requests before sending, queueing, or what evering
 *
 * @param {Mixed} api Reference to the Person/WhatEver API.
 * @param {Object} query Query string object that should be send.
 * @param {Object} args Arguments.
 * @api private
 */
FullContact.prototype.process = function req(api, query, args) {
  query.apiKey = query.apiKey || this.key;

  //
  // Add some addition properties
  //
  if (args.queue) {
    query.queue = args.queue;
  }
  if (args.casing) {
    query.casing = args.casing;
  }
  if (args.population) {
    query.includeZeroPopulation = !!args.population;
  }

  if (args.webhookUrl) {
    query.webhookUrl = args.webhookUrl;
  }
  if (args.webhookId) {
    query.webhookId = args.webhookId;
  }
  if (args.webhookBody) {
    query.webhookBody = args.webhookBody;
  }

  //
  // The packet that is send to the server or queued when we are in queuing
  // mode.
  //
  var packet = {
    method: 'GET',
    uri: args.endpoint || api.endpoint,
    qs: query
  };

  if (this.queueing) {
    return this.queue(packet, args);
  }

  return this.request(packet, args);
};

/**
 * Send a GET request to the FullContact servers using given packet.
 *
 * @param {Object} packet Request packet.
 * @param {Object} args API arguments.
 * @api private
 */
FullContact.prototype.request = function req(packet, args) {
  var fn = args.fn
  , self = this;

  request(packet, function requested(err, res, body) {
    if (err) {
      return fn(err);
    }

    self.ratereset = +res.headers['x-rate-limit-reset'] || self.ratereset;
    self.ratelimit = +res.headers['x-rate-limit-limit'] || self.ratelimit;
    self.remaining = +res.headers['x-rate-limit-remaining'] || self.remaining;

    //
    // Parse response to JSON.
    //
    if (typeof body === 'string') {
      try { body = JSON.parse(body); }
      catch (e) {
        return fn(new Error('Failed to parse API response (' + e.message + ')'));
      }
    }

    //
    // Handle API errors, FullContact adds a "status" key to the JSON response
    // it will have a "message" property when it's a failed request so we can
    // leverage that to return a nice error.
    //
    if (body.status !== 200 && body.status !== 202) {
      err = new Error(body.message);
      err.status = body.status;

      return fn(err);
    }

    fn(undefined, body);
  });

  return this;
};

/**
 * Start a multi/batch request to the API.
 *
 * @api public
 */
FullContact.prototype.multi = function multi() {
  var queued = new FullContact(this.key);

  //
  // Force queueing mode on the newly generated API
  //
  queued.queueing = true;

  return queued;
};

/**
 * Queue up requests so they can be send as a batch.
 *
 * @param {Object} packet The object that would be send using .request
 * @param {Object} args The arguments;
 * @api private
 */
FullContact.prototype.queue = function queue(packet, args) {
  this.requests.push({
    url: packet.uri + '?' + qs.stringify(packet.qs),
    fn: args.fn
  });

  return this;
};

/**
 * Send all the batched requests to the server.
 *
 * @param {Function} fn The callback.
 * @api public
 */
FullContact.prototype.exec = function exec(fn) {
  fn = fn || function noop() {};

  var requests = this.requests.splice(0);

  /**
   * Handle errors easily and ensure that all callbacks are called that were
   * queued in the process.
   *
   * @param {Error} err The exception that occured
   */
  function bailout(err) {
    requests.forEach(function cb(data) {
      if (data.fn) {
        data.fn(err);
      }
    });

    fn(err);
  }

  //
  // We are no longer queing requests.
  //
  this.queueing = false;

  request({
    method: 'POST',
    uri: 'https://api.fullcontact.com/' + this.version + '/batch.json',
    qs: { apiKey: this.key },
    json: {
      requests: requests.map(function urlsonly(data) {
        return data.url;
      })
    }
  }, function requested(err, res, body) {
    if (err) {
      return bailout(err);
    }

    fn(err, body.responses);
  });
};

/**
 * Parse the given arguments because we don't want to do an optional queue check
 * for every single API endpoint.
 *
 * @param {Arguments} args Arguments
 * @returns {Object}
 * @api private
 */
FullContact.prototype.args = function parser(args) {
  var optional = slice.call(arguments, 1);
  args = slice.call(args, 0);

  return optional.reduce(function optional(data, key, index) {
    data[key] = args[index];
    return data;
  }, { value: args.shift(), fn: args.pop() });
};

/**
 * Define an lazyload new API's.
 *
 * @param {Object} where Where should we define the property
 * @param {String} name The name of the property
 * @param {Function} fn The function that returns the new value
 * @api private
 */
FullContact.define = function define(where, name, fn) {
  Object.defineProperty(where, name, {
    configurable: true,
    get: function get() {
      return Object.defineProperty(this, name, {
        value: fn.call(this)
      })[name];
    },
    set: function set(value) {
      return Object.defineProperty(this, name, {
        value: value
      })[name];
    }
  });
};

/**
 * Have a Node API compatible client interface.
 *
 * @param {String} api The API key for full contact
 * @returns {FullContact}
 * @api public
 */
FullContact.createClient = function createClient(api) {
  return new FullContact(api);
};

//
// Expose the endpoints.
//
FullContact.Location = require('./endpoints/location');
FullContact.Person = require('./endpoints/person');
FullContact.Email = require('./endpoints/email');
FullContact.Name = require('./endpoints/name');
FullContact.Company = require('./endpoints/company');

//
// Lazy load the various of endpoints so they only get initialized when we
// actually need them.
//
FullContact.define(FullContact.prototype, 'location', function define() {
  return new FullContact.Location(this);
});

FullContact.define(FullContact.prototype, 'email', function define() {
  return new FullContact.Email(this);
});

FullContact.define(FullContact.prototype, 'person', function define() {
  return new FullContact.Person(this);
});

FullContact.define(FullContact.prototype, 'name', function define() {
  return new FullContact.Name(this);
});

FullContact.define(FullContact.prototype, 'company', function define() {
  return new FullContact.Company(this);
});

//
// Expose the FullContact API.
//
module.exports = FullContact;
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// UTILS //

var utils = {};
setReadOnly( utils, 'fs', {} );

// General:
setReadOnly( utils, 'setReadOnly', setReadOnly );
setReadOnly( utils, 'moveProperty', require( '@stdlib/utils/move-property' ) );
setReadOnly( utils, 'isFunction', require( '@stdlib/utils/is-function' ) );
setReadOnly( utils, 'isLittleEndian', require( '@stdlib/utils/is-little-endian' ) );
setReadOnly( utils, 'isNaN', require( '@stdlib/utils/is-nan' ) );
setReadOnly( utils, 'isNonNegativeInteger', require( '@stdlib/utils/is-nonnegative-integer' ) );
setReadOnly( utils, 'isNumber', require( '@stdlib/utils/is-number' ) );
setReadOnly( utils, 'isInteger', require( '@stdlib/utils/is-integer' ) );

// fs:
setReadOnly( utils.fs, 'exists', require( '@stdlib/utils/fs/exists' ) );

// EXPORTS //

module.exports = utils;
<commit_msg>Export isTypedArray util function<commit_after>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// UTILS //

var utils = {};
setReadOnly( utils, 'fs', {} );

// General:
setReadOnly( utils, 'setReadOnly', setReadOnly );
setReadOnly( utils, 'moveProperty', require( '@stdlib/utils/move-property' ) );
setReadOnly( utils, 'isFunction', require( '@stdlib/utils/is-function' ) );
setReadOnly( utils, 'isLittleEndian', require( '@stdlib/utils/is-little-endian' ) );
setReadOnly( utils, 'isNaN', require( '@stdlib/utils/is-nan' ) );
setReadOnly( utils, 'isNonNegativeInteger', require( '@stdlib/utils/is-nonnegative-integer' ) );
setReadOnly( utils, 'isNumber', require( '@stdlib/utils/is-number' ) );
setReadOnly( utils, 'isTypedArray', require( '@stdlib/utils/is-typed-array' ) );
setReadOnly( utils, 'isInteger', require( '@stdlib/utils/is-integer' ) );

// fs:
setReadOnly( utils.fs, 'exists', require( '@stdlib/utils/fs/exists' ) );

// EXPORTS //

module.exports = utils;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Glyptodon Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file Overrides the default document.execCommand() implementation, providing
 * versions of the "cut", "copy", and "paste" commands which directly access
 * clipboard data if permission has been explicitly granted for the current
 * page. If permission has not been granted, or a different command is given,
 * the default document.execCommand() implementation is used.
 *
 * @author Michael Jumper
 */

// Override document.execCommand() such that clipboard data can be exposed
// without corresponding user events if permission is explicitly granted.
(function overrideExecCommand() {

    /**
     * The current contents of the local clipboard. This will be continuously
     * updated by the clipboard monitor script. If the clipboard cannot be read
     * this will be null.
     *
     * @type {String}
     */
    var clipboardContents = null;

    /**
     * The previous definition of document.execCommand(). This function will be
     * invoked when the original behavior of document.execCommand() is needed.
     *
     * @type {Function}
     */
    var _execCommand = document.execCommand;

    /**
     * Sets the value of the local clipboard to the given string.
     *
     * @param {String} value
     *     The value to assign to the local clipboard.
     */
    var setLocalClipboard = function setLocalClipboard(value) {
        document.dispatchEvent(new CustomEvent('_clip-perm-man-set-data', {
            'detail' : value
        }));
    };

    /**
     * Requests that data from the local clipboard be pulled. This pull is
     * asynchronous; data will be returned via a "_clip-perm-man-data" event
     * if reading from the clipboard is successful.
     */
    var requestLocalClipboard = function requestLocalClipboard() {

        // Defer request for clipboard data
        window.setTimeout(function requestClipboardData() {
            document.dispatchEvent(new CustomEvent('_clip-perm-man-get-data'));
        }, 50);

    };

    /**
     * Map of handlers for document.execCommand() functions, where the key of
     * each entry is the name of the command being overridden.
     *
     * @type {Object.<String, Function>}
     */
    var commandHandlers = {

        /**
         * Handler for document.execCommand('cut').
         */
        'cut' : function handleCut() {
            setLocalClipboard(window.getSelection().toString());
            _execCommand.call(this, 'insertText', false, '');
        },

        /**
         * Handler for document.execCommand('copy').
         */
        'copy' : function handleCopy() {
            setLocalClipboard(window.getSelection().toString());
        },

        /**
         * Handler for document.execCommand('paste').
         */
        'paste' : function handlePaste() {
            _execCommand.call(this, 'insertText', false, clipboardContents);
        }

    };

    /**
     * An implementation of document.execCommand() which allows access to all
     * clipboard commands as long as the user has approved this access ahead of
     * time. All other commands are passed through to the browser's own
     * document.execCommand() implementation.
     *
     * @param {String} name
     *     The name of the command to execute within the current document.
     *
     * @return {Boolean}
     *     true if the command was executed successfully, false otherwise.
     */
    document.execCommand = function clipExecCommand(name) {

        // Override behavior only if the command has a defined handler
        var commandHandler = commandHandlers[name];
        if (commandHandler) {

            // If clipboard has ever successfully been read, override default
            // behavior of document.execCommand()
            if (clipboardContents !== null) {
                commandHandler.apply(this);
                return true;
            }

        }

        // Otherwise pass through to original execCommand() implementation
        return _execCommand.apply(this, arguments);

    };

    // Request an update of the local clipboard when it may have changed
    window.addEventListener('focus', requestLocalClipboard, true);
    window.addEventListener('copy',  requestLocalClipboard, true);
    window.addEventListener('cut',   requestLocalClipboard, true);

    // When clipboard contents are received, update our internal clipboard
    // content tracking property
    document.addEventListener('_clip-perm-man-data', function handleData(e) {
        clipboardContents = e.detail;
    });

})();

<commit_msg>GUAC-1480: Make initial clipboard request on load.<commit_after>/*
 * Copyright (C) 2016 Glyptodon Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file Overrides the default document.execCommand() implementation, providing
 * versions of the "cut", "copy", and "paste" commands which directly access
 * clipboard data if permission has been explicitly granted for the current
 * page. If permission has not been granted, or a different command is given,
 * the default document.execCommand() implementation is used.
 *
 * @author Michael Jumper
 */

// Override document.execCommand() such that clipboard data can be exposed
// without corresponding user events if permission is explicitly granted.
(function overrideExecCommand() {

    /**
     * The current contents of the local clipboard. This will be continuously
     * updated by the clipboard monitor script. If the clipboard cannot be read
     * this will be null.
     *
     * @type {String}
     */
    var clipboardContents = null;

    /**
     * The previous definition of document.execCommand(). This function will be
     * invoked when the original behavior of document.execCommand() is needed.
     *
     * @type {Function}
     */
    var _execCommand = document.execCommand;

    /**
     * Sets the value of the local clipboard to the given string.
     *
     * @param {String} value
     *     The value to assign to the local clipboard.
     */
    var setLocalClipboard = function setLocalClipboard(value) {
        document.dispatchEvent(new CustomEvent('_clip-perm-man-set-data', {
            'detail' : value
        }));
    };

    /**
     * Requests that data from the local clipboard be pulled. This pull is
     * asynchronous; data will be returned via a "_clip-perm-man-data" event
     * if reading from the clipboard is successful.
     */
    var requestLocalClipboard = function requestLocalClipboard() {

        // Defer request for clipboard data
        window.setTimeout(function requestClipboardData() {
            document.dispatchEvent(new CustomEvent('_clip-perm-man-get-data'));
        }, 50);

    };

    /**
     * Map of handlers for document.execCommand() functions, where the key of
     * each entry is the name of the command being overridden.
     *
     * @type {Object.<String, Function>}
     */
    var commandHandlers = {

        /**
         * Handler for document.execCommand('cut').
         */
        'cut' : function handleCut() {
            setLocalClipboard(window.getSelection().toString());
            _execCommand.call(this, 'insertText', false, '');
        },

        /**
         * Handler for document.execCommand('copy').
         */
        'copy' : function handleCopy() {
            setLocalClipboard(window.getSelection().toString());
        },

        /**
         * Handler for document.execCommand('paste').
         */
        'paste' : function handlePaste() {
            _execCommand.call(this, 'insertText', false, clipboardContents);
        }

    };

    /**
     * An implementation of document.execCommand() which allows access to all
     * clipboard commands as long as the user has approved this access ahead of
     * time. All other commands are passed through to the browser's own
     * document.execCommand() implementation.
     *
     * @param {String} name
     *     The name of the command to execute within the current document.
     *
     * @return {Boolean}
     *     true if the command was executed successfully, false otherwise.
     */
    document.execCommand = function clipExecCommand(name) {

        // Override behavior only if the command has a defined handler
        var commandHandler = commandHandlers[name];
        if (commandHandler) {

            // If clipboard has ever successfully been read, override default
            // behavior of document.execCommand()
            if (clipboardContents !== null) {
                commandHandler.apply(this);
                return true;
            }

        }

        // Otherwise pass through to original execCommand() implementation
        return _execCommand.apply(this, arguments);

    };

    // Request an update of the local clipboard when it may have changed
    window.addEventListener('load',  requestLocalClipboard, true);
    window.addEventListener('focus', requestLocalClipboard, true);
    window.addEventListener('copy',  requestLocalClipboard, true);
    window.addEventListener('cut',   requestLocalClipboard, true);

    // When clipboard contents are received, update our internal clipboard
    // content tracking property
    document.addEventListener('_clip-perm-man-data', function handleData(e) {
        clipboardContents = e.detail;
    });

})();

<|endoftext|>


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

const optimist = require('optimist').argv
const http = require('http')

if (!optimist.from && !optimist.f) {
  console.log('From param should be defined')
  process.exit()
}

var from = optimist.from ? optimist.from : optimist.f

from = from.toUpperCase()

if (!optimist.to && !optimist.t) {
  console.log('To param should be defined')
  process.exit()
}

var to = optimist.to ? optimist.to : optimist.t
to = to.toUpperCase()

let type = 'simple'

if (optimist.ouput || optimist.o) {
  if (optimist.ouput === 'full' || optimist.o === 'full') type = 'full'
};

let amount
process.argv.forEach(function (value) {
  if (!isNaN(parseFloat(value)) && isFinite(value)) {
    amount = value
  }
})

if (!amount) {
  console.log('Amount param should be defined')
  process.exit()
}

var code = from + '_' + to

http.get('http://free.currencyconverterapi.com/api/v3/convert?q=' + code + '&compact=ultra', (res) => {
  res.on('data', (data) => {
    data = JSON.parse(data)
    if (!data[code]) {
      console.log('Currency no supported or bad spell')
    } else {
    // raw response
      if (type === 'full') {
        console.log('Amount: ' + amount + ' ' + from)
        console.log('From: ' + from)
        console.log('To: ' + to)
        console.log('Current Rate: ' + data[code] + ' ' + to)
        console.log('Total: ' + amount * data[code] + ' ' + to)
      } else {
        console.log(amount * data[code] + ' ' + to)
      }
    }
  })
})
<commit_msg>Set strings contactenations with ec6<commit_after>#! /usr/bin/env node
'use strict'

const optimist = require('optimist').argv
const http = require('http')

if (!optimist.from && !optimist.f) {
  console.log('From param should be defined')
  process.exit()
}

var from = optimist.from ? optimist.from : optimist.f

from = from.toUpperCase()

if (!optimist.to && !optimist.t) {
  console.log('To param should be defined')
  process.exit()
}

var to = optimist.to ? optimist.to : optimist.t
to = to.toUpperCase()

let type = 'simple'

if (optimist.ouput || optimist.o) {
  if (optimist.ouput === 'full' || optimist.o === 'full') type = 'full'
};

let amount
process.argv.forEach((value) => {
  if (!isNaN(parseFloat(value)) && isFinite(value)) {
    amount = value
  }
})

if (!amount) {
  console.log('Amount param should be defined')
  process.exit()
}

var code = `${from}_${to}`

http.get('http://free.currencyconverterapi.com/api/v3/convert?q=' + code + '&compact=ultra', (res) => {
  res.on('data', (data) => {
    data = JSON.parse(data)
    if (!data[code]) {
      console.log('Currency no supported or bad spell')
    } else {
    // raw response
      if (type === 'full') {
        console.log(`Amount: ${amount} ${from}`)
        console.log(`From: ${from}`)
        console.log(`To: ${to}`)
        console.log(`Current Rate: ${data[code]} ${to}`)
        console.log(`Total: ${amount * data[code]} ${to}`)
      } else {
        console.log(`${amount * data[code]} ${to}`)
      }
    }
  })
})
<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var exec = require('child_process').exec;

var trim = require('util/misc').trim;

exports.get = function(done) {
  /* Return runit services path if runsvdir is running, false otherwise */
  exec('ps aux | grep runsvdir | grep -v grep', function(err, stdout, stderr) {
    var matches, services_path;

    if (err) {
      done({runit_services_path: false});
      return;
    }

    matches = stdout.match(/runsvdir (\-p)? (.*?) /i);

    if (matches === null || matches.length !== 3) {
      done({runit_services_path: false});
      return;
    }

    services_path = matches[2];
    done({runit_services_path: services_path});
  });
};
<commit_msg>More runit path parsing improvements<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var exec = require('child_process').exec;
var trim = require('util/misc').trim;
var log = require('util/log');

exports.get = function(done) {
  /* Return runit services path if runsvdir is running, false otherwise */
  exec('ps -C runsvdir -o args --no-headers', function(err, stdout, stderr) {
    var lines, matches, services_path;

    if (err) {
      done({runit_services_path: false});
      return;
    }
    lines = trim(stdout).split('\n');

    if (lines.length > 1) {
      // TODO: Better handling of this situation */
      log.err("More than one 'runsvdir' process found");
      done({runit_services_path: false});
      return;
    }
    else if (lines.length < 1) {
      done({runit_services_path: false});
      return;
    }

    // runsvdir [-P] path [ log ]
    matches = lines[0].match(/runsvdir (\-p\ )?(\S+)/i);

    if (matches === null || matches.length !== 3) {
      done({runit_services_path: false});
      return;
    }

    services_path = matches[2];
    done({runit_services_path: services_path});
  });
};
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var fs = require('fs');
var path = require('path');
var os = require('os');
var extend = require('extend');

var defaultOptions = {};

var debug = require('debug');
// Define some debug logging functions for easy and readable debug messages.
var log = {
  main: debug('HLW'),
  gameStart: debug('HLW:game-start'),
  zoneChange: debug('HLW:zone-change'),
  gameOver: debug('HLW:game-over')
};

// Determine the default location of the config and log files.
if (/^win/.test(os.platform())) {
  log.main('Windows platform detected.');
  var programFiles = 'Program Files';
  if (/64/.test(os.arch())) {
    programFiles += '(x86)';
  }
  defaultOptions.logFile = path.join('C:', programFiles, 'Hearthstone', 'Hearthstone_Data', 'output_log.txt');
  defaultOptions.configFile = path.join(process.env.LOCALAPPDATA, 'Blizzard', 'Hearthstone', 'log.config');
} else {
  log.main('OS X platform detected.');
  defaultOptions.logFile = path.join(process.env.HOME, 'Library', 'Logs', 'Unity', 'Player.log');
  defaultOptions.configFile = path.join(process.env.HOME, 'Library', 'Preferences', 'Blizzard', 'Hearthstone', 'log.config');
}

// The watcher is an event emitter so we can emit events based on what we parse in the log.
function LogWatcher(options) {
    this.options = extend({}, defaultOptions, options);

    log.main('config file path: %s', this.options.configFile);
    log.main('log file path: %s', this.options.logFile);

    // Copy local config file to the correct location.
    // We're just gonna do this every time.
    var localConfigFile = path.join(__dirname, 'log.config');
    fs.createReadStream(localConfigFile).pipe(fs.createWriteStream(this.options.configFile));
    log.main('Copied log.config file to force Hearthstone to write to its log file.');
}
util.inherits(LogWatcher, EventEmitter);

LogWatcher.prototype.start = function () {
  var self = this;

  log.main('Log watcher started.');
  // Begin watching the Hearthstone log file.
  var fileSize = fs.statSync(this.options.logFile).size;
  var players = [];
  var gameOverCount = 0;
  var watcher = fs.watch(this.options.logFile, function (event, filename) {

    // We're only going to read the portion of the file that we have not read so far.
    var newFileSize = fs.statSync(self.options.logFile).size;
    var sizeDiff = newFileSize - fileSize;
    if (sizeDiff <= 0) {
      fileSize = newFileSize;
      return;
    }
    var buffer = new Buffer(sizeDiff);
    var fileDescriptor = fs.openSync(self.options.logFile, 'r');
    fs.readSync(fileDescriptor, buffer, 0, sizeDiff, fileSize + 1);
    fs.closeSync(fileDescriptor);
    fileSize = newFileSize;

    // Iterate over each line in the buffer.
    buffer.toString().split('\n').forEach(function (line) {

      // Check if a card is changing zones.
      var zoneChangeRegex = /name=(.*) id=(\d+).*to (FRIENDLY|OPPOSING) (.*)$/;
      if (zoneChangeRegex.test(line)) {
        var parts = zoneChangeRegex.exec(line);
        var data = {
          cardName: parts[1],
          cardId: parseInt(parts[2]),
          team: parts[3],
          zone: parts[4]
        };
        log.zoneChange('%s moved to %s %s.', data.cardName, data.team, data.zone)
        self.emit('zone-change', data);
      }

      // Check for players entering play and track their team IDs.
      var newPlayerRegex = /Entity=(.*) tag=TEAM_ID value=(.)$/;
      if (newPlayerRegex.test(line)) {
        var parts = newPlayerRegex.exec(line);
        players.push({
          name: parts[1],
          teamId: parseInt(parts[2])
        });
      }

      // Look for mulligan status line that only shows for the local FRIENDLY player.
      // Compare the ID to the team ID and set player zones appropriately.
      var mulliganCountRegex = /id=(\d) ChoiceType=MULLIGAN Cancelable=False CountMin=0 CountMax=\d$/;
      if (mulliganCountRegex.test(line)) {
        var parts = mulliganCountRegex.exec(line);
        var teamId = parseInt(parts[1]);
        players.forEach(function (player) {
          if (teamId === player.teamId) {
            player.team = 'FRIENDLY';
          } else {
            player.team = 'OPPOSING';
          }
        });
        log.gameStart('A game has started.')
        self.emit('game-start', players);
      }

      // Check if the game is over.
      var gameOverRegex = /Entity=(.*) tag=PLAYSTATE value=(LOST|WON)$/;
      if (gameOverRegex.test(line)) {
        var parts = gameOverRegex.exec(line);
        // Set the status for the appropriate player.
        players.forEach(function (player) {
          if (player.name === parts[1]) {
            player.status = parts[2];
          }
        });
        gameOverCount++;
        // When both players have lost, emit a game-over event.
        if (gameOverCount === 2) {
          log.gameOver('The current game has ended.');
          self.emit('game-over', players);
          gameOverCount = 0;
          players = [];
        }
      }

    });

  });

  self.stop = function () {
    watcher.close();
    delete self.stop;
  };
};

LogWatcher.prototype.stop = function () {};

// Set the entire module to our emitter.
module.exports = LogWatcher;
<commit_msg>Switched to use the platform-specific end of line character for splitting up the file buffer.<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var fs = require('fs');
var path = require('path');
var os = require('os');
var extend = require('extend');

var defaultOptions = {};

var debug = require('debug');
// Define some debug logging functions for easy and readable debug messages.
var log = {
  main: debug('HLW'),
  gameStart: debug('HLW:game-start'),
  zoneChange: debug('HLW:zone-change'),
  gameOver: debug('HLW:game-over')
};

// Determine the default location of the config and log files.
if (/^win/.test(os.platform())) {
  log.main('Windows platform detected.');
  var programFiles = 'Program Files';
  if (/64/.test(os.arch())) {
    programFiles += '(x86)';
  }
  defaultOptions.logFile = path.join('C:', programFiles, 'Hearthstone', 'Hearthstone_Data', 'output_log.txt');
  defaultOptions.configFile = path.join(process.env.LOCALAPPDATA, 'Blizzard', 'Hearthstone', 'log.config');
} else {
  log.main('OS X platform detected.');
  defaultOptions.logFile = path.join(process.env.HOME, 'Library', 'Logs', 'Unity', 'Player.log');
  defaultOptions.configFile = path.join(process.env.HOME, 'Library', 'Preferences', 'Blizzard', 'Hearthstone', 'log.config');
}

// The watcher is an event emitter so we can emit events based on what we parse in the log.
function LogWatcher(options) {
    this.options = extend({}, defaultOptions, options);

    log.main('config file path: %s', this.options.configFile);
    log.main('log file path: %s', this.options.logFile);

    // Copy local config file to the correct location.
    // We're just gonna do this every time.
    var localConfigFile = path.join(__dirname, 'log.config');
    fs.createReadStream(localConfigFile).pipe(fs.createWriteStream(this.options.configFile));
    log.main('Copied log.config file to force Hearthstone to write to its log file.');
}
util.inherits(LogWatcher, EventEmitter);

LogWatcher.prototype.start = function () {
  var self = this;

  log.main('Log watcher started.');
  // Begin watching the Hearthstone log file.
  var fileSize = fs.statSync(this.options.logFile).size;
  var players = [];
  var gameOverCount = 0;
  var watcher = fs.watch(this.options.logFile, function (event, filename) {

    // We're only going to read the portion of the file that we have not read so far.
    var newFileSize = fs.statSync(self.options.logFile).size;
    var sizeDiff = newFileSize - fileSize;
    if (sizeDiff <= 0) {
      fileSize = newFileSize;
      return;
    }
    var buffer = new Buffer(sizeDiff);
    var fileDescriptor = fs.openSync(self.options.logFile, 'r');
    fs.readSync(fileDescriptor, buffer, 0, sizeDiff, fileSize + 1);
    fs.closeSync(fileDescriptor);
    fileSize = newFileSize;

    // Iterate over each line in the buffer.
    buffer.toString().split(os.EOL).forEach(function (line) {

      // Check if a card is changing zones.
      var zoneChangeRegex = /name=(.*) id=(\d+).*to (FRIENDLY|OPPOSING) (.*)$/;
      if (zoneChangeRegex.test(line)) {
        var parts = zoneChangeRegex.exec(line);
        var data = {
          cardName: parts[1],
          cardId: parseInt(parts[2]),
          team: parts[3],
          zone: parts[4]
        };
        log.zoneChange('%s moved to %s %s.', data.cardName, data.team, data.zone)
        self.emit('zone-change', data);
      }

      // Check for players entering play and track their team IDs.
      var newPlayerRegex = /Entity=(.*) tag=TEAM_ID value=(.)$/;
      if (newPlayerRegex.test(line)) {
        var parts = newPlayerRegex.exec(line);
        players.push({
          name: parts[1],
          teamId: parseInt(parts[2])
        });
      }

      // Look for mulligan status line that only shows for the local FRIENDLY player.
      // Compare the ID to the team ID and set player zones appropriately.
      var mulliganCountRegex = /id=(\d) ChoiceType=MULLIGAN Cancelable=False CountMin=0 CountMax=\d$/;
      if (mulliganCountRegex.test(line)) {
        var parts = mulliganCountRegex.exec(line);
        var teamId = parseInt(parts[1]);
        players.forEach(function (player) {
          if (teamId === player.teamId) {
            player.team = 'FRIENDLY';
          } else {
            player.team = 'OPPOSING';
          }
        });
        log.gameStart('A game has started.')
        self.emit('game-start', players);
      }

      // Check if the game is over.
      var gameOverRegex = /Entity=(.*) tag=PLAYSTATE value=(LOST|WON)$/;
      if (gameOverRegex.test(line)) {
        var parts = gameOverRegex.exec(line);
        // Set the status for the appropriate player.
        players.forEach(function (player) {
          if (player.name === parts[1]) {
            player.status = parts[2];
          }
        });
        gameOverCount++;
        // When both players have lost, emit a game-over event.
        if (gameOverCount === 2) {
          log.gameOver('The current game has ended.');
          self.emit('game-over', players);
          gameOverCount = 0;
          players = [];
        }
      }

    });

  });

  self.stop = function () {
    watcher.close();
    delete self.stop;
  };
};

LogWatcher.prototype.stop = function () {};

// Set the entire module to our emitter.
module.exports = LogWatcher;
<|endoftext|>


<commit_before>'use strict';

const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
const path = require('path');

module.exports = {
  name: 'ember-site-tour',

  _options: {},

  included(app) {
    this._super.included(app);
    this._ensureThisImport();

    // Setup default options
    let options = Object.assign({
      importHopscotchJS: true,
      importHopscotchCSS: false
    }, app.options['ember-site-tour'] || {});

    this._options = options;

    if (options.importHopscotchJS) {
      this.import('vendor/hopscotch/js/hopscotch.js');
    }

    if (options.importHopscotchCSS) {
      this.import('vendor/hopscotch/css/hopscotch.css');
      this.import('vendor/hopscotch-override.css');
    }
  },

  treeForVendor(vendorTree) {
    let hopscotchPath = this._getPath();

    let trees = [];
    if (vendorTree) {
      trees.push(vendorTree);
    }

    let hopscotchTree = new Funnel(hopscotchPath, {
      include: ['js/hopscotch.js', 'css/hopscotch.css'],
      destDir: 'hopscotch'
    });

    trees.push(hopscotchTree);

    return new MergeTrees(trees, { overwrite: true });
  },

  treeForPublic(tree) {
    this._requireBuildPackages();

    if (!this.app) {
      return tree;
    }

    let importHopscotchCSS = this._options.importHopscotchCSS;

    if (importHopscotchCSS) {
      let hopscotchPath = this._getPath();

      return new Funnel(hopscotchPath, {
        srcDir: '/img',
        destDir: '/assets/img'
      });
    }

    return tree;
  },

  _getPath() {
    let hopscotchPath = path.dirname(require.resolve('hopscotch'));

    // The path returned here is e.g. node_modules/hopscotch/dist/js
    // We want to move one step out to get the dist folder
    hopscotchPath = hopscotchPath.replace('/dist/js', '/dist');
    hopscotchPath = hopscotchPath.replace('\\dist\\js', '\\dist');

    return hopscotchPath;
  },

  _ensureThisImport() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        let app = this._findHost();
        app.import(asset, options);
      };
    }
  }
};
<commit_msg>Stop using _requireBuildPackages()<commit_after>'use strict';

const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
const path = require('path');

module.exports = {
  name: 'ember-site-tour',

  _options: {},

  included(app) {
    this._super.included(app);
    this._ensureThisImport();

    // Setup default options
    let options = Object.assign({
      importHopscotchJS: true,
      importHopscotchCSS: false
    }, app.options['ember-site-tour'] || {});

    this._options = options;

    if (options.importHopscotchJS) {
      this.import('vendor/hopscotch/js/hopscotch.js');
    }

    if (options.importHopscotchCSS) {
      this.import('vendor/hopscotch/css/hopscotch.css');
      this.import('vendor/hopscotch-override.css');
    }
  },

  treeForVendor(vendorTree) {
    let hopscotchPath = this._getPath();

    let trees = [];
    if (vendorTree) {
      trees.push(vendorTree);
    }

    let hopscotchTree = new Funnel(hopscotchPath, {
      include: ['js/hopscotch.js', 'css/hopscotch.css'],
      destDir: 'hopscotch'
    });

    trees.push(hopscotchTree);

    return new MergeTrees(trees, { overwrite: true });
  },

  treeForPublic(tree) {
    if (!this.app) {
      return tree;
    }

    let importHopscotchCSS = this._options.importHopscotchCSS;

    if (importHopscotchCSS) {
      let hopscotchPath = this._getPath();

      return new Funnel(hopscotchPath, {
        srcDir: '/img',
        destDir: '/assets/img'
      });
    }

    return tree;
  },

  _getPath() {
    let hopscotchPath = path.dirname(require.resolve('hopscotch'));

    // The path returned here is e.g. node_modules/hopscotch/dist/js
    // We want to move one step out to get the dist folder
    hopscotchPath = hopscotchPath.replace('/dist/js', '/dist');
    hopscotchPath = hopscotchPath.replace('\\dist\\js', '\\dist');

    return hopscotchPath;
  },

  _ensureThisImport() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        let app = this._findHost();
        app.import(asset, options);
      };
    }
  }
};
<|endoftext|>


<commit_before> express = require('express');
let bodyParser = require('body-parser');
let request = require('request');
let app = express();
let count = 0;

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));

// Server frontpage
app.get('/', function (req, res) {
    res.send('This is Tim\'s TestBot Server');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'testbot_verify_token') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// handler receiving messages
app.post('/webhook', function (req, res) {
    let events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        let event = events[i];
        if (event.message && event.message.text) {
            sendMessage(event.sender.id, {text: "Echo message"+count+":\r\n " + event.message.text});
        }
    }
    res.sendStatus(200);
});

// generic function sending messages
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};<commit_msg>Fixed:count problems<commit_after> express = require('express');
let bodyParser = require('body-parser');
let request = require('request');
let app = express();
let count = 0;

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));

// Server frontpage
app.get('/', function (req, res) {
    res.send('This is Tim\'s TestBot Server');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'testbot_verify_token') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// handler receiving messages
app.post('/webhook', function (req, res) {
    let events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        let event = events[i];
        if (event.message && event.message.text) {
            sendMessage(event.sender.id, {text: "Echo message"+count+":\r\n " + event.message.text});
            count++;
        }
    }
    res.sendStatus(200);
});

// generic function sending messages
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};<|endoftext|>


<commit_before>require('dotenv').load()
const restify = require('restify')
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const sessions = require('client-sessions')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const User = require('./src/model/user.js')

mongoose.connect(process.env.MONGODB_URI, (err) => {
  if (err) {
    console.error(err)
    process.exit(1)
  }
  console.log('Connected to MongoDB')
})

const server = restify.createServer()
server.use(restify.queryParser())
server.use(restify.bodyParser())
server.use(sessions({
  cookieName: 'session',
  secret: 'lol',
  duration: 182 * 24 * 60 * 60 * 1000
}))
server.use(passport.initialize())
server.use(passport.session())

passport.use(new LocalStrategy({ passReqToCallback: true }, require('./src/route/users.js')))

passport.serializeUser((user, done) => {
  done(null, user._id)
})

passport.deserializeUser((id, done) => {
  User.findById(id).exec()
    .then((user) => {
      done(null, user)
    })
    .catch((err) => {
      done(err)
    })
})

server.post('/users/:username/scores/:number/', require('./src/route/scores.js'))
server.post('/users/:username/sessions/', require('./src/route/sessions.js'))

server.post('/users/:username/', passport.authenticate('local'), (req, res, next) => {
  User.findOne({ username: req.params.username }).exec()
    .then((user) => {
      return res.json({
        status: 'success',
        data: { user }
      })
    })
    .catch((err) => {
      console.error(err)
      return res.json({
        status: 'error',
        message: err
      })
    })

  next()
})

server.get('/hello/:name', (req, res, next) => {
  res.send(`Hello ${req.params.name}`)
  next()
})

server.listen(process.env.PORT, () => {
  console.log(`${server.name} listening at ${server.url}`)
})
<commit_msg>Fix trailing slashes in routes<commit_after>require('dotenv').load()
const restify = require('restify')
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const sessions = require('client-sessions')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const User = require('./src/model/user.js')

mongoose.connect(process.env.MONGODB_URI, (err) => {
  if (err) {
    console.error(err)
    process.exit(1)
  }
  console.log('Connected to MongoDB')
})

const server = restify.createServer()
server.use(restify.queryParser())
server.use(restify.bodyParser())
server.use(sessions({
  cookieName: 'session',
  secret: 'lol',
  duration: 182 * 24 * 60 * 60 * 1000
}))
server.use(passport.initialize())
server.use(passport.session())

passport.use(new LocalStrategy({ passReqToCallback: true }, require('./src/route/users.js')))

passport.serializeUser((user, done) => {
  done(null, user._id)
})

passport.deserializeUser((id, done) => {
  User.findById(id).exec()
    .then((user) => {
      done(null, user)
    })
    .catch((err) => {
      done(err)
    })
})

server.post('/users/:username/scores/:number', require('./src/route/scores.js'))
server.post('/users/:username/scores', require('./src/route/scores.js'))
server.post('/users/:username/sessions', require('./src/route/sessions.js'))

server.post('/users/:username', passport.authenticate('local'), (req, res, next) => {
  User.findOne({ username: req.params.username }).exec()
    .then((user) => {
      return res.json({
        status: 'success',
        data: { user }
      })
    })
    .catch((err) => {
      console.error(err)
      return res.json({
        status: 'error',
        message: err
      })
    })

  next()
})

server.get('/hello/:name', (req, res, next) => {
  res.send(`Hello ${req.params.name}`)
  next()
})

server.listen(process.env.PORT, () => {
  console.log(`${server.name} listening at ${server.url}`)
})
<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.deepmerge = factory();
    }
}(this, function () {

function isMergeableObject(val) {
    var nonNullObject = val && typeof val === 'object'

    return nonNullObject
        && Object.prototype.toString.call(val) !== '[object RegExp]'
        && Object.prototype.toString.call(val) !== '[object Date]'
}

return function deepmerge(target, src) {
    var array = Array.isArray(src);
    var dst = array && [] || {};

    if (array) {
        target = target || [];
        dst = dst.concat(target);
        src.forEach(function(e, i) {
            if (typeof dst[i] === 'undefined') {
                dst[i] = e;
            } else if (isMergeableObject(e)) {
                dst[i] = deepmerge(target[i], e);
            } else {
                if (target.indexOf(e) === -1) {
                    dst.push(e);
                }
            }
        });
    } else {
        if (isMergeableObject(target)) {
            Object.keys(target).forEach(function (key) {
                dst[key] = target[key];
            })
        }
        Object.keys(src).forEach(function (key) {
            if (!isMergeableObject(src[key])) {
                dst[key] = src[key];
            } else {
                if (!target[key]) {
                    dst[key] = src[key];
                } else {
                    dst[key] = deepmerge(target[key], src[key]);
                }
            }
        });
    }

    return dst;
}

}));
<commit_msg>Small refactors for clarity<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.deepmerge = factory();
    }
}(this, function () {

function isMergeableObject(val) {
    var nonNullObject = val && typeof val === 'object'

    return nonNullObject
        && Object.prototype.toString.call(val) !== '[object RegExp]'
        && Object.prototype.toString.call(val) !== '[object Date]'
}

return function deepmerge(target, src) {
    var array = Array.isArray(src);
    var dst = array ? [] : {};

    if (array) {
        target = target || [];
        dst = dst.concat(target);
        src.forEach(function(e, i) {
            if (typeof dst[i] === 'undefined') {
                dst[i] = e;
            } else if (isMergeableObject(e)) {
                dst[i] = deepmerge(target[i], e);
            } else if (target.indexOf(e) === -1) {
                dst.push(e);
            }
        });
    } else {
        if (isMergeableObject(target)) {
            Object.keys(target).forEach(function (key) {
                dst[key] = target[key];
            })
        }
        Object.keys(src).forEach(function (key) {
            if (!isMergeableObject(src[key])) {
                dst[key] = src[key];
            } else {
                if (!target[key]) {
                    dst[key] = src[key];
                } else {
                    dst[key] = deepmerge(target[key], src[key]);
                }
            }
        });
    }

    return dst;
}

}));
<|endoftext|>


<commit_before>/**
 *
 */
var fs=require('fs');
var http=require('http');
var async=require('async');

var documentRoot='./html/';

var devices=[
      {
    	  name:'Pin 7',
    	  direction:'in',
      }
]

function printFile(file, res){

}

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

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

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

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

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

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

			}else{

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

			}

		});
	}else{

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

	}

});

server.listen(8080);
<commit_msg>removed unused code, and set to port 80<commit_after>/**
 *
 */
var fs=require('fs');
var http=require('http');
var async=require('async');
var port=80;
var documentRoot='./html/';

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

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

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

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

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

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

			}else{

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

			}

		});
	}else{

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

	}

});

server.listen(port);
console.log('listening on: '+port);
<|endoftext|>


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

var units = ["Kelvin", "Celsius", "Fahrenhet"];

exports.createAppliance = function(applianceManager) {
  if (!app) {
    app = express();
    appMgr = applianceManager;
    devMgr = appMgr.deviceManager;
    app.get('/', index);
  }

  return app;
}

function index(req, res, next) {
  //now show all thermometers...
  var devices = devMgr.getDevicesByType(devMgr.DeviceType.TEMPERATURE_SENSOR);
  var processed = 0;
  var results = "";

  if (devices.length == 0) {
    res.send("No devices");
  }

  devices.forEach(function(device) {
    devMgr.getData(device, function(command, responseTLV) {

      var thermoData = responseTLV.getFirstChild(0xA1);

      var temperature = thermoData.getFirstChild(0x82).value.readInt32BE(0) / thermoData.getFirstChild(0x81).value.readUInt16BE(0);
      var unit = thermoData.getFirstChild(0x80).value.readUInt8(0);

      results = results + temperature + " " + units[unit] + "
";
      processed++;

      if (processed == devices.length) {
        res.send(results);
      }
    });
  });
}<commit_msg>use new TLV method<commit_after>var express = require('express');
var app;
var appMgr;
var devMgr;

var units = ["Kelvin", "Celsius", "Fahrenhet"];

exports.createAppliance = function(applianceManager) {
  if (!app) {
    app = express();
    appMgr = applianceManager;
    devMgr = appMgr.deviceManager;
    app.get('/', index);
  }

  return app;
}

function index(req, res, next) {
  //now show all thermometers...
  var devices = devMgr.getDevicesByType(devMgr.DeviceType.TEMPERATURE_SENSOR);
  var processed = 0;
  var results = "";

  if (devices.length == 0) {
    res.send("No devices");
  }

  devices.forEach(function(device) {
    devMgr.getData(device, function(command, responseTLV) {

      var thermoData = responseTLV.getFirstChild(0xA1);

      var temperature = thermoData.getFirstChild(0x82).getIntValue() / thermoData.getFirstChild(0x81).getUIntValue();
      var unit = thermoData.getFirstChild(0x80).getUIntValue();

      results = results + temperature + " " + units[unit] + "
";
      processed++;

      if (processed == devices.length) {
        res.send(results);
      }
    });
  });
}<|endoftext|>


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

module.exports = axios.interceptors.response.use(
  function logResponse(res) {
    console.log('%c Request Success:', 'color: #4CAF50; font-weight: bold', res);
    return res;
  },

  function logPromiseError(err) {
    console.log('%c Request Error:', 'color: #EC6060; font-weight: bold', err);
    return Promise.reject(err);
  }
);
<commit_msg>UMDify haha<commit_after>var axios = require('axios');

function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['axios'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS
    factory(require('axios'));
  } else {
    // Browser globals
    factory(root.axios);
  }
}(this, function (axios) {
  return axios.interceptors.response.use(
    function logResponse(res) {
      console.log('%c Request Success:', 'color: #4CAF50; font-weight: bold', res);
      return res;
    },

    function logPromiseError(err) {
      console.log('%c Request Error:', 'color: #EC6060; font-weight: bold', err);
      return Promise.reject(err);
    }
  );
}));
<|endoftext|>


<commit_before>'use strict';

var Parth = require('parth');
var Runtime = require('runtime');
var vinylFS = require('vinyl-fs')

var cli = require('./lib/cli');
var util = require('./lib/util');
var __slice = Array.prototype.slice;

var Gulp = module.exports = Runtime.createClass({
  src: vinylFS.src,
  dest: vinylFS.dest,
  create: function Gulp(props){
    Gulp.super_.call(this, props);
    this.tasks = new Parth();

    this.log = this.log === void 0 || this.log;
    this.gulpfile = new Error().stack.match(/\/([^:()]+)/g)[2];

    if(this.repl){
      this.repl = require('gulp-repl')(this);
    }

    if(this.log && !util.isSilent){
      if(this.repl){
        util.log('REPL enabled');
      }
      if(util.logGulpfile){
        util.log('Using gulpfile', util.format.path(this.gulpfile));
      }
    }

    // add cli tasks and run the cli for this instance
    cli(this);
  }
});

/**
 * gulp.task
**/

Gulp.prototype.task = function(name, deps, handle){
  handle = util.type(handle || deps || name).function || '';
  deps = util.type(deps).array || util.type(name).array;
  name = util.type(name).string || util.type(handle.name).string || '';

  if(name && !deps && !handle){
    return (this.tasks.get(name) || {fn: null}).fn;
  } else if(handle && handle.name !== name){
    handle.displayName = name;
  }
  handle = handle || function(cb){ cb(); };

  if(name && deps && deps.length){
    var series = this.series.apply(this, deps.concat(handle));
    this.tasks.set(name, {name: name, fn: series});
  } else if(name){
    this.tasks.set(name, {name: name, fn: handle});
  }

  return this;
};

/**
 * gulp.watch
 **/
Gulp.prototype.watch = function(glob, opt, handle) {
  var fn = util.type(handle || opt).function;
  var tasks = util.type(opt).array;

  if(tasks){
    var composer = this.stack.apply(this, tasks);
    return vinylFS.watch(glob, function(/* arguments */){
      var args = __slice.call(arguments);
      composer.apply(null, fn ? args.concat(fn) : args);
    });
  }

  return vinylFS.watch(glob, opt, fn);
};

/**
 gulp.tree
**/
Gulp.prototype.tree = function(options){
  options = options || {};
  var depth = options.depth === void 0 || options.depth;

  if(depth && typeof depth !== 'number'){
    depth = 1;
  }

  var self = this;
  var tree = {label: options.label || '', nodes: []};

  if(!(this instanceof Runtime.Stack)){
    var tasks = Object.keys(this.tasks.store).filter(function(task){
      return !/^\:cli/.test(task);
    });

    if(options.simple){ return tasks; }

    tasks.forEach(function(name){
      var task = self.tasks.store[name];
      var node = {label: task.name};

      if(task.fn.stack instanceof Runtime.Stack){
        node = task.fn.stack.tree({
          host: task,
          depth: depth < options.depth ? depth + 1 : false
        });
      }

      tree.nodes.push(node);
    });
    return tree;
  }

  var sites = this.length ? this : this.reduce();

  sites.forEach(function(task){
    if(!task || !task.fn){ return; }
    var node = task;

    if(task.fn.stack instanceof Runtime.Stack){
      node = task.fn.stack.tree({
        host: task,
        depth: depth < options.depth && (depth + 1) || false
      });
    }

    tree.label += (tree.label && ', ' + node.label) || node.label;
    tree.nodes.push(node);
  });

  if(options.host && options.host.name){
    tree.label = options.host.name;
    tree.nodes = tree.nodes.filter(function(node){
      return node.label !== tree.label;
    });
    tree.label = util.chalk.underline(tree.label);
  }

  return tree;
};

/**
 maps all the arguments of gulp.stack to functions
**/
Gulp.prototype.reduceStack = function(stack, site){
  var task = this.tasks.get(site) || (
    typeof site === 'function' && {fn: site}
  );

  if(!task){
    util.log('Task `%s` is not defined yet',
      util.format.task(site)
    );

    util.log('Not sure how to do that? See: %s',
      util.format.link(util.docs.task)
    );

    throw new Error('task ' + site + ' not defined yet');
  }

  stack.push(task);

  if(task.fn.stack instanceof Runtime.Stack){
    task.mode = task.fn.stack.wait ? 'series' : 'parallel';
  } else {
    task.label = task.name || task.fn.displayName || task.fn.name;
  }
};

/**
 logging
**/

Gulp.prototype.onHandleStart = function(task, stack){
  if(!this.log || (task.params && task.params.cli)){
    return;
  }

  task.time = process.hrtime();

  if(!stack.time){
    stack.time = process.hrtime();

    stack.deep = stack.length > 1;
    stack.mode = stack.wait ? 'series' : 'parallel';
    stack.label = stack.tree().label;

    if(stack.deep && !stack.host){
      util.log('Start', util.format.task(stack));
    }
  }

  if(task.mode){
    task.label = task.fn.stack.tree().label;
  }

  if(task.mode || (!stack.deep && !stack.host)){
    util.log('Start', util.format.task(task, stack));
  }
};

Gulp.prototype.onHandleEnd = function(task, stack){
  if(this.log && !(task.params && task.params.cli)){
    if(!task.mode && stack.deep){
      util.log('- %s took %s',
        util.format.task(task),
        util.format.time(task.time)
      );
    }

    if(stack.end && !stack.host){
      util.log('Ended %s after %s',
        util.format.task(stack.deep ? stack : task),
        util.format.time(stack.time)
      );
    }
  }

  clearTimeout(stack.timeout);
  if(this.repl && stack.end && !stack.host){
    var self = this;
    stack.timeout = setTimeout(function(){
      self.repl.prompt();
    }, 250);
  }
};

/**
 error handling
**/
Gulp.prototype.onHandleError = function(err, site, stack){
  console.log('helloo', arguments);
  util.log('%s in %s',
    util.format.error('error'),
    stack.label || stack.tree().label,
    !this.repl ? '\n' + err.stack : ''
  );

  console.log('%s failed after %s',
    util.format.error(site.label),
    util.format.time(site.time)
  );

  if(!this.repl){ throw err; }
};

/**
  With some sugar on top please
**/

Gulp.prototype.start = function(/* arguments */){
  this.stack.apply(this, arguments.length ? arguments : ['default'])();
  return this;
};

Gulp.prototype.series = function(/* arguments */){
  var args = __slice.call(arguments);
  var props = util.type(args[args.length - 1]).plainObject && args.pop() || {};
  var tasks = args.concat(util.merge(props, {wait: true}));
  return this.stack.apply(this, tasks);
};

Gulp.prototype.parallel = function(/* arguments */){
  var args = __slice.call(arguments);
  var props = util.type(args[args.length - 1]).plainObject && args.pop() || {};
  var tasks = args.concat(util.merge(props, {wait: false}));
  return this.stack.apply(this, tasks);
};
<commit_msg>dev: final cleaning before release<commit_after>'use strict';

var Parth = require('parth');
var Runtime = require('runtime');
var vinylFS = require('vinyl-fs')

var cli = require('./lib/cli');
var util = require('./lib/util');
var __slice = Array.prototype.slice;

var Gulp = module.exports = Runtime.createClass({
  src: vinylFS.src,
  dest: vinylFS.dest,
  create: function Gulp(props){
    Gulp.super_.call(this, props);
    this.tasks = new Parth();

    this.log = this.log === void 0 || this.log;
    this.gulpfile = util.getGulpFile();

    if(this.repl){
      this.repl = require('gulp-repl')(this);
      util.log('REPL enabled');
    }

    if(this.log){
      util.log('Using gulpfile', util.format.path(this.gulpfile));
    }

    // add cli tasks and run the cli for this instance
    cli(this);
  }
});

/**
 * gulp.task
**/

Gulp.prototype.task = function(name, deps, handle){
  handle = util.type(handle || deps || name).function || '';
  deps = util.type(deps).array || util.type(name).array;
  name = util.type(name).string || util.type(handle.name).string;

  if(name && !deps && !handle){
    return (this.tasks.get(name) || {fn: null}).fn;
  }

  if(handle && handle.name !== name){
    handle.displayName = name;
  }

  if(name && deps && handle){
    var tasks = deps.concat(handle);
    var composer = this.series.apply(this, tasks);
    this.tasks.set(name, {name: name, fn: composer});
  } else if(name && deps){
    var composer = this.stack.apply(this, deps);
    this.tasks.set(name, {name: name, fn: composer});
  } else if(name){
    this.tasks.set(name, {name: name, fn: handle});
  }

  return this;
};

/**
 * gulp.watch
 **/
Gulp.prototype.watch = function(glob, opt, handle) {
  var fn = util.type(handle || opt).function;
  var tasks = util.type(opt).array;

  if(tasks){
    var composer = this.stack.apply(this, tasks);
    return vinylFS.watch(glob, function(/* arguments */){
      var args = __slice.call(arguments);
      composer.apply(null, fn ? args.concat(fn) : args);
    });
  }

  return vinylFS.watch(glob, opt, fn);
};

/**
 gulp.tree
**/
Gulp.prototype.tree = function(options){
  options = options || {};
  var depth = options.depth === void 0 || options.depth;

  if(depth && typeof depth !== 'number'){
    depth = 1;
  }

  var self = this;
  var tree = {label: options.label || '', nodes: []};

  if(!(this instanceof Runtime.Stack)){
    var tasks = Object.keys(this.tasks.store).filter(function(task){
      return !/^\:cli/.test(task);
    });

    if(options.simple){ return tasks; }

    tasks.forEach(function(name){
      var task = self.tasks.store[name];
      var node = {label: task.name};

      if(task.fn.stack instanceof Runtime.Stack){
        node = task.fn.stack.tree({
          host: task,
          depth: depth < options.depth ? depth + 1 : false
        });
      }

      tree.nodes.push(node);
    });
    return tree;
  }

  var sites = this.length ? this : this.reduce();

  sites.forEach(function(task){
    if(!task || !task.fn){ return; }
    var node = task;

    if(task.fn.stack instanceof Runtime.Stack){
      node = task.fn.stack.tree({
        host: task,
        depth: depth < options.depth && (depth + 1) || false
      });
    }

    tree.label += (tree.label && ', ' + node.label) || node.label;
    tree.nodes.push(node);
  });

  if(options.host && options.host.name){
    tree.label = options.host.name;
    tree.nodes = tree.nodes.filter(function(node){
      return node.label !== tree.label;
    });
    tree.label = util.chalk.underline(tree.label);
  }

  return tree;
};

/**
 maps all the arguments of gulp.stack to functions
**/
Gulp.prototype.reduceStack = function(stack, site){
  var task = typeof site === 'function'
    ? {fn: site}
    : this.tasks.get(site);

  if(!task){
    util.log('Task `%s` is not defined yet',
      util.format.task(site)
    );

    util.log('Not sure how to do that? See %s',
      util.format.link(util.docs.task)
    );

    if(util.isFromCLI(this)){
      return process.exit(1);
    }

    throw new Error(
      'task `' + util.format.task(site) + '` is not defined yet'
    );
  }

  stack.push(task);

  if(task.fn.stack instanceof Runtime.Stack){
    task.mode = task.fn.stack.wait ? 'series' : 'parallel';
  } else {
    task.label = task.name || task.fn.displayName || task.fn.name;
  }
};

/**
 logging
**/

Gulp.prototype.onHandleStart = function(task, stack){
  if(!this.log || (task.params && task.params.cli)){
    return;
  }

  if(!stack.time){
    stack.time = process.hrtime();

    stack.deep = stack.length > 1;
    stack.mode = stack.wait ? 'series' : 'parallel';
    stack.label = stack.tree().label;

    if(stack.deep && !stack.host){
      util.log('Start', util.format.task(stack));
    }
  }

  if(task.mode){
    task.label = task.fn.stack.tree().label;
  }

  if(task.mode || (!stack.deep && !stack.host)){
    util.log('Start', util.format.task(task));
  }

  task.time = process.hrtime();
};

Gulp.prototype.onHandleEnd = function(task, stack){
  if(this.log && !(task.params && task.params.cli)){

    if(stack.host && !task.mode){
      util.log(' %s took %s',
        util.format.task(task),
        util.format.time(task.time)
      );
    } else if(stack.end){
      util.log('Ended %s after %s',
        util.format.task(stack.deep ? stack : task),
        util.format.time(stack.time)
      );
    }
  }

  if(this.repl && stack.end && !stack.host){
    var self = this;
    clearTimeout(this.timeout);
    this._timeout = setTimeout(function (){
      self.repl.prompt();
    }, 150);
  }
};

/**
 error handling
**/
Gulp.prototype.onHandleError = function(err, site, stack){
  util.log('%s in %s',
    util.format.error('error'),
    stack.label || stack.tree().label,
    this.repl ? '' : '\n' + err.stack
  );

  console.log('%s failed after %s',
    util.format.error(site.label),
    util.format.time(site.time)
  );

  if(!this.repl){ throw err; }
};

/**
  With some sugar on top please
**/

Gulp.prototype.start = function(/* arguments */){
  if(!arguments.length){ return; }
  this.stack.apply(this, arguments.length ? arguments : ['default'])();
  return this;
};

Gulp.prototype.series = function(/* arguments */){
  var args = __slice.call(arguments);
  var props = util.type(args[args.length - 1]).plainObject && args.pop() || {};
  var tasks = args.concat(util.merge(props, {wait: true}));
  return this.stack.apply(this, tasks);
};

Gulp.prototype.parallel = function(/* arguments */){
  var args = __slice.call(arguments);
  var props = util.type(args[args.length - 1]).plainObject && args.pop() || {};
  var tasks = args.concat(util.merge(props, {wait: false}));
  return this.stack.apply(this, tasks);
};
<|endoftext|>


<commit_before>var fs = require("fs");
var http = require("http");
var https = require("https");
var path = require("path");
var url = require("url");
var events = require("events").EventEmitter;
var util = require("util");

var cheerio = require("cheerio");

// The "Image" class.
function Image(image, address){

	var at = this.attributes = image.attribs;

	this.name = path.basename(at.src, path.extname(at.src));
	this.saveTo = path.dirname(require.main.filename) + "/";
	this.extension = path.extname(at.src);
	this.address = url.resolve(address, at.src);
	this.fromAddress = address;
}

Image.prototype.save = function(callback){

	var parsedUrl = url.parse(this.address);

	// Make a reference to the current instance.
	var ref = this;

	// Support HTTPS.
	var protocol = http;
	if(parsedUrl.protocol == "https:") {
		protocol = https;
	}

	var request = protocol.request(this.address, function(response){

		if(response.statusCode != 200){

			console.error("Image scraper(3): image couldn't be found. (statusCode:" + statusCode + ")");
		}
		else{

			var imageFile = fs.createWriteStream(path.normalize(ref.saveTo + ref.name + ref.extension));

			imageFile.on("error", function(e){

				console.error("Image scraper(4): error while loading image: " + e + ".");
			});

			response.on("data", function(data){

				imageFile.write(data);
			});

			response.on("end", function(){

				imageFile.end();

				if(typeof(callback) == "function") callback.call(ref);
			});
		}
	});

	request.end();
	request.on("error", function(e){

		console.error(e);
	});
};

function Scraper(address){

	events.call(this);
	this.address = address;
}

// Inherit the methods of "events".
util.inherits(Scraper, events);

Scraper.prototype.scrape = function(callback){

	if(typeof(callback) == "function"){

		this.on("image", callback);
	}

	var parsedUrl = url.parse(this.address);

	// Make a reference to the current instance.
	var ref = this;

	// Support HTTPS.
	var protocol = http;
	if(parsedUrl.protocol == "https:") {
		protocol = https;
	}

	var request = protocol.request(this.address, function(response){

		if(response.statusCode != 200){

			console.error("Image scraper(1): web page couldn't be found. (statusCode:" + statusCode + ")");
		}
		else{

			response.setEncoding("utf8");

			var previous = "",
				current;

			response.on("data", function(data){
				var current = previous + data;

				current.replace(/<img[\S\s]*?>/ig, function(m){

					var image = new Image(cheerio.load(m)("img")[0], ref.address);

					ref.emit("image", image);
				});

				previous = data;
			});

			response.on("end", function(){
				ref.emit("end");
			});
		}
	});
	request.end();

	request.on("error", function(e){

		console.error("Image scraper(2): error while loading web page: " + e + ".");
	});
};

module.exports = Scraper;<commit_msg>Whoops. Missed handling the status code logging correctly.<commit_after>var fs = require("fs");
var http = require("http");
var https = require("https");
var path = require("path");
var url = require("url");
var events = require("events").EventEmitter;
var util = require("util");

var cheerio = require("cheerio");

// The "Image" class.
function Image(image, address){

	var at = this.attributes = image.attribs;

	this.name = path.basename(at.src, path.extname(at.src));
	this.saveTo = path.dirname(require.main.filename) + "/";
	this.extension = path.extname(at.src);
	this.address = url.resolve(address, at.src);
	this.fromAddress = address;
}

Image.prototype.save = function(callback){

	var parsedUrl = url.parse(this.address);

	// Make a reference to the current instance.
	var ref = this;

	// Support HTTPS.
	var protocol = http;
	if(parsedUrl.protocol == "https:") {
		protocol = https;
	}

	var request = protocol.request(this.address, function(response){

		if(response.statusCode != 200){

			console.error("Image scraper(3): image couldn't be found. (statusCode:" + response.statusCode + ")");
			return request.end();
		}
		else{

			var imageFile = fs.createWriteStream(path.normalize(ref.saveTo + ref.name + ref.extension));

			imageFile.on("error", function(e){

				console.error("Image scraper(4): error while loading image: " + e + ".");
			});

			response.on("data", function(data){

				imageFile.write(data);
			});

			response.on("end", function(){

				imageFile.end();

				if(typeof(callback) == "function") callback.call(ref);
			});
		}
	});

	request.end();
	request.on("error", function(e){

		console.error(e);
	});
};

function Scraper(address){

	events.call(this);
	this.address = address;
}

// Inherit the methods of "events".
util.inherits(Scraper, events);

Scraper.prototype.scrape = function(callback){

	if(typeof(callback) == "function"){

		this.on("image", callback);
	}

	var parsedUrl = url.parse(this.address);

	// Make a reference to the current instance.
	var ref = this;

	// Support HTTPS.
	var protocol = http;
	if(parsedUrl.protocol == "https:") {
		protocol = https;
	}

	var request = protocol.request(this.address, function(response){

		if(response.statusCode != 200){
			console.error("Image scraper(1): web page couldn't be found. (statusCode:" + response.statusCode + ")");
			ref.emit("end");
			request.end();
			return process.exit(1);
		}
		else{

			response.setEncoding("utf8");

			var previous = "",
				current;

			response.on("data", function(data){
				var current = previous + data;

				current.replace(/<img[\S\s]*?>/ig, function(m){

					var image = new Image(cheerio.load(m)("img")[0], ref.address);

					ref.emit("image", image);
				});

				previous = data;
			});

			response.on("end", function(){
				ref.emit("end");
			});
		}
	});
	request.end();

	request.on("error", function(e){

		console.error("Image scraper(2): error while loading web page: " + e + ".");
	});
};

module.exports = Scraper;<|endoftext|>