<commit_before>/* jshint node: true */
'use strict';

var debug = require('cog/logger')('rtc-signaller');
var detect = require('rtc-core/detect');
var EventEmitter = require('events').EventEmitter;
var uuid = require('uuid');
var extend = require('cog/extend');
var throttle = require('cog/throttle');
var FastMap = require('collections/fast-map');

// initialise the list of valid "write" methods
var WRITE_METHODS = ['write', 'send'];
var CLOSE_METHODS = ['close'];

// initialise signaller metadata so we don't have to include the package.json
// TODO: make this checkable with some kind of prepublish script
var metadata = {
  version: '0.19.2'
};

/**
  # rtc-signaller

  The `rtc-signaller` module provides a transportless signalling
  mechanism for WebRTC.

  ## Purpose

  The signaller provides set of client-side tools that assist with the
  setting up an `PeerConnection` and helping them communicate. All that is
  required for the signaller to operate is a suitable messenger.

  A messenger is a simple object that implements node
  [EventEmitter](http://nodejs.org/api/events.html) style `on` events for
  `open`, `close`, `message` events, and also a `send` method by which
  data will be send "over-the-wire".

  By using this approach, we can conduct signalling over any number of
  mechanisms:

  - local, in memory message passing
  - via WebSockets and higher level abstractions (such as
    [primus](https://github.com/primus/primus))
  - also over WebRTC data-channels (very meta, and admittedly a little
    complicated).

  ## Getting Started

  While the signaller is capable of communicating by a number of different
  messengers (i.e. anything that can send and receive messages over a wire)
  it comes with support for understanding how to connect to an
  [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard) out of the box.

  The following code sample demonstrates how:

  <<< examples/getting-started.js

  ## Signal Flow Diagrams

  Displayed below are some diagrams how the signalling flow between peers
  behaves.  In each of the diagrams we illustrate three peers (A, B and C)
  participating discovery and coordinating RTCPeerConnection handshakes.

  In each case, only the interaction between the clients is represented not
  how a signalling server
  (such as [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard)) would
  pass on broadcast messages, etc.  This is done for two reasons:

  1. It is out of scope of this documentation.
  2. The `rtc-signaller` has been designed to work without having to rely on
     any intelligence in the server side signalling component.  In the
     instance that a signaller broadcasts all messages to all connected peers
     then `rtc-signaller` should be smart enough to make sure everything works
     as expected.

  ### Peer Discovery / Announcement

  This diagram illustrates the process of how peer `A` announces itself to
  peers `B` and `C`, and in turn they announce themselves.

  ![](https://raw.github.com/rtc-io/rtc-signaller/master/docs/announce.png)

  ### Editing / Updating the Diagrams

  Each of the diagrams has been generated using
  [mscgen](http://www.mcternan.me.uk/mscgen/index.html) and the source for
  these documents can be found in the `docs/` folder of this repository.

  ## Reference

  The `rtc-signaller` module is designed to be used primarily in a functional
  way and when called it creates a new signaller that will enable
  you to communicate with other peers via your messaging network.

  ```js
  // create a signaller from something that knows how to send messages
  var signaller = require('rtc-signaller')(messenger);
  ```

  As demonstrated in the getting started guide, you can also pass through
  a string value instead of a messenger instance if you simply want to
  connect to an existing `rtc-switchboard` instance.

**/
var sig = module.exports = function(messenger, opts) {

  // get the autoreply setting
  var autoreply = (opts || {}).autoreply;

  // create the signaller
  var signaller = new EventEmitter();

  // initialise the id
  var id = signaller.id = (opts || {}).id || uuid.v4();

  // initialise the attributes
  var attributes = signaller.attributes = {
    browser: detect.browser,
    browserVersion: detect.browserVersion,
    id: id,
    agent: 'signaller@' + metadata.version
  };

  // create the peers map
  var peers = signaller.peers = new FastMap();

  // initialise the data event name
  var dataEvent = (opts || {}).dataEvent || 'data';
  var openEvent = (opts || {}).openEvent || 'open';
  var writeMethod = (opts || {}).writeMethod || 'write';
  var closeMethod = (opts || {}).closeMethod || 'close';
  var initialized = false;
  var write;
  var close;
  var processor;
  var announceTimer = 0;

  function connectToPrimus(url) {
    // load primus
    sig.loadPrimus(url, function(err, Primus) {
      if (err) {
        return signaller.emit('error', err);
      }

      // create the actual messenger from a primus connection
      messenger = Primus.connect(url);

      // now init
      init();
    });
  }

  function extractProp(name) {
    return messenger[name];
  }

  function isF(target) {
    return typeof target == 'function';
  }

  function init() {
    // extract the write and close function references
    write = [writeMethod].concat(WRITE_METHODS).map(extractProp).filter(isF)[0];
    close = [closeMethod].concat(CLOSE_METHODS).map(extractProp).filter(isF)[0];

    // create the processor
    processor = require('./processor')(signaller);

    // if the messenger doesn't provide a valid write method, then complain
    if (typeof write != 'function') {
      throw new Error('provided messenger does not implement a "' +
        writeMethod + '" write method');
    }

    // handle message data events
    messenger.on(dataEvent, processor);

    // when the connection is open, then emit an open event and a connected event
    messenger.on(openEvent, function() {
      // TODO: deprecate the open event
      signaller.emit('open');
      signaller.emit('connected');
    });

    // flag as initialised
    initialized = true;
    signaller.emit('init');
  }

  // set the autoreply flag
  signaller.autoreply = autoreply === undefined || autoreply;

  function prepareArg(arg) {
    if (typeof arg == 'object' && (! (arg instanceof String))) {
      return JSON.stringify(arg);
    }
    else if (typeof arg == 'function') {
      return null;
    }

    return arg;
  }

  /**
    ### signaller#send(message, data*)

    Use the send function to send a message to other peers in the current
    signalling scope (if announced in a room this will be a room, otherwise
    broadcast to all peers connected to the signalling server).

  **/
  var send = signaller.send = function() {
    // iterate over the arguments and stringify as required
    // var metadata = { id: signaller.id };
    var args = [].slice.call(arguments);
    var dataline;

    // inject the metadata
    args.splice(1, 0, { id: signaller.id });
    dataline = args.map(prepareArg).filter(Boolean).join('|');

    // if we are not initialized, then wait until we are
    if (! initialized) {
      return signaller.once('init', function() {
        write.call(messenger, dataline);
      });
    }

    // send the data over the messenger
    return write.call(messenger, dataline);
  };

  /**
    ### announce(data?)

    The `announce` function of the signaller will pass an `/announce` message
    through the messenger network.  When no additional data is supplied to
    this function then only the id of the signaller is sent to all active
    members of the messenging network.

    #### Joining Rooms

    To join a room using an announce call you simply provide the name of the
    room you wish to join as part of the data block that you annouce, for
    example:

    ```js
    signaller.announce({ room: 'testroom' });
    ```

    Signalling servers (such as
    [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard)) will then
    place your peer connection into a room with other peers that have also
    announced in this room.

    Once you have joined a room, the server will only deliver messages that
    you `send` to other peers within that room.

    #### Providing Additional Announce Data

    There may be instances where you wish to send additional data as part of
    your announce message in your application.  For instance, maybe you want
    to send an alias or nick as part of your announce message rather than just
    use the signaller's generated id.

    If for instance you were writing a simple chat application you could join
    the `webrtc` room and tell everyone your name with the following announce
    call:

    ```js
    signaller.announce({
      room: 'webrtc',
      nick: 'Damon'
    });
    ```

    #### Announcing Updates

    The signaller is written to distinguish between initial peer announcements
    and peer data updates (see the docs on the announce handler below). As
    such it is ok to provide any data updates using the announce method also.

    For instance, I could send a status update as an announce message to flag
    that I am going offline:

    ```js
    signaller.announce({ status: 'offline' });
    ```

  **/
  signaller.announce = function(data, sender) {
    clearTimeout(announceTimer);

    // update internal attributes
    extend(attributes, data, { id: signaller.id });

    // send the attributes over the network
    return announceTimer = setTimeout(function() {
      (sender || send)('/announce', attributes);
    }, (opts || {}).announceDelay || 10);
  };

  /**
    ### isMaster(targetId)

    A simple function that indicates whether the local signaller is the master
    for it's relationship with peer signaller indicated by `targetId`.  Roles
    are determined at the point at which signalling peers discover each other,
    and are simply worked out by whichever peer has the lowest signaller id
    when lexigraphically sorted.

    For example, if we have two signaller peers that have discovered each
    others with the following ids:

    - `b11f4fd0-feb5-447c-80c8-c51d8c3cced2`
    - `8a07f82e-49a5-4b9b-a02e-43d911382be6`

    They would be assigned roles:

    - `b11f4fd0-feb5-447c-80c8-c51d8c3cced2`
    - `8a07f82e-49a5-4b9b-a02e-43d911382be6` (master)

  **/
  signaller.isMaster = function(targetId) {
    var peer = peers.get(targetId);

    return peer && peer.roleIdx !== 0;
  };

  /**
    ### leave()

    Tell the signalling server we are leaving.  Calling this function is
    usually not required though as the signalling server should issue correct
    `/leave` messages when it detects a disconnect event.

  **/
  signaller.leave = function() {
    // send the leave signal
    send('/leave', { id: id });

    // call the close method
    if (typeof close == 'function') {
      close.call(messenger);
    }
  };

  /**
    ### to(targetId)

    Use the `to` function to send a message to the specified target peer.
    A large parge of negotiating a WebRTC peer connection involves direct
    communication between two parties which must be done by the signalling
    server.  The `to` function provides a simple way to provide a logical
    communication channel between the two parties:

    ```js
    var send = signaller.to('e95fa05b-9062-45c6-bfa2-5055bf6625f4').send;

    // create an offer on a local peer connection
    pc.createOffer(
      function(desc) {
        // set the local description using the offer sdp
        // if this occurs successfully send this to our peer
        pc.setLocalDescription(
          desc,
          function() {
            send('/sdp', desc);
          },
          handleFail
        );
      },
      handleFail
    );
    ```

  **/
  signaller.to = function(targetId) {
    // create a sender that will prepend messages with /to|targetId|
    var sender = function() {
      // get the peer (yes when send is called to make sure it hasn't left)
      var peer = signaller.peers.get(targetId);
      var args;

      if (! peer) {
        throw new Error('Unknown peer: ' + targetId);
      }

      // if the peer is inactive, then abort
      if (peer.inactive) {
        return;
      }

      args = [
        '/to',
        targetId
      ].concat([].slice.call(arguments));

      // inject metadata
      args.splice(3, 0, { id: signaller.id });

      setTimeout(function() {
        var msg = args.map(prepareArg).filter(Boolean).join('|');
        debug('TX (' + targetId + '): ' + msg);

        write.call(messenger, msg);
      }, 0);
    };

    return {
      announce: function(data) {
        return signaller.announce(data, sender);
      },

      send: sender,
    }
  };

  // if the messenger is a string, then we are going to attach to a
  // ws endpoint and automatically set up primus
  if (typeof messenger == 'string' || (messenger instanceof String)) {
    connectToPrimus(messenger);
  }
  // otherwise, initialise the connection
  else {
    init();
  }

  return signaller;
};

sig.loadPrimus = require('./primus-loader');<commit_msg>Restructure event binding to support native browser WebSockets also<commit_after>/* jshint node: true */
'use strict';

var debug = require('cog/logger')('rtc-signaller');
var detect = require('rtc-core/detect');
var EventEmitter = require('events').EventEmitter;
var uuid = require('uuid');
var extend = require('cog/extend');
var throttle = require('cog/throttle');
var FastMap = require('collections/fast-map');

// initialise the list of valid "write" methods
var WRITE_METHODS = ['write', 'send'];
var CLOSE_METHODS = ['close'];

// initialise signaller metadata so we don't have to include the package.json
// TODO: make this checkable with some kind of prepublish script
var metadata = {
  version: '0.19.2'
};

/**
  # rtc-signaller

  The `rtc-signaller` module provides a transportless signalling
  mechanism for WebRTC.

  ## Purpose

  The signaller provides set of client-side tools that assist with the
  setting up an `PeerConnection` and helping them communicate. All that is
  required for the signaller to operate is a suitable messenger.

  A messenger is a simple object that implements node
  [EventEmitter](http://nodejs.org/api/events.html) style `on` events for
  `open`, `close`, `message` events, and also a `send` method by which
  data will be send "over-the-wire".

  By using this approach, we can conduct signalling over any number of
  mechanisms:

  - local, in memory message passing
  - via WebSockets and higher level abstractions (such as
    [primus](https://github.com/primus/primus))
  - also over WebRTC data-channels (very meta, and admittedly a little
    complicated).

  ## Getting Started

  While the signaller is capable of communicating by a number of different
  messengers (i.e. anything that can send and receive messages over a wire)
  it comes with support for understanding how to connect to an
  [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard) out of the box.

  The following code sample demonstrates how:

  <<< examples/getting-started.js

  ## Signal Flow Diagrams

  Displayed below are some diagrams how the signalling flow between peers
  behaves.  In each of the diagrams we illustrate three peers (A, B and C)
  participating discovery and coordinating RTCPeerConnection handshakes.

  In each case, only the interaction between the clients is represented not
  how a signalling server
  (such as [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard)) would
  pass on broadcast messages, etc.  This is done for two reasons:

  1. It is out of scope of this documentation.
  2. The `rtc-signaller` has been designed to work without having to rely on
     any intelligence in the server side signalling component.  In the
     instance that a signaller broadcasts all messages to all connected peers
     then `rtc-signaller` should be smart enough to make sure everything works
     as expected.

  ### Peer Discovery / Announcement

  This diagram illustrates the process of how peer `A` announces itself to
  peers `B` and `C`, and in turn they announce themselves.

  ![](https://raw.github.com/rtc-io/rtc-signaller/master/docs/announce.png)

  ### Editing / Updating the Diagrams

  Each of the diagrams has been generated using
  [mscgen](http://www.mcternan.me.uk/mscgen/index.html) and the source for
  these documents can be found in the `docs/` folder of this repository.

  ## Reference

  The `rtc-signaller` module is designed to be used primarily in a functional
  way and when called it creates a new signaller that will enable
  you to communicate with other peers via your messaging network.

  ```js
  // create a signaller from something that knows how to send messages
  var signaller = require('rtc-signaller')(messenger);
  ```

  As demonstrated in the getting started guide, you can also pass through
  a string value instead of a messenger instance if you simply want to
  connect to an existing `rtc-switchboard` instance.

**/
var sig = module.exports = function(messenger, opts) {

  // get the autoreply setting
  var autoreply = (opts || {}).autoreply;

  // create the signaller
  var signaller = new EventEmitter();

  // initialise the id
  var id = signaller.id = (opts || {}).id || uuid.v4();

  // initialise the attributes
  var attributes = signaller.attributes = {
    browser: detect.browser,
    browserVersion: detect.browserVersion,
    id: id,
    agent: 'signaller@' + metadata.version
  };

  // create the peers map
  var peers = signaller.peers = new FastMap();

  // initialise the data event name
  var dataEvent = (opts || {}).dataEvent || 'data';
  var openEvent = (opts || {}).openEvent || 'open';
  var writeMethod = (opts || {}).writeMethod || 'write';
  var closeMethod = (opts || {}).closeMethod || 'close';
  var initialized = false;
  var write;
  var close;
  var processor;
  var announceTimer = 0;

  function bindBrowserEvents() {
    messenger.addEventListener('message', function(evt) {
      processor(evt.data);
    });

    messenger.addEventListener('open', function(evt) {
      signaller.emit('open');
      signaller.emit('connected');
    });
  }

  function bindEvents() {
    // handle message data events
    messenger.on(dataEvent, processor);

    // when the connection is open, then emit an open event and a connected event
    messenger.on(openEvent, function() {
      // TODO: deprecate the open event
      signaller.emit('open');
      signaller.emit('connected');
    });
  }

  function connectToPrimus(url) {
    // load primus
    sig.loadPrimus(url, function(err, Primus) {
      if (err) {
        return signaller.emit('error', err);
      }

      // create the actual messenger from a primus connection
      messenger = Primus.connect(url);

      // now init
      init();
    });
  }

  function extractProp(name) {
    return messenger[name];
  }

  function isF(target) {
    return typeof target == 'function';
  }

  function init() {
    // extract the write and close function references
    write = [writeMethod].concat(WRITE_METHODS).map(extractProp).filter(isF)[0];
    close = [closeMethod].concat(CLOSE_METHODS).map(extractProp).filter(isF)[0];

    // create the processor
    processor = require('./processor')(signaller);

    // if the messenger doesn't provide a valid write method, then complain
    if (typeof write != 'function') {
      throw new Error('provided messenger does not implement a "' +
        writeMethod + '" write method');
    }

    // handle core browser messenging apis
    if (typeof messenger.addEventListener == 'function') {
      bindBrowserEvents();
    }
    else {
      bindEvents();
    }

    // flag as initialised
    initialized = true;
    signaller.emit('init');
  }

  // set the autoreply flag
  signaller.autoreply = autoreply === undefined || autoreply;

  function prepareArg(arg) {
    if (typeof arg == 'object' && (! (arg instanceof String))) {
      return JSON.stringify(arg);
    }
    else if (typeof arg == 'function') {
      return null;
    }

    return arg;
  }

  /**
    ### signaller#send(message, data*)

    Use the send function to send a message to other peers in the current
    signalling scope (if announced in a room this will be a room, otherwise
    broadcast to all peers connected to the signalling server).

  **/
  var send = signaller.send = function() {
    // iterate over the arguments and stringify as required
    // var metadata = { id: signaller.id };
    var args = [].slice.call(arguments);
    var dataline;

    // inject the metadata
    args.splice(1, 0, { id: signaller.id });
    dataline = args.map(prepareArg).filter(Boolean).join('|');

    // if we are not initialized, then wait until we are
    if (! initialized) {
      return signaller.once('init', function() {
        write.call(messenger, dataline);
      });
    }

    // send the data over the messenger
    return write.call(messenger, dataline);
  };

  /**
    ### announce(data?)

    The `announce` function of the signaller will pass an `/announce` message
    through the messenger network.  When no additional data is supplied to
    this function then only the id of the signaller is sent to all active
    members of the messenging network.

    #### Joining Rooms

    To join a room using an announce call you simply provide the name of the
    room you wish to join as part of the data block that you annouce, for
    example:

    ```js
    signaller.announce({ room: 'testroom' });
    ```

    Signalling servers (such as
    [rtc-switchboard](https://github.com/rtc-io/rtc-switchboard)) will then
    place your peer connection into a room with other peers that have also
    announced in this room.

    Once you have joined a room, the server will only deliver messages that
    you `send` to other peers within that room.

    #### Providing Additional Announce Data

    There may be instances where you wish to send additional data as part of
    your announce message in your application.  For instance, maybe you want
    to send an alias or nick as part of your announce message rather than just
    use the signaller's generated id.

    If for instance you were writing a simple chat application you could join
    the `webrtc` room and tell everyone your name with the following announce
    call:

    ```js
    signaller.announce({
      room: 'webrtc',
      nick: 'Damon'
    });
    ```

    #### Announcing Updates

    The signaller is written to distinguish between initial peer announcements
    and peer data updates (see the docs on the announce handler below). As
    such it is ok to provide any data updates using the announce method also.

    For instance, I could send a status update as an announce message to flag
    that I am going offline:

    ```js
    signaller.announce({ status: 'offline' });
    ```

  **/
  signaller.announce = function(data, sender) {
    clearTimeout(announceTimer);

    // update internal attributes
    extend(attributes, data, { id: signaller.id });

    // send the attributes over the network
    return announceTimer = setTimeout(function() {
      (sender || send)('/announce', attributes);
    }, (opts || {}).announceDelay || 10);
  };

  /**
    ### isMaster(targetId)

    A simple function that indicates whether the local signaller is the master
    for it's relationship with peer signaller indicated by `targetId`.  Roles
    are determined at the point at which signalling peers discover each other,
    and are simply worked out by whichever peer has the lowest signaller id
    when lexigraphically sorted.

    For example, if we have two signaller peers that have discovered each
    others with the following ids:

    - `b11f4fd0-feb5-447c-80c8-c51d8c3cced2`
    - `8a07f82e-49a5-4b9b-a02e-43d911382be6`

    They would be assigned roles:

    - `b11f4fd0-feb5-447c-80c8-c51d8c3cced2`
    - `8a07f82e-49a5-4b9b-a02e-43d911382be6` (master)

  **/
  signaller.isMaster = function(targetId) {
    var peer = peers.get(targetId);

    return peer && peer.roleIdx !== 0;
  };

  /**
    ### leave()

    Tell the signalling server we are leaving.  Calling this function is
    usually not required though as the signalling server should issue correct
    `/leave` messages when it detects a disconnect event.

  **/
  signaller.leave = function() {
    // send the leave signal
    send('/leave', { id: id });

    // call the close method
    if (typeof close == 'function') {
      close.call(messenger);
    }
  };

  /**
    ### to(targetId)

    Use the `to` function to send a message to the specified target peer.
    A large parge of negotiating a WebRTC peer connection involves direct
    communication between two parties which must be done by the signalling
    server.  The `to` function provides a simple way to provide a logical
    communication channel between the two parties:

    ```js
    var send = signaller.to('e95fa05b-9062-45c6-bfa2-5055bf6625f4').send;

    // create an offer on a local peer connection
    pc.createOffer(
      function(desc) {
        // set the local description using the offer sdp
        // if this occurs successfully send this to our peer
        pc.setLocalDescription(
          desc,
          function() {
            send('/sdp', desc);
          },
          handleFail
        );
      },
      handleFail
    );
    ```

  **/
  signaller.to = function(targetId) {
    // create a sender that will prepend messages with /to|targetId|
    var sender = function() {
      // get the peer (yes when send is called to make sure it hasn't left)
      var peer = signaller.peers.get(targetId);
      var args;

      if (! peer) {
        throw new Error('Unknown peer: ' + targetId);
      }

      // if the peer is inactive, then abort
      if (peer.inactive) {
        return;
      }

      args = [
        '/to',
        targetId
      ].concat([].slice.call(arguments));

      // inject metadata
      args.splice(3, 0, { id: signaller.id });

      setTimeout(function() {
        var msg = args.map(prepareArg).filter(Boolean).join('|');
        debug('TX (' + targetId + '): ' + msg);

        write.call(messenger, msg);
      }, 0);
    };

    return {
      announce: function(data) {
        return signaller.announce(data, sender);
      },

      send: sender,
    }
  };

  // if the messenger is a string, then we are going to attach to a
  // ws endpoint and automatically set up primus
  if (typeof messenger == 'string' || (messenger instanceof String)) {
    connectToPrimus(messenger);
  }
  // otherwise, initialise the connection
  else {
    init();
  }

  return signaller;
};

sig.loadPrimus = require('./primus-loader');<|endoftext|>


<commit_before>'use strict'

var execSync = require('child_process').execSync

module.exports = function (cwd) {
	var command = 'git log --pretty=oneline'
	var result = execSync(command, { cwd: cwd }).toString()
	return result
		.split('\n')[0]
		.split(' ')
}
<commit_msg>fix lint<commit_after>'use strict'

var execSync = require('child_process').execSync

module.exports = function (cwd) {
	var command = 'git log --pretty=oneline'
	var result = execSync(command, {cwd: cwd}).toString()
	return result
		.split('\n')[0]
		.split(' ')
}
<|endoftext|>


<commit_before>'use strict';
let express = require('express');

// Ignore requests for favicons
app.get('/favicon.ico', function(req, res) {
  res.sendStatus(404);
});

app.use('/findPerson', require('/middleware/findPerson'));
app.use('/findRoom', require('/middleware/findRoom'));
app.use('/checkInOut', require('/middleware/checkInOut'));
app.use('/screenConnect', require('/middleware/screenConnect'));

app.listen(3000);
<commit_msg>Helps to tell server app is an express server<commit_after>'use strict';
let express = require('express');
let app = express();

// Ignore requests for favicons
app.get('/favicon.ico', function(req, res) {
  res.sendStatus(404);
});

app.use('/findPerson', require('/middleware/findPerson'));
app.use('/findRoom', require('/middleware/findRoom'));
app.use('/checkInOut', require('/middleware/checkInOut'));
app.use('/screenConnect', require('/middleware/screenConnect'));

app.listen(3000);
<|endoftext|>


<commit_before>var inside = require('turf-inside');

/**
* Calculates the minimum value of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/min
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {string} inField the field in input data to analyze
* @param {string} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField` values
* @example
* var polygons = turf.featurecollection([
*   turf.polygon([[
*     [72.809658, 18.961818],
*     [72.809658, 18.974805],
*     [72.827167, 18.974805],
*     [72.827167, 18.961818],
*     [72.809658, 18.961818]
*   ]]),
*   turf.polygon([[
*     [72.820987, 18.947043],
*     [72.820987, 18.95922],
*     [72.841243, 18.95922],
*     [72.841243, 18.947043],
*     [72.820987, 18.947043]
*   ]])
* ]);
* var points = turf.featurecollection([
*   turf.point([72.814464, 18.971396], {population: 200}),
*   turf.point([72.820043, 18.969772], {population: 600}),
*   turf.point([72.817296, 18.964253], {population: 100}),
*   turf.point([72.83575, 18.954837], {population: 200}),
*   turf.point([72.828197, 18.95094], {population: 300})]);
*
* var minimums = turf.min(
*   polygons, points, 'population', 'min');
*
* var result = turf.featurecollection(
*   points.features.concat(minimums.features));
*
* //=result
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = min(values);
  });

  return polyFC;
};

function min(x) {
    var value;
    for (var i = 0; i < x.length; i++) {
        // On the first iteration of this loop, min is
        // undefined and is thus made the minimum element in the array
        if (x[i] < value || value === undefined) value = x[i];
    }
    return value;
}
<commit_msg>Switch example to geojson primitives<commit_after>var inside = require('turf-inside');

/**
* Calculates the minimum value of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/min
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {string} inField the field in input data to analyze
* @param {string} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField` values
* @example
* var polygons = {
*   "type": "FeatureCollection",
*   "features": [
*     {
*       "type": "Feature",
*       "properties": {},
*       "geometry": {
*         "type": "Polygon",
*         "coordinates": [[
*           [72.809658, 18.961818],
*           [72.809658, 18.974805],
*           [72.827167, 18.974805],
*           [72.827167, 18.961818],
*           [72.809658, 18.961818]
*         ]]
*       }
*     }, {
*       "type": "Feature",
*       "properties": {},
*       "geometry": {
*         "type": "Polygon",
*         "coordinates": [[
*           [72.820987, 18.947043],
*           [72.820987, 18.95922],
*           [72.841243, 18.95922],
*           [72.841243, 18.947043],
*           [72.820987, 18.947043]
*         ]]
*       }
*     }
*   ]
* };
* var points = {
*   "type": "FeatureCollection",
*   "features": [
*     {
*       "type": "Feature",
*       "properties": {
*         "population": 200
*       },
*       "geometry": {
*         "type": "Point",
*         "coordinates": [72.814464, 18.971396]
*       }
*     }, {
*       "type": "Feature",
*       "properties": {
*         "population": 600
*       },
*       "geometry": {
*         "type": "Point",
*         "coordinates": [72.820043, 18.969772]
*       }
*     }, {
*       "type": "Feature",
*       "properties": {
*         "population": 100
*       },
*       "geometry": {
*         "type": "Point",
*         "coordinates": [72.817296, 18.964253]
*       }
*     }, {
*       "type": "Feature",
*       "properties": {
*         "population": 200
*       },
*       "geometry": {
*         "type": "Point",
*         "coordinates": [72.83575, 18.954837]
*       }
*     }, {
*       "type": "Feature",
*       "properties": {
*         "population": 300
*       },
*       "geometry": {
*         "type": "Point",
*         "coordinates": [72.828197, 18.95094]
*       }
*     }
*   ]
* };
*
* var minimums = turf.min(
*   polygons, points, 'population', 'min');
*
* var resultFeatures = points.features.concat(
*   minimums.features);
* var result = {
*   "type": "FeatureCollection",
*   "features": resultFeatures
* };
*
* //=result
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = min(values);
  });

  return polyFC;
};

function min(x) {
    var value;
    for (var i = 0; i < x.length; i++) {
        // On the first iteration of this loop, min is
        // undefined and is thus made the minimum element in the array
        if (x[i] < value || value === undefined) value = x[i];
    }
    return value;
}
<|endoftext|>


<commit_before>'use strict';

var through = require('through2'),
    gutil = require('gulp-util'),
    PluginError = gutil.PluginError,
    path = require('path'),
    os = require('os'),
    _ = require('lodash'),
    exec = require('child_process').exec;

var PLUGIN_NAME = 'gulp-msbuild';

var msbuildVersions = {
  1.0: 'v1.0.3705',
  1.1: 'v1.1.4322',
  2.0: 'v2.0.50727',
  3.5: 'v3.5',
  4.0: 'v4.0.30319'
};

function findMsBuildExecutable(toolsVersion, platform, architecture, windir) {
  var executable;
  if (platform === 'linux' || platform === 'darwin') {
    executable = 'xbuild';
  } else {
    var version = msbuildVersions[toolsVersion];
    if (!version) {
      throw new PluginError(PLUGIN_NAME, 'No MSBuild Version was supplied!');
    }

    var framework = architecture === 'x64' ? 'Framework64' : 'Framework';
    executable = path.join(windir, 'Microsoft.Net', framework, version, 'MSBuild.exe');
  }

  return executable;
}

function buildArguments(options) {
  var args = [];
  args.push('/target:' + options.targets.join(';'));
  args.push('/verbosity:' + options.verbosity);
  args.push('/toolsversion:' + msbuildVersions[options.toolsVersion].substr(1));

  if (options.nologo) {
    args.push('/nologo');
  }

  if (options.maxcpucount && options.maxcpucount > 0) {
    gutil.log(gutil.colors.cyan('Using maxcpucount: ' + options.maxcpucount));
    args.push('/maxcpucount:' + options.maxcpucount);
  }

  for (var property in options.properties) {
    args.push('/property:' + property + '="' + options.properties[property] + '"');
  }

  return args.join(' ');
}

function msbuild(options, execFile) {
  options = _.extend({
    stdout: false,
    stderr: true,
    targets: ['Rebuild'],
    configuration: 'Release',
    toolsVersion: 4.0,
    properties: {},
    verbosity: 'normal',
    maxcpucount: 0,
    nologo: true,
    platform: process.platform,
    architecture: os.arch(),
    windir: process.env.WINDIR
  }, options);

  var stream = through.obj(function(file, enc, callback) {
    if (file.isNull()) {
      this.push(file);
      return callback();
    }

    this.push(file);
    options.properties.Configuration = options.configuration;

    var executable = path.normalize(findMsBuildExecutable(options.toolsVersion, options.platform, options.architecture, options.windir));
    var args = buildArguments(options);

    var executeFunc = execFile ? execFile : exec;
    var cp = executeFunc([executable, file.path, args].join(' '), {}, function(err) {
      if (err) {
        gutil.log(gutil.colors.red('Build failed!'));
        return;
      }

      gutil.log(gutil.colors.cyan('Build complete!'));
      return;
    });

    if (options.stdout && cp) {
      cp.stdout.pipe(process.stdout);
    }

    if (options.stderr && cp) {
      cp.stderr.pipe(process.stderr);
    }

    return callback();
  });

  return stream;
}

module.exports = msbuild;
<commit_msg>Fixed ToolsVersion property<commit_after>'use strict';

var through = require('through2'),
    gutil = require('gulp-util'),
    PluginError = gutil.PluginError,
    path = require('path'),
    os = require('os'),
    _ = require('lodash'),
    exec = require('child_process').exec;

var PLUGIN_NAME = 'gulp-msbuild';

var msbuildVersions = {
  1.0: 'v1.0.3705',
  1.1: 'v1.1.4322',
  2.0: 'v2.0.50727',
  3.5: 'v3.5',
  4.0: 'v4.0.30319'
};

function findMsBuildExecutable(toolsVersion, platform, architecture, windir) {
  var executable;
  if (platform === 'linux' || platform === 'darwin') {
    executable = 'xbuild';
  } else {
    var version = msbuildVersions[toolsVersion];
    if (!version) {
      throw new PluginError(PLUGIN_NAME, 'No MSBuild Version was supplied!');
    }

    var framework = architecture === 'x64' ? 'Framework64' : 'Framework';
    executable = path.join(windir, 'Microsoft.Net', framework, version, 'MSBuild.exe');
  }

  return executable;
}

function buildArguments(options) {
  var args = [];
  args.push('/target:' + options.targets.join(';'));
  args.push('/verbosity:' + options.verbosity);
  args.push('/toolsversion:' + parseFloat(options.toolsVersion).toFixed(1));

  if (options.nologo) {
    args.push('/nologo');
  }

  if (options.maxcpucount && options.maxcpucount > 0) {
    gutil.log(gutil.colors.cyan('Using maxcpucount: ' + options.maxcpucount));
    args.push('/maxcpucount:' + options.maxcpucount);
  }

  for (var property in options.properties) {
    args.push('/property:' + property + '="' + options.properties[property] + '"');
  }

  return args.join(' ');
}

function msbuild(options, execFile) {
  options = _.extend({
    stdout: false,
    stderr: true,
    targets: ['Rebuild'],
    configuration: 'Release',
    toolsVersion: 4.0,
    properties: {},
    verbosity: 'normal',
    maxcpucount: 0,
    nologo: true,
    platform: process.platform,
    architecture: os.arch(),
    windir: process.env.WINDIR
  }, options);

  var stream = through.obj(function(file, enc, callback) {
    if (file.isNull()) {
      this.push(file);
      return callback();
    }

    this.push(file);
    options.properties.Configuration = options.configuration;

    var executable = path.normalize(findMsBuildExecutable(options.toolsVersion, options.platform, options.architecture, options.windir));
    var args = buildArguments(options);

    var executeFunc = execFile ? execFile : exec;
    var cp = executeFunc([executable, file.path, args].join(' '), {}, function(err) {
      if (err) {
        gutil.log(gutil.colors.red('Build failed!'));
        return;
      }

      gutil.log(gutil.colors.cyan('Build complete!'));
      return;
    });

    if (options.stdout && cp) {
      cp.stdout.pipe(process.stdout);
    }

    if (options.stderr && cp) {
      cp.stderr.pipe(process.stderr);
    }

    return callback();
  });

  return stream;
}

module.exports = msbuild;
<|endoftext|>


<commit_before>'use strict';

console.log( 7 );

var Gpio = require('chip-gpio').Gpio,
    request = require( 'request' ),
    jsonfile = require( 'jsonfile' ),
    client = null,

    persist = 'persist.json',
    persistedData = jsonfile.readFileSync( persist ),
    brightness = 255;

var red = new Gpio( 2, 'out' );
var green = new Gpio( 3, 'out' );
var blue = new Gpio( 4, 'out' );

red.write( 1 ); green.write( 1 ); blue.write( 1 );

// led.write( 0 ) to turn on

// Setup th buttons and rotary encoder
var btn = new Gpio(7, 'in', 'both', {
      debounceTimeout: 500
    }),

    a = new Gpio(0, 'in', 'both',{
        debounceTimeout: 200
    }),

    b = new Gpio(1, 'in', 'both',{
      debounceTimeout: 200
    });

var apiBaseUrl,
    // Set default Values
    brightness = 255;

function setState( on, brightness )
{
  console.log( 'setState', {
    on, brightness
  });
  request.put( apiBaseUrl + persistedData.username + '/lights/4/state', {
    json: {
      on: on,
      bri: Math.ceil( brightness )
    }
  });
}

/*
*  Connect to the Bridge
*/

// Search for the Bridge
request( 'https://www.meethue.com/api/nupnp', function( error, response, body ){
  persistedData.ip = JSON.parse( body )[0].internalipaddress;
  jsonfile.writeFile( persist, persistedData );

  apiBaseUrl = 'http://' + persistedData.ip + '/api/';
  console.log( apiBaseUrl );

  // Do we need to create a user?
  if( typeof persistedData.username == 'undefined' || ! persistedData.username )
  {
    request.post( apiBaseUrl, {
      json: {
        devicetype: 'chip_hue_switch'
      }
    }, function( error, response, body ){
      persistedData.username = body[0].success.username;
      jsonfile.writeFile( persist, persistedData );
    });
  }
});

btn.watch(function (err, value) {
  console.log('press', value);
  console.log( apiBaseUrl + persistedData.username + '/lights' );

  request( apiBaseUrl + persistedData.username + '/lights', function( error, response, body ){
  	body = JSON.parse( body );
  	var newState = ! body[4].state.on;

    setState( newState, brightness );

  });

});

var previousA, previousB;

function setBrightness()
{
	if( brightness >= 255 ) brightness = 255;
	if( brightness <= 1 ) brightness = 1;

	console.info( 'Setting brightness to ' + brightness );

  setState( true, brightness );
}

a.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousA != currentA )
	{
		if( currentA != currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

b.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousB != currentB )
	{
		if( currentA == currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

function exit() {
    btn.unexport();
    a.unexport();
    b.unexport();
    process.exit();
}

process.on('SIGINT', exit);
<commit_msg>Change<commit_after>'use strict';

console.log( 7 );

var Gpio = require('chip-gpio').Gpio,
    request = require( 'request' ),
    jsonfile = require( 'jsonfile' ),
    client = null,

    persist = 'persist.json',
    persistedData = jsonfile.readFileSync( persist ),
    brightness = 255;

// Needs work..
var red = new Gpio( 2, 'out' );
var green = new Gpio( 3, 'out' );
var blue = new Gpio( 4, 'out' );

red.write( 1 ); green.write( 1 ); blue.write( 1 );

// led.write( 0 ) to turn on

// Setup th buttons and rotary encoder
var btn = new Gpio(7, 'in', 'both', {
      debounceTimeout: 500
    }),

    a = new Gpio(0, 'in', 'both',{
        debounceTimeout: 200
    }),

    b = new Gpio(1, 'in', 'both',{
      debounceTimeout: 200
    });

var apiBaseUrl,
    // Set default Values
    brightness = 255;

function setState( on, brightness )
{
  console.log( 'setState', {
    on, brightness
  });
  request.put( apiBaseUrl + persistedData.username + '/lights/4/state', {
    json: {
      on: on,
      bri: Math.ceil( brightness )
    }
  });
}

/*
*  Connect to the Bridge
*/

// Search for the Bridge
request( 'https://www.meethue.com/api/nupnp', function( error, response, body ){
  persistedData.ip = JSON.parse( body )[0].internalipaddress;
  jsonfile.writeFile( persist, persistedData );

  apiBaseUrl = 'http://' + persistedData.ip + '/api/';
  console.log( apiBaseUrl );

  // Do we need to create a user?
  if( typeof persistedData.username == 'undefined' || ! persistedData.username )
  {
    request.post( apiBaseUrl, {
      json: {
        devicetype: 'chip_hue_switch'
      }
    }, function( error, response, body ){
      persistedData.username = body[0].success.username;
      jsonfile.writeFile( persist, persistedData );
    });
  }
});

btn.watch(function (err, value) {
  console.log('press', value);
  console.log( apiBaseUrl + persistedData.username + '/lights' );

  request( apiBaseUrl + persistedData.username + '/lights', function( error, response, body ){
  	body = JSON.parse( body );
  	var newState = ! body[4].state.on;

    setState( newState, brightness );

  });

});

var previousA, previousB;

function setBrightness()
{
	if( brightness >= 255 ) brightness = 255;
	if( brightness <= 1 ) brightness = 1;

	console.info( 'Setting brightness to ' + brightness );

  setState( true, brightness );
}

a.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousA != currentA )
	{
		if( currentA != currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

b.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousB != currentB )
	{
		if( currentA == currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

function exit() {
    btn.unexport();
    a.unexport();
    b.unexport();
    process.exit();
}

process.on('SIGINT', exit);
<|endoftext|>


<commit_before>var pull = require('pull-stream')
var pullWeird = require('./pull-weird')
var PacketStream = require('packet-stream')
var EventEmitter = require('events').EventEmitter

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return 'string' === typeof s
}

module.exports = function (remoteApi, localApi, serializer) {
  localApi = localApi || {}
  remoteApi = remoteApi || {}

  return function (local) {
    local = local || {}

    var emitter = new EventEmitter ()

    function hasAsync(name) {
      return (
        localApi.async
        && ~localApi.async.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasSource(name) {
      return (
        localApi.source
        && ~localApi.source.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasSink(name) {
      return (
        localApi.sink
        && ~localApi.sink.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasDuplex(name) {
      return (
        localApi.duplex
        && ~localApi.duplex.indexOf(name)
        && isFunction(local[name])
      )
    }

    function createPacketStream () {

      return PacketStream({
        request: function (opts, cb) {
          var name = opts.name
          if(!hasAsync(name))
            return cb(new Error('method not supported:'+name))
          var args = opts.args
          args.push(cb)
          //packet stream already has a thing to check cb fires only once.
          try { local[name].apply(local, args) }
          catch (err) { cb(err) }
        },
        stream: function (stream) {
          stream.read = function (data, end) {
            var name = data.name
            stream.read = null
            if(end) return stream.write(null, end)

            if (data.type == 'source') {
              if(!hasSource(name))
                return stream.write(null, new Error('no source:'+name))

              var source, sink = pullWeird.sink(stream)
              try {
                source = local[name].apply(local, data.args)
              } catch (err) {
                return sink(pull.error(err))
              }
              sink(source)
            }
            else if (data.type == 'sink') {
              if(!hasSink(name))
                return stream.write(null, new Error('no sink:'+name))

              var sink, source = pullWeird.source(stream)
              try {
                sink = local[name].apply(local, data.args)
              } catch (err) {
                return pullWeird.sink(stream)(pull.error(err))
              }
              sink(source)
            }
            else if (data.type == 'duplex') {
              if(!hasDuplex(name))
                return stream.write(null, new Error('no duplex:'+name))

              var s1 = pullWeird(stream)
              try {
                s2 = local[name].apply(local, data.args)
              } catch (err) {
                return s1.sink(pull.error(err))
              }
              pull(s1, s2, s1)
            }
            else {
              return stream.write(null, new Error('unsupported stream type:'+data.type))
            }
          }
        }
      })
    }

    var ps = createPacketStream(), _cb
    //if we create the stream immediately,
    //we get the pull-stream's internal buffer
    //so all operations are queued for free!
    var ws = pullWeird(ps, function (err) {
      if(_cb) _cb(err)
    })

    var noop = function(err) {
      if (err) throw err
    }
    if(remoteApi.async)
      remoteApi.async.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          if(isFunction (args[args.length - 1]))
            cb = args.pop()
          else
            cb = noop

          ps.request({name: name, args: args}, cb)
        }
      })

    if(remoteApi.source)
      remoteApi.source.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird.source(ws)
          ws.write({name: name, args: args, type: 'source'})
          return s
        }
      })

    if(remoteApi.sink)
      remoteApi.sink.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird.sink(ws)
          ws.write({name: name, args: args, type: 'sink'})
          return s
        }
      })

    if(remoteApi.duplex)
      remoteApi.duplex.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird(ws)
          ws.write({name: name, args: args, type: 'duplex'})
          return s
        }
      })

    //this is the stream to the remote server.
    //it only makes sense to have one of these.
    //either throw an error if the user creates
    //another when the previous has not yet ended
    //or abort the previous one, and create a new one?

    var once = false

    emitter.createStream = function (cb) {
      if(ps.ended) {
        ps = createPacketStream()
        ws = pullWeird(ps, cb)
        once = false
      }
      else if(once)
        throw new Error('only one stream allowed at a time')
      else
      //set the cb, this applies to the first stream created only.
        _cb = cb
      once = true
      var stream = (serializer) ? serializer(ws) : ws
      stream.close = ps.close
      return stream
    }

    return emitter
  }
}
<commit_msg>use stream.destroy to kill a stream<commit_after>var pull = require('pull-stream')
var pullWeird = require('./pull-weird')
var PacketStream = require('packet-stream')
var EventEmitter = require('events').EventEmitter

function isFunction (f) {
  return 'function' === typeof f
}

function isString (s) {
  return 'string' === typeof s
}

module.exports = function (remoteApi, localApi, serializer) {
  localApi = localApi || {}
  remoteApi = remoteApi || {}

  return function (local) {
    local = local || {}

    var emitter = new EventEmitter ()

    function hasAsync(name) {
      return (
        localApi.async
        && ~localApi.async.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasSource(name) {
      return (
        localApi.source
        && ~localApi.source.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasSink(name) {
      return (
        localApi.sink
        && ~localApi.sink.indexOf(name)
        && isFunction(local[name])
      )
    }

    function hasDuplex(name) {
      return (
        localApi.duplex
        && ~localApi.duplex.indexOf(name)
        && isFunction(local[name])
      )
    }

    function createPacketStream () {

      return PacketStream({
        request: function (opts, cb) {
          var name = opts.name
          if(!hasAsync(name))
            return cb(new Error('method not supported:'+name))
          var args = opts.args
          args.push(cb)
          //packet stream already has a thing to check cb fires only once.
          try { local[name].apply(local, args) }
          catch (err) { cb(err) }
        },
        stream: function (stream) {
          stream.read = function (data, end) {
            var name = data.name
            stream.read = null
            if(end) return stream.write(null, end)

            if (data.type == 'source') {
              if(!hasSource(name))
                return stream.destroy(new Error('no source:'+name))

              var source, sink = pullWeird.sink(stream)
              try {
                source = local[name].apply(local, data.args)
              } catch (err) {
                return sink(pull.error(err))
              }
              sink(source)
            }
            else if (data.type == 'sink') {
              if(!hasSink(name))
                return stream.destroy(new Error('no sink:'+name))

              var sink, source = pullWeird.source(stream)
              try {
                sink = local[name].apply(local, data.args)
              } catch (err) {
                return pullWeird.sink(stream)(pull.error(err))
              }
              sink(source)
            }
            else if (data.type == 'duplex') {
              if(!hasDuplex(name))
                return stream.destroy(new Error('no duplex:'+name))

              var s1 = pullWeird(stream)
              try {
                s2 = local[name].apply(local, data.args)
              } catch (err) {
                return s1.sink(pull.error(err))
              }
              pull(s1, s2, s1)
            }
            else {
              return stream.write(null, new Error('unsupported stream type:'+data.type))
            }
          }
        }
      })
    }

    var ps = createPacketStream(), _cb
    //if we create the stream immediately,
    //we get the pull-stream's internal buffer
    //so all operations are queued for free!
    var ws = pullWeird(ps, function (err) {
      if(_cb) _cb(err)
    })

    var noop = function(err) {
      if (err) throw err
    }
    if(remoteApi.async)
      remoteApi.async.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          if(isFunction (args[args.length - 1]))
            cb = args.pop()
          else
            cb = noop

          ps.request({name: name, args: args}, cb)
        }
      })

    if(remoteApi.source)
      remoteApi.source.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird.source(ws)
          ws.write({name: name, args: args, type: 'source'})
          return s
        }
      })

    if(remoteApi.sink)
      remoteApi.sink.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird.sink(ws)
          ws.write({name: name, args: args, type: 'sink'})
          return s
        }
      })

    if(remoteApi.duplex)
      remoteApi.duplex.forEach(function (name) {
        emitter[name] = function () {
          var args = [].slice.call(arguments)
          var ws = ps.stream()
          var s = pullWeird(ws)
          ws.write({name: name, args: args, type: 'duplex'})
          return s
        }
      })

    //this is the stream to the remote server.
    //it only makes sense to have one of these.
    //either throw an error if the user creates
    //another when the previous has not yet ended
    //or abort the previous one, and create a new one?

    var once = false

    emitter.createStream = function (cb) {
      if(ps.ended) {
        ps = createPacketStream()
        ws = pullWeird(ps, cb)
        once = false
      }
      else if(once)
        throw new Error('only one stream allowed at a time')
      else
      //set the cb, this applies to the first stream created only.
        _cb = cb
      once = true
      var stream = (serializer) ? serializer(ws) : ws
      stream.close = ps.close
      return stream
    }

    return emitter
  }
}
<|endoftext|>


<commit_before>

function union (a, b) {
  if(b == null) return a
  var c = []
  b.forEach(function (v) {
    if(~a.indexOf(v)) c.push(v)
  })
  return c.sort()
}

module.exports = function (examples) {

  var order = {}
  examples.forEach(function (seq, i) {
    var seen = []
    console.log(order)
    seq.forEach(function (value) {
      order[value] = union(seen.slice(), order[value])
      seen.push(value)
    })
    if(order) return
  })
  return order
}
<commit_msg>canonical order<commit_after>

function union (a, b) {
  if(b == null) return a
  var c = []
  b.forEach(function (v) {
    if(~a.indexOf(v)) c.push(v)
  })
  return c.sort()
}

function remove(ary, v) {
  var i = ary.indexOf(v)
  if(~i) ary.splice(i, 1)
  return ary
}

function clean (order) {
  var newOrder = {}
  for(var key in order) {
    var after = order[key]

    //remove all the items that the are indirectly before key.
    var direct = after.slice()
    after.forEach(function (k) {
      order[k].forEach(function (v) {
        remove(direct, v)
      })
    })
    newOrder[key] = direct
  }
  return newOrder
}

module.exports = function (examples, doClean) {

  var order = {}
  examples.forEach(function (seq, i) {
    var seen = []
    seq.forEach(function (value) {
      console.log(value, '->', order[value] || [])
      console.log('seen', seen)
      order[value] = union(seen.slice(), order[value])
      seen.push(value)
    })
    if(order) return
  })

  if(doClean)
    return clean(order)

  return order
}

module.exports.canonical = clean
<|endoftext|>


<commit_before>'use strict';

const Hapi = require('hapi');
const unirest = require('unirest');

const server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
  method: 'POST',
  path: '/750',
  config: {
    payload: {
      output: 'data',
      parse: true
    }
  },
  handler: function (request, reply) {
    console.log(request.payload);
    unirest.post(`https://maker.ifttt.com/trigger/${process.env.EVENT_NAME}/with/key/${process.env.MAKER_KEY}`)
    .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
    .send({ "value1": 23, "value2": "bar", "value3": "bz" })
    .end(function (response) {
      console.log(response.body);
      reply(response.body);
    });
  }
});

server.start((err) => {

  if (err) {
    throw err;
  }
  console.log(`Server running at: ${server.info.uri}`);
});<commit_msg>Changes correct values for post<commit_after>'use strict';

const Hapi = require('hapi');
const unirest = require('unirest');

const server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
  method: 'POST',
  path: '/750',
  config: {
    payload: {
      output: 'data',
      parse: true
    }
  },
  handler: function (request, reply) {
    console.log(request.payload);
    unirest.post(`https://maker.ifttt.com/trigger/${process.env.EVENT_NAME}/with/key/${process.env.MAKER_KEY}`)
    .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
    .send({ "value1": request.payload.words , "value2": request.payload.body, "value3": request.payload.date })
    .end(function (response) {
      console.log(response.body);
      reply(response.body);
    });
  }
});

server.start((err) => {

  if (err) {
    throw err;
  }
  console.log(`Server running at: ${server.info.uri}`);
});<|endoftext|>


<commit_before>var distance = require('turf-distance');
var point = require('turf-point');
var linestring = require('turf-linestring');
var bearing = require('turf-bearing');
var destination = require('turf-destination');

/**
 * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the LineString.
 *
 * @module turf/point-on-line
 * @category misc
 * @param {Feature<LineString>} line line to snap to
 * @param {Feature<Point>} point point to snap from
 * @return {Feature<Point>} closest point on the `line` to `point`
 * @example
 * var line = {
 *   "type": "Feature",
 *   "properties": {},
 *   "geometry": {
 *     "type": "LineString",
 *     "coordinates": [
 *       [-77.031669, 38.878605],
 *       [-77.029609, 38.881946],
 *       [-77.020339, 38.884084],
 *       [-77.025661, 38.885821],
 *       [-77.021884, 38.889563],
 *       [-77.019824, 38.892368]
 *     ]
 *   }
 * };
 * var pt = {
 *   "type": "Feature",
 *   "properties": {},
 *   "geometry": {
 *     "type": "Point",
 *     "coordinates": [-77.037076, 38.884017]
 *   }
 * };
 *
 * var snapped = turf.pointOnLine(line, pt);
 * snapped.properties['marker-color'] = '#00f'
 *
 * var result = {
 *   "type": "FeatureCollection",
 *   "features": [line, pt, snapped]
 * };
 *
 * //=result
 */

module.exports = function (line, pt) {
  var coords;
  if (line.type === 'Feature') {
    coords = line.geometry.coordinates;
  } else if (line.type === 'LineString') {
    coords = line.geometry.coordinates;
  } else {
    throw new Error('input must be a LineString Feature or Geometry');
  }

  return pointOnLine(pt, coords);
};

function pointOnLine (pt, coords) {
  var units = 'miles';
  var closestPt = point([Infinity, Infinity], {
    dist: Infinity
  });
  for(var i = 0; i < coords.length - 1; i++) {
    var start = point(coords[i]);
    var stop = point(coords[i + 1]);
    //start
    start.properties.dist = distance(pt, start, units);
    //stop
    stop.properties.dist = distance(pt, stop, units);
    //perpendicular
    var direction = bearing(start, stop);
    var perpendicularPt1 = destination(pt, 1000 , direction + 90, units); // 1000 = gross
    var perpendicularPt2 = destination(pt, 1000 , direction - 90, units); // 1000 = gross
    var intersect = lineIntersects(
      perpendicularPt1.geometry.coordinates[0],
      perpendicularPt1.geometry.coordinates[1],
      perpendicularPt2.geometry.coordinates[0],
      perpendicularPt2.geometry.coordinates[1],
      start.geometry.coordinates[0],
      start.geometry.coordinates[1],
      stop.geometry.coordinates[0],
      stop.geometry.coordinates[1]
      );
    var intersectPt;
    if(intersect) {
      var intersectPt = point(intersect);
      intersectPt.properties.dist = distance(pt, intersectPt, units);
    }

    if(start.properties.dist < closestPt.properties.dist) {
      closestPt = start;
      closestPt.properties.index = i;
    }
    if(stop.properties.dist < closestPt.properties.dist) {
     closestPt = stop;
     closestPt.properties.index = i;
    }
    if(intersectPt && intersectPt.properties.dist < closestPt.properties.dist){
      closestPt = intersectPt;
      closestPt.properties.index = i;
    }
  }

  return closestPt;
}

// modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {
  // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point
  var denominator, a, b, numerator1, numerator2,
    result = {
    x: null,
    y: null,
    onLine1: false,
    onLine2: false
  };
  denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY));
  if (denominator === 0) {
    if (result.x !== null && result.y !== null) {
      return result;
    } else {
      return false;
    }
  }
  a = line1StartY - line2StartY;
  b = line1StartX - line2StartX;
  numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b);
  numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b);
  a = numerator1 / denominator;
  b = numerator2 / denominator;

  // if we cast these lines infinitely in both directions, they intersect here:
  result.x = line1StartX + (a * (line1EndX - line1StartX));
  result.y = line1StartY + (a * (line1EndY - line1StartY));

  // if line1 is a segment and line2 is infinite, they intersect if:
  if (a > 0 && a < 1) {
    result.onLine1 = true;
  }
  // if line2 is a segment and line1 is infinite, they intersect if:
  if (b > 0 && b < 1) {
    result.onLine2 = true;
  }
  // if line1 and line2 are segments, they intersect if both of the above are true
  if(result.onLine1 && result.onLine2){
    return [result.x, result.y];
  } else {
    return false;
  }
}
<commit_msg>[Style] Style restored to the current turf-point-on-line/master/index.js file for the PR.<commit_after>var distance = require('turf-distance');
var point = require('turf-point');
var linestring = require('turf-linestring');
var bearing = require('turf-bearing');
var destination = require('turf-destination');

/**
 * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the LineString.
 *
 * @module turf/point-on-line
 * @category misc
 * @param {Feature<LineString>} line line to snap to
 * @param {Feature<Point>} point point to snap from
 * @return {Feature<Point>} closest point on the `line` to `point`
 * @example
 * var line = {
 *   "type": "Feature",
 *   "properties": {},
 *   "geometry": {
 *     "type": "LineString",
 *     "coordinates": [
 *       [-77.031669, 38.878605],
 *       [-77.029609, 38.881946],
 *       [-77.020339, 38.884084],
 *       [-77.025661, 38.885821],
 *       [-77.021884, 38.889563],
 *       [-77.019824, 38.892368]
 *     ]
 *   }
 * };
 * var pt = {
 *   "type": "Feature",
 *   "properties": {},
 *   "geometry": {
 *     "type": "Point",
 *     "coordinates": [-77.037076, 38.884017]
 *   }
 * };
 *
 * var snapped = turf.pointOnLine(line, pt);
 * snapped.properties['marker-color'] = '#00f'
 *
 * var result = {
 *   "type": "FeatureCollection",
 *   "features": [line, pt, snapped]
 * };
 *
 * //=result
 */

module.exports = function(line, pt) {
  var coords;
  if (line.type === 'Feature') {
    coords = line.geometry.coordinates;
  } else if (line.type === 'LineString') {
    coords = line.geometry.coordinates;
  } else {
    throw new Error('input must be a LineString Feature or Geometry');
  }

  return pointOnLine(pt, coords);
};

function pointOnLine(pt, coords) {
  var units = 'miles';
  var closestPt = point([Infinity, Infinity], {
    dist: Infinity
  });
  for (var i = 0; i < coords.length - 1; i++) {
    var start = point(coords[i]);
    var stop = point(coords[i + 1]);
    //start
    start.properties.dist = distance(pt, start, units);
    //stop
    stop.properties.dist = distance(pt, stop, units);
    //perpendicular
    var direction = bearing(start, stop);
    var perpendicularPt1 = destination(pt, 1000 , direction + 90, units); // 1000 = gross
    var perpendicularPt2 = destination(pt, 1000 , direction - 90, units); // 1000 = gross
    var intersect = lineIntersects(
      perpendicularPt1.geometry.coordinates[0],
      perpendicularPt1.geometry.coordinates[1],
      perpendicularPt2.geometry.coordinates[0],
      perpendicularPt2.geometry.coordinates[1],
      start.geometry.coordinates[0],
      start.geometry.coordinates[1],
      stop.geometry.coordinates[0],
      stop.geometry.coordinates[1]
      );
    var intersectPt;
    if (intersect) {
      var intersectPt = point(intersect);
      intersectPt.properties.dist = distance(pt, intersectPt, units);
    }

    if (start.properties.dist < closestPt.properties.dist) {
      closestPt = start;
      closestPt.properties.index = i;
    }
    if (stop.properties.dist < closestPt.properties.dist) {
      closestPt = stop;
      closestPt.properties.index = i;
    }
    if (intersectPt && intersectPt.properties.dist < closestPt.properties.dist) {
      closestPt = intersectPt;
      closestPt.properties.index = i;
    }
  }

  return closestPt;
}

// modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {
  // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point
  var denominator, a, b, numerator1, numerator2,
    result = {
      x: null,
      y: null,
      onLine1: false,
      onLine2: false
    };
  denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY));
  if (denominator === 0) {
    if (result.x !== null && result.y !== null) {
      return result;
    } else {
      return false;
    }
  }
  a = line1StartY - line2StartY;
  b = line1StartX - line2StartX;
  numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b);
  numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b);
  a = numerator1 / denominator;
  b = numerator2 / denominator;

  // if we cast these lines infinitely in both directions, they intersect here:
  result.x = line1StartX + (a * (line1EndX - line1StartX));
  result.y = line1StartY + (a * (line1EndY - line1StartY));

  // if line1 is a segment and line2 is infinite, they intersect if:
  if (a > 0 && a < 1) {
    result.onLine1 = true;
  }
  // if line2 is a segment and line1 is infinite, they intersect if:
  if (b > 0 && b < 1) {
    result.onLine2 = true;
  }
  // if line1 and line2 are segments, they intersect if both of the above are true
  if (result.onLine1 && result.onLine2) {
    return [result.x, result.y];
  } else {
    return false;
  }
}
<|endoftext|>


<commit_before>var Promise = require("bluebird");
var AlexaUtterances = require("alexa-utterances");
var SSML = require("./to-ssml");
var alexa = {};

alexa.response = function() {
  this.resolved = false;
  this.response = {
    "version": "1.0",
    "sessionAttributes": {},
    "response": {
      "shouldEndSession": true
    }
  };
  this.say = function(str) {
    if (typeof this.response.response.outputSpeech == "undefined") {
      this.response.response.outputSpeech = {
        "type": "SSML",
        "ssml": SSML.fromStr(str)
      };
    } else {
      // append str to the current outputSpeech, stripping the out speak tag
      this.response.response.outputSpeech.ssml = SSML.fromStr(str, this.response.response.outputSpeech.ssml);
    }
    return this;
  };
  this.clear = function(/*str*/) {
    this.response.response.outputSpeech = {
      "type": "PlainText",
      "text": ""
    };
    return this;
  };
  this.reprompt = function(str) {
    if (typeof this.response.response.reprompt == "undefined") {
      this.response.response.reprompt = {
        "outputSpeech": {
          "type": "SSML",
          "ssml": SSML.fromStr(str)
        }
      };
    } else {
      // append str to the current outputSpeech, stripping the out speak tag
      this.response.response.reprompt.outputSpeech.ssml = SSML.fromStr(str, this.response.response.reprompt.outputSpeech.text);
    }
    return this;
  };
  this.card = function(oCard) {
    if (2 == arguments.length) {  //backwards compat
      oCard = {
        type: "Simple",
        title: arguments[0],
        content: arguments[1]
      };
    }

    var requiredAttrs = [],
      clenseAttrs = [];

    switch (oCard.type) {
      case 'Simple':
        requiredAttrs.push('content');
        clenseAttrs.push('content');
        break;
      case 'Standard':
        requiredAttrs.push('text');
        clenseAttrs.push('text');
        if (('image' in oCard) && ( !('smallImageUrl' in oCard['image']) && !('largeImageUrl' in oCard['image']) )) {
          console.error('If card.image is defined, must specify at least smallImageUrl or largeImageUrl');
          return this;
        }
        break;
      default:
        break;
    }

    var hasAllReq = requiredAttrs.every(function(idx) {
      if (!(idx in oCard)) {
        console.error('Card object is missing required attr "' + idx + '"');
        return false;
      }
      return true;
    });

    if (!hasAllReq) {
      return this;
    }

    // remove all SSML to keep the card clean
    clenseAttrs.forEach(function(idx) {
      oCard[idx] = SSML.cleanse(oCard[idx]);
    });

    this.response.response.card = oCard;

    return this;
  };
  this.linkAccount = function() {
    this.response.response.card = {
      "type": "LinkAccount"
    };
    return this;
  };
  this.shouldEndSession = function(bool, reprompt) {
    this.response.response.shouldEndSession = bool;
    if (reprompt) {
      this.reprompt(reprompt);
    }
    return this;
  };
  this.session = function(key, val) {
    if (typeof val == "undefined") {
      return this.response.sessionAttributes[key];
    } else {
      this.response.sessionAttributes[key] = val;
    }
    return this;
  };
  this.clearSession = function(key) {
    if (typeof key == "string" && typeof this.response.sessionAttributes[key] != "undefined") {
      delete this.response.sessionAttributes[key];
    } else {
      this.response.sessionAttributes = {};
    }
    return this;
  };

};

alexa.request = function(json) {
  this.data = json;
  this.slot = function(slotName, defaultValue) {
    try {
      return this.data.request.intent.slots[slotName].value;
    } catch (e) {
      console.error("missing intent in request: " + slotName, e);
      return defaultValue;
    }
  };
  this.type = function() {
    try {
      return this.data.request.type;
    } catch (e) {
      console.error("missing type", e);
      return null;
    }
  };

  if (typeof this.data.session == 'undefined') {
    this.sessionDetails = {
      "new": false,
      "sessionId": null,
      "userId": null,
      "accessToken": null,
      "attributes": {},
      "application": {
        applicationId: null
      }
    };
  } else {
    this.sessionDetails = {
      "new": this.data.session.new,
      "sessionId": this.data.session.sessionId,
      "userId": this.data.session.user.userId,
      "accessToken": this.data.session.user.accessToken || null,
      "attributes": this.data.session.attributes,
      "application": this.data.session.application
    };
  }
  this.userId = this.sessionDetails.userId;
  this.applicationId = this.sessionDetails.application.applicationId;
  this.sessionId = this.sessionDetails.sessionId;
  this.sessionAttributes = this.sessionDetails.attributes;
  this.isSessionNew = (true === this.sessionDetails.new);
  this.session = function(key) {
    try {
      return this.sessionDetails.attributes[key];
    } catch (e) {
      console.error("key not found on session attributes: " + key, e);
      return;
    }
  };
};

alexa.apps = {};

alexa.app = function(name, endpoint) {
  var self = this;
  this.name = name;
  this.messages = {
    // When an intent was passed in that the application was not configured to handle
    "NO_INTENT_FOUND": "Sorry, the application didn't know what to do with that intent",
    // When the app was used with 'open' or 'launch' but no launch handler was defined
    "NO_LAUNCH_FUNCTION": "Try telling the application what to do instead of opening it",
    // When a request type was not recognized
    "INVALID_REQUEST_TYPE": "Error: not a valid request",
    // If some other exception happens
    "GENERIC_ERROR": "Sorry, the application encountered an error"
  };

  // Persist session variables from every request into every response?
  this.persistentSession = true;

  // use a minimal set of utterances or the full cartesian product?
  this.exhaustiveUtterances = false;

  // A catch-all error handler - do nothing by default
  this.error = null;

  // pre/post hooks to be run on every request
  this.pre = function(/*request, response, type*/) {};
  this.post = function(/*request, response, type*/) {};

  this.endpoint = endpoint;
  // A mapping of keywords to arrays of possible values, for expansion of sample utterances
  this.dictionary = {};
  this.intents = {};
  this.intent = function(intentName, schema, func) {
    if (typeof schema == "function") {
      func = schema;
      schema = null;
    }
    self.intents[intentName] = {
      "name": intentName,
      "function": func
    };
    if (schema) {
      self.intents[intentName].schema = schema;
    }
  };
  this.launchFunc = null;
  this.launch = function(func) {
    self.launchFunc = func;
  };
  this.sessionEndedFunc = null;
  this.sessionEnded = function(func) {
    self.sessionEndedFunc = func;
  };
  this.request = function(request_json) {
    return new Promise(function(resolve, reject) {
      var request = new alexa.request(request_json);
      var response = new alexa.response();
      var postExecuted = false;
      // Attach Promise resolve/reject functions to the response object
      response.send = function(exception) {
        if (typeof self.post == "function" && !postExecuted) {
          postExecuted = true;
          self.post(request, response, requestType, exception);
        }
        if (!response.resolved) {
          response.resolved = true;
          resolve(response.response);
        }
      };
      response.fail = function(msg, exception) {
        if (typeof self.post == "function" && !postExecuted) {
          postExecuted = true;
          self.post(request, response, requestType, exception);
        }
        if (!response.resolved) {
          response.resolved = true;
          reject(msg);
        }
      };
      try {
        var key;
        // Copy all the session attributes from the request into the response so they persist.
        // The Alexa API doesn't think session variables should persist for the entire
        // duration of the session, but I do.
        if (request.sessionAttributes && self.persistentSession) {
          for (key in request.sessionAttributes) {
            response.session(key, request.sessionAttributes[key]);
          }
        }
        var requestType = request.type();
        console.log('Request type: ' + requestType);
        if (typeof self.pre == "function") {
          self.pre(request, response, requestType);
        }
        if (!response.resolved) {
          if ("IntentRequest" === requestType || "Messaging.MessageReceived" === requestType) {
            var intent = request_json.request.intent.name;
            if (typeof self.intents[intent] != "undefined" && typeof self.intents[intent]["function"] == "function") {
              if (false !== self.intents[intent]["function"](request, response)) {
                response.send();
              }
            } else {
              throw "NO_INTENT_FOUND";
            }
          } else if ("LaunchRequest" === requestType) {
            if (typeof self.launchFunc == "function") {
              if (false !== self.launchFunc(request, response)) {
                response.send();
              }
            } else {
              throw "NO_LAUNCH_FUNCTION";
            }
          } else if ("SessionEndedRequest" === requestType) {
            if (typeof self.sessionEndedFunc == "function") {
              if (false !== self.sessionEndedFunc(request, response)) {
                response.send();
              }
            }
          } else {
            throw "INVALID_REQUEST_TYPE";
          }
        }
      } catch (e) {
        if (typeof self.error == "function") {
          self.error(e, request, response);
        } else if (typeof e == "string" && self.messages[e]) {
          response.say(self.messages[e]);
          response.send(e);
        }
        if (!response.resolved) {
          response.fail("Unhandled exception" + e.message, e);
        }
      }
    });
  };

  // Extract the schema and generate a schema JSON object
  this.schema = function() {
    var schema = {
      "intents": []
    }, intentName, intent, key;
    for (intentName in self.intents) {
      intent = self.intents[intentName];
      var intentSchema = {
        "intent": intent.name,
        "slots": []
      };
      if (intent.schema) {
        if (intent.schema.slots) {
          for (key in intent.schema.slots) {
            intentSchema.slots.push({
              "name": key,
              "type": intent.schema.slots[key]
            });
          }
        }
      }
      schema.intents.push(intentSchema);
    }
    return JSON.stringify(schema, null, 3);
  };

  // Generate a list of sample utterances
  this.utterances = function() {
    var intentName,
      intent,
      out = "";
    for (intentName in self.intents) {
      intent = self.intents[intentName];
      if (intent.schema && intent.schema.utterances) {
        intent.schema.utterances.forEach(function(sample) {
          var list = AlexaUtterances(sample,
            intent.schema.slots,
            self.dictionary,
            self.exhaustiveUtterances);
          list.forEach(function(utterance) {
            out += intent.name + "\t" + (utterance.replace(/\s+/g, " ")).trim() + "\n";
          });
        });
      }
    }
    return out;
  };

  // A built-in handler for AWS Lambda
  this.handler = function(event, context) {
    self.request(event)
      .then(function(response) {
        context.succeed(response);
      })
      .catch(function(response) {
        context.fail(response);
      });
  };

  // For backwards compatibility
  this.lambda = function() {
    return self.handler;
  };

  // A utility method to bootstrap alexa endpoints into express automatically
  this.express = function(express, path, enableDebug) {
    var endpoint = (path || "/") + (self.endpoint || self.name);
    express.post(endpoint, function(req, res) {
      self.request(req.body).then(function(response) {
        res.json(response);
      }, function() {
        res.status(500).send("Server Error");
      });
    });
    if (typeof enableDebug != "boolean") {
      enableDebug = true;
    }
    if (enableDebug) {
      express.get(endpoint, function(req, res) {
        res.render("test", {
          "json": self,
          "schema": self.schema(),
          "utterances": self.utterances()
        });
      });
    }
  };

  // Add the app to the global list of named apps
  if (name) {
    alexa.apps[name] = self;
  }

  return this;
};

module.exports = alexa;
<commit_msg>another debugging statement<commit_after>var Promise = require("bluebird");
var AlexaUtterances = require("alexa-utterances");
var SSML = require("./to-ssml");
var alexa = {};

alexa.response = function() {
  this.resolved = false;
  this.response = {
    "version": "1.0",
    "sessionAttributes": {},
    "response": {
      "shouldEndSession": true
    }
  };
  this.say = function(str) {
    if (typeof this.response.response.outputSpeech == "undefined") {
      this.response.response.outputSpeech = {
        "type": "SSML",
        "ssml": SSML.fromStr(str)
      };
    } else {
      // append str to the current outputSpeech, stripping the out speak tag
      this.response.response.outputSpeech.ssml = SSML.fromStr(str, this.response.response.outputSpeech.ssml);
    }
    return this;
  };
  this.clear = function(/*str*/) {
    this.response.response.outputSpeech = {
      "type": "PlainText",
      "text": ""
    };
    return this;
  };
  this.reprompt = function(str) {
    if (typeof this.response.response.reprompt == "undefined") {
      this.response.response.reprompt = {
        "outputSpeech": {
          "type": "SSML",
          "ssml": SSML.fromStr(str)
        }
      };
    } else {
      // append str to the current outputSpeech, stripping the out speak tag
      this.response.response.reprompt.outputSpeech.ssml = SSML.fromStr(str, this.response.response.reprompt.outputSpeech.text);
    }
    return this;
  };
  this.card = function(oCard) {
    if (2 == arguments.length) {  //backwards compat
      oCard = {
        type: "Simple",
        title: arguments[0],
        content: arguments[1]
      };
    }

    var requiredAttrs = [],
      clenseAttrs = [];

    switch (oCard.type) {
      case 'Simple':
        requiredAttrs.push('content');
        clenseAttrs.push('content');
        break;
      case 'Standard':
        requiredAttrs.push('text');
        clenseAttrs.push('text');
        if (('image' in oCard) && ( !('smallImageUrl' in oCard['image']) && !('largeImageUrl' in oCard['image']) )) {
          console.error('If card.image is defined, must specify at least smallImageUrl or largeImageUrl');
          return this;
        }
        break;
      default:
        break;
    }

    var hasAllReq = requiredAttrs.every(function(idx) {
      if (!(idx in oCard)) {
        console.error('Card object is missing required attr "' + idx + '"');
        return false;
      }
      return true;
    });

    if (!hasAllReq) {
      return this;
    }

    // remove all SSML to keep the card clean
    clenseAttrs.forEach(function(idx) {
      oCard[idx] = SSML.cleanse(oCard[idx]);
    });

    this.response.response.card = oCard;

    return this;
  };
  this.linkAccount = function() {
    this.response.response.card = {
      "type": "LinkAccount"
    };
    return this;
  };
  this.shouldEndSession = function(bool, reprompt) {
    this.response.response.shouldEndSession = bool;
    if (reprompt) {
      this.reprompt(reprompt);
    }
    return this;
  };
  this.session = function(key, val) {
    if (typeof val == "undefined") {
      return this.response.sessionAttributes[key];
    } else {
      this.response.sessionAttributes[key] = val;
    }
    return this;
  };
  this.clearSession = function(key) {
    if (typeof key == "string" && typeof this.response.sessionAttributes[key] != "undefined") {
      delete this.response.sessionAttributes[key];
    } else {
      this.response.sessionAttributes = {};
    }
    return this;
  };

};

alexa.request = function(json) {
  this.data = json;
  this.slot = function(slotName, defaultValue) {
    try {
      return this.data.request.intent.slots[slotName].value;
    } catch (e) {
      console.error("missing intent in request: " + slotName, e);
      return defaultValue;
    }
  };
  this.type = function() {
    console.log(this.data);
    try {
      return this.data.request.type;
    } catch (e) {
      console.error("missing type", e);
      return null;
    }
  };

  if (typeof this.data.session == 'undefined') {
    this.sessionDetails = {
      "new": false,
      "sessionId": null,
      "userId": null,
      "accessToken": null,
      "attributes": {},
      "application": {
        applicationId: null
      }
    };
  } else {
    this.sessionDetails = {
      "new": this.data.session.new,
      "sessionId": this.data.session.sessionId,
      "userId": this.data.session.user.userId,
      "accessToken": this.data.session.user.accessToken || null,
      "attributes": this.data.session.attributes,
      "application": this.data.session.application
    };
  }
  this.userId = this.sessionDetails.userId;
  this.applicationId = this.sessionDetails.application.applicationId;
  this.sessionId = this.sessionDetails.sessionId;
  this.sessionAttributes = this.sessionDetails.attributes;
  this.isSessionNew = (true === this.sessionDetails.new);
  this.session = function(key) {
    try {
      return this.sessionDetails.attributes[key];
    } catch (e) {
      console.error("key not found on session attributes: " + key, e);
      return;
    }
  };
};

alexa.apps = {};

alexa.app = function(name, endpoint) {
  var self = this;
  this.name = name;
  this.messages = {
    // When an intent was passed in that the application was not configured to handle
    "NO_INTENT_FOUND": "Sorry, the application didn't know what to do with that intent",
    // When the app was used with 'open' or 'launch' but no launch handler was defined
    "NO_LAUNCH_FUNCTION": "Try telling the application what to do instead of opening it",
    // When a request type was not recognized
    "INVALID_REQUEST_TYPE": "Error: not a valid request",
    // If some other exception happens
    "GENERIC_ERROR": "Sorry, the application encountered an error"
  };

  // Persist session variables from every request into every response?
  this.persistentSession = true;

  // use a minimal set of utterances or the full cartesian product?
  this.exhaustiveUtterances = false;

  // A catch-all error handler - do nothing by default
  this.error = null;

  // pre/post hooks to be run on every request
  this.pre = function(/*request, response, type*/) {};
  this.post = function(/*request, response, type*/) {};

  this.endpoint = endpoint;
  // A mapping of keywords to arrays of possible values, for expansion of sample utterances
  this.dictionary = {};
  this.intents = {};
  this.intent = function(intentName, schema, func) {
    if (typeof schema == "function") {
      func = schema;
      schema = null;
    }
    self.intents[intentName] = {
      "name": intentName,
      "function": func
    };
    if (schema) {
      self.intents[intentName].schema = schema;
    }
  };
  this.launchFunc = null;
  this.launch = function(func) {
    self.launchFunc = func;
  };
  this.sessionEndedFunc = null;
  this.sessionEnded = function(func) {
    self.sessionEndedFunc = func;
  };
  this.request = function(request_json) {
    return new Promise(function(resolve, reject) {
      var request = new alexa.request(request_json);
      var response = new alexa.response();
      var postExecuted = false;
      // Attach Promise resolve/reject functions to the response object
      response.send = function(exception) {
        if (typeof self.post == "function" && !postExecuted) {
          postExecuted = true;
          self.post(request, response, requestType, exception);
        }
        if (!response.resolved) {
          response.resolved = true;
          resolve(response.response);
        }
      };
      response.fail = function(msg, exception) {
        if (typeof self.post == "function" && !postExecuted) {
          postExecuted = true;
          self.post(request, response, requestType, exception);
        }
        if (!response.resolved) {
          response.resolved = true;
          reject(msg);
        }
      };
      try {
        var key;
        // Copy all the session attributes from the request into the response so they persist.
        // The Alexa API doesn't think session variables should persist for the entire
        // duration of the session, but I do.
        if (request.sessionAttributes && self.persistentSession) {
          for (key in request.sessionAttributes) {
            response.session(key, request.sessionAttributes[key]);
          }
        }
        var requestType = request.type();
        console.log('Request type: ' + requestType);
        if (typeof self.pre == "function") {
          self.pre(request, response, requestType);
        }
        if (!response.resolved) {
          if ("IntentRequest" === requestType || "Messaging.MessageReceived" === requestType) {
            if ("IntentRequest" === requestType) {
            var intent = request_json.request.intent.name;
            if (typeof self.intents[intent] != "undefined" && typeof self.intents[intent]["function"] == "function") {
              if (false !== self.intents[intent]["function"](request, response)) {
                response.send();
              }
            } else {
              throw "NO_INTENT_FOUND";
            }
          } else if ("LaunchRequest" === requestType) {
            if (typeof self.launchFunc == "function") {
              if (false !== self.launchFunc(request, response)) {
                response.send();
              }
            } else {
              throw "NO_LAUNCH_FUNCTION";
            }
          } else if ("SessionEndedRequest" === requestType) {
            if (typeof self.sessionEndedFunc == "function") {
              if (false !== self.sessionEndedFunc(request, response)) {
                response.send();
              }
            }
          } else {
            throw "INVALID_REQUEST_TYPE";
          }
        }
      } catch (e) {
        if (typeof self.error == "function") {
          self.error(e, request, response);
        } else if (typeof e == "string" && self.messages[e]) {
          response.say(self.messages[e]);
          response.send(e);
        }
        if (!response.resolved) {
          response.fail("Unhandled exception" + e.message, e);
        }
      }
    });
  };

  // Extract the schema and generate a schema JSON object
  this.schema = function() {
    var schema = {
      "intents": []
    }, intentName, intent, key;
    for (intentName in self.intents) {
      intent = self.intents[intentName];
      var intentSchema = {
        "intent": intent.name,
        "slots": []
      };
      if (intent.schema) {
        if (intent.schema.slots) {
          for (key in intent.schema.slots) {
            intentSchema.slots.push({
              "name": key,
              "type": intent.schema.slots[key]
            });
          }
        }
      }
      schema.intents.push(intentSchema);
    }
    return JSON.stringify(schema, null, 3);
  };

  // Generate a list of sample utterances
  this.utterances = function() {
    var intentName,
      intent,
      out = "";
    for (intentName in self.intents) {
      intent = self.intents[intentName];
      if (intent.schema && intent.schema.utterances) {
        intent.schema.utterances.forEach(function(sample) {
          var list = AlexaUtterances(sample,
            intent.schema.slots,
            self.dictionary,
            self.exhaustiveUtterances);
          list.forEach(function(utterance) {
            out += intent.name + "\t" + (utterance.replace(/\s+/g, " ")).trim() + "\n";
          });
        });
      }
    }
    return out;
  };

  // A built-in handler for AWS Lambda
  this.handler = function(event, context) {
    self.request(event)
      .then(function(response) {
        context.succeed(response);
      })
      .catch(function(response) {
        context.fail(response);
      });
  };

  // For backwards compatibility
  this.lambda = function() {
    return self.handler;
  };

  // A utility method to bootstrap alexa endpoints into express automatically
  this.express = function(express, path, enableDebug) {
    var endpoint = (path || "/") + (self.endpoint || self.name);
    express.post(endpoint, function(req, res) {
      self.request(req.body).then(function(response) {
        res.json(response);
      }, function() {
        res.status(500).send("Server Error");
      });
    });
    if (typeof enableDebug != "boolean") {
      enableDebug = true;
    }
    if (enableDebug) {
      express.get(endpoint, function(req, res) {
        res.render("test", {
          "json": self,
          "schema": self.schema(),
          "utterances": self.utterances()
        });
      });
    }
  };

  // Add the app to the global list of named apps
  if (name) {
    alexa.apps[name] = self;
  }

  return this;
};

module.exports = alexa;
<|endoftext|>


<commit_before>var Twitter = require('twitter');
var GoogleSpreadsheet = require("google-spreadsheet");

var client = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

function getTweet(cb) {
    var sheet = new GoogleSpreadsheet(process.env.GOOGLE_SHEET_ID);

    sheet.getRows(1, function (error, tweets) {
        if (error) throw error;

        var index = Math.floor(Math.random() * tweets.length);
        var tweet = tweets[index];
        cb(tweet);
    });
}

function sendTweet(status) {
    client.post('statuses/update', {
            status: status
        },
        function (error, tweet, response) {
            if (error) throw error;
        });
}

getTweet(function (tweet) {
    if (tweet) {
        console.log(tweet.tweet);
        //sendTweet(tweet);
    }
});
<commit_msg>Send the tweet<commit_after>var Twitter = require('twitter');
var GoogleSpreadsheet = require("google-spreadsheet");

var client = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

function getTweet(cb) {
    var sheet = new GoogleSpreadsheet(process.env.GOOGLE_SHEET_ID);

    sheet.getRows(1, function (error, tweets) {
        if (error) throw error;

        var index = Math.floor(Math.random() * tweets.length);
        var tweet = tweets[index];
        cb(tweet);
    });
}

function sendTweet(status) {
    client.post('statuses/update', {
            status: status
        },
        function (error, tweet, response) {
            if (error) throw error;
        });
}

getTweet(function (tweet) {
    if (tweet) {
        console.log(tweet.tweet);
        sendTweet(tweet);
    }
});
<|endoftext|>


<commit_before>'use strict';
var childProcess = require('child_process');
var findVersions = require('find-versions');

module.exports = function (bin, cb) {
	childProcess.exec(bin + ' --version', function (err, stdout, stderr) {
		if (err) {
			if (err.code === 'ENOENT') {
				err.message = 'Couldn\'t find the `' + bin + '` binary. Make sure it\'s installed and in your $PATH';
			}

			return cb(err);
		}

		cb(null, findVersions(stdout.trim() || stderr.trim(), {loose: true})[0]);
	});
};
<commit_msg>add quotes around the `bin` argument - closes #4<commit_after>'use strict';
var childProcess = require('child_process');
var findVersions = require('find-versions');

module.exports = function (bin, cb) {
	childProcess.exec('\'' + bin + '\' --version', function (err, stdout, stderr) {
		if (err) {
			if (err.code === 'ENOENT') {
				err.message = 'Couldn\'t find the `' + bin + '` binary. Make sure it\'s installed and in your $PATH';
			}

			return cb(err);
		}

		cb(null, findVersions(stdout.trim() || stderr.trim(), {loose: true})[0]);
	});
};
<|endoftext|>


<commit_before>/**
 * Created by pkleim on 5/13/2015.
 */
module.exports = {
    gen: function(jscs, options) {
        var options = options || {};

        options.title = options.title || "Style Guide";

        return "JSCS:" + options.title + jscs.requireCurlyBraces;
    }
};
<commit_msg>new message<commit_after>/**
 * Created by pkleim on 5/13/2015.
 */
module.exports = {
    gen: function(jscs, options) {
        var options = options || {};

        options.title = options.title || "Style Guide";

        return "JSCS: " + options.title + jscs.requireCurlyBraces;
    }
};
<|endoftext|>