<commit_before>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {

            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = req.body;
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        if (facebook_message.message) {

                            var message = {
                                text: facebook_message.message.text,
                                user: facebook_message.sender.id,
                                channel: facebook_message.sender.id,
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                            };

                            facebook_botkit.receiveMessage(bot, message);
                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: facebook_message.sender.id,
                                channel: facebook_message.sender.id,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: facebook_message.sender.id,
                                channel: facebook_message.sender.id,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: facebook_message.sender.id,
                                channel: facebook_message.sender.id,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.json());
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<commit_msg>to string<commit_after>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id.toString() = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {

            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = req.body;
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        if (facebook_message.message) {

                            var message = {
                                text: facebook_message.message.text,
                                user: facebook_message.sender.id.toString(),
                                channel: facebook_message.sender.id.toString(),
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                            };

                            facebook_botkit.receiveMessage(bot, message);
                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: facebook_message.sender.id.toString(),
                                channel: facebook_message.sender.id,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: facebook_message.sender.id.toString(),
                                channel: facebook_message.sender.id.toString(),
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: facebook_message.sender.id.toString(),
                                channel: facebook_message.sender.id.toString(),
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.json());
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('app.states')
    .controller('BlueprintEditorController', ['$scope', '$timeout', 'BlueprintsState', 'DesignerState', 'BlueprintDetailsModal',
      'SaveBlueprintModal', '$state', 'Notifications', 'sprintf', ComponentController]);

  /** @ngInject */
  function ComponentController($scope, $timeout, BlueprintsState, DesignerState, BlueprintDetailsModal, SaveBlueprintModal, $state,
                               Notifications, sprintf) {
    $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      if (toState.name === 'login') {
        return;
      }
      if (fromState.name === "designer.blueprints.editor" && toState.name !== "designer.blueprints.editor") {
        var origBlueprint = BlueprintsState.getOriginalBlueprint();
        if (!BlueprintsState.doNotSave() && !angular.equals(origBlueprint, $scope.blueprint) && !event.defaultPrevented) {
          SaveBlueprintModal.showModal($scope.blueprint, toState, toParams, fromState, fromParams);
          event.preventDefault();
        }
      }
    });

    $scope.blueprint = $scope.$parent.vm.blueprint;

    var blueprintDirty = false;

    if (!$scope.blueprint) {
      $scope.blueprint = angular.copy(newBlueprint());
    }

    BlueprintsState.saveOriginalBlueprint(angular.copy($scope.blueprint));

    // $log.debug("RETRIEVED Blueprint: " + angular.toJson($scope.blueprint, true));

    $scope.$watch("blueprint", function(oldValue, newValue) {
      if (!angular.equals(oldValue, newValue, true)) {
        blueprintDirty = true;
      }
    }, true);

    $scope.$on('BlueprintCanvasChanged', function(evt, args) {
      if (args.chartDataModel && !angular.equals($scope.blueprint.ui_properties.chart_data_model, args.chartDataMode)) {
        $scope.blueprint.ui_properties.chart_data_model = args.chartDataModel;
        blueprintDirty = true;
      }
    });

    $scope.blueprintUnchanged = function() {
      return !blueprintDirty;
    };

    function newBlueprint() {
      var blueprint = BlueprintsState.getNewBlueprintObj();
      blueprintDirty = true;

      return blueprint;
    }

    $scope.saveBlueprint = function() {
      BlueprintsState.saveBlueprint($scope.blueprint).then(saveSuccess, saveFailure);

      function saveSuccess(id) {
        Notifications.success(sprintf(__("'%s' was succesfully saved."), $scope.blueprint.name));
        if (id) {
          $state.go($state.current, {blueprintId: id}, {reload: true});
        }

        /*
         Saving in case we decide to not always reload; for performance

         get another copy to work, different obj from what was saved
         BlueprintsState.saveOriginalBlueprint(angular.copy($scope.blueprint));
         blueprintDirty = false;
         $( "#saveBtm" ).blur();
         $log.debug("Saved blueprint from designer"); */
      }

      function saveFailure() {
        Notifications.error(sprintf(__("Failed to save '%s'."), $scope.blueprint.name));
      }
    };

    $scope.editDetails = function() {
      $scope.loading = true;
      BlueprintDetailsModal.showModal('edit', $scope.blueprint).then(
        function() {
          $scope.loading = false;
        });
    };

    $scope.itemsSelected = function() {
      if ($scope.chartViewModel && $scope.chartViewModel.getSelectedNodes) {
        return $scope.chartViewModel.getSelectedNodes().length > 0;
      } else {
        return false;
      }
    };

    $scope.onlyOneTtemSelected = function() {
      if ($scope.chartViewModel && $scope.chartViewModel.getSelectedNodes) {
        return $scope.chartViewModel.getSelectedNodes().length === 1;
      } else {
        return false;
      }
    };

    $scope.duplicateSelectedItem = function() {
      $scope.$broadcast('duplicateSelectedItem');
      angular.element("#duplicateItem").blur();
    };

    $scope.removeSelectedItemsFromCanvas = function() {
      $scope.$broadcast('removeSelectedItems');
      angular.element("#removeItems").blur();
    };

    /*  Catalog Editor Toolbox Methods */

    $scope.toolboxVisible = false;

    $scope.showToolbox = function() {
      $scope.toolboxVisible = true;
      // add class to subtabs to apply PF style and
      // focus to filter input box

      $timeout(function() {
        angular.element(".subtabs>ul").addClass('nav-tabs-pf');
        angular.element("#filterFld").focus();
      });
    };

    $scope.hideToolbox = function() {
      $scope.toolboxVisible = false;
    };

    $scope.$on('clickOnChart', function(evt) {
      $scope.hideToolbox();
    });

    $scope.tabClicked = function() {
      angular.element("#filterFld").focus();
    };

    $scope.inConnectingMode = false;
    $scope.hideConnectors = false;

    // broadcast hideConnectors change down to canvas
    $scope.toggleshowHideConnectors = function() {
      $scope.$broadcast('hideConnectors', {hideConnectors: $scope.hideConnectors});
    };

    // listen for in connecting mode from canvas
    $scope.$on('inConnectingMode', function(evt, args) {
      $scope.inConnectingMode = args.inConnectingMode;
      $scope.hideConnectors = false;
    });

    $scope.tabs = DesignerState.getDesignerToolboxTabs($scope.$parent.vm.serviceTemplates);

    $scope.getNewItem = function() {
      var activeTab = $scope.activeTab();
      var activeSubTab = $scope.activeSubTab();
      var activeSubSubTab = $scope.activeSubSubTab();

      if (activeSubSubTab && activeSubSubTab.newItem) {
        return activeSubSubTab.newItem;
      }

      if (activeSubTab && activeSubTab.newItem) {
        return activeSubTab.newItem;
      }

      if (activeTab && activeTab.newItem) {
        return activeTab.newItem;
      }

      return null;
    };

    $scope.activeTab = function() {
      return $scope.tabs.filter(function(tab) {
        return tab.active;
      })[0];
    };

    $scope.activeSubTab = function() {
      var activeTab = $scope.activeTab();
      if (activeTab && activeTab.subtabs) {
        return activeTab.subtabs.filter(function(subtab) {
          return subtab.active;
        })[0];
      }
    };

    $scope.activeSubSubTab = function() {
      var activeSubTab = $scope.activeSubTab();
      if (activeSubTab && activeSubTab.subtabs) {
        return activeSubTab.subtabs.filter(function(subsubtab) {
          return subsubtab.active;
        })[0];
      }
    };
  }
})();
<commit_msg>Designer: Fixed Save Blueprint Notification<commit_after>(function() {
  'use strict';

  angular.module('app.states')
    .controller('BlueprintEditorController', ['$scope', '$timeout', 'BlueprintsState', 'DesignerState', 'BlueprintDetailsModal',
      'SaveBlueprintModal', '$state', 'EventNotifications', 'sprintf', ComponentController]);

  /** @ngInject */
  function ComponentController($scope, $timeout, BlueprintsState, DesignerState, BlueprintDetailsModal, SaveBlueprintModal, $state,
                               EventNotifications, sprintf) {
    $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      if (toState.name === 'login') {
        return;
      }
      if (fromState.name === "designer.blueprints.editor" && toState.name !== "designer.blueprints.editor") {
        var origBlueprint = BlueprintsState.getOriginalBlueprint();
        if (!BlueprintsState.doNotSave() && !angular.equals(origBlueprint, $scope.blueprint) && !event.defaultPrevented) {
          SaveBlueprintModal.showModal($scope.blueprint, toState, toParams, fromState, fromParams);
          event.preventDefault();
        }
      }
    });

    $scope.blueprint = $scope.$parent.vm.blueprint;

    var blueprintDirty = false;

    if (!$scope.blueprint) {
      $scope.blueprint = angular.copy(newBlueprint());
    }

    BlueprintsState.saveOriginalBlueprint(angular.copy($scope.blueprint));

    // $log.debug("RETRIEVED Blueprint: " + angular.toJson($scope.blueprint, true));

    $scope.$watch("blueprint", function(oldValue, newValue) {
      if (!angular.equals(oldValue, newValue, true)) {
        blueprintDirty = true;
      }
    }, true);

    $scope.$on('BlueprintCanvasChanged', function(evt, args) {
      if (args.chartDataModel && !angular.equals($scope.blueprint.ui_properties.chart_data_model, args.chartDataMode)) {
        $scope.blueprint.ui_properties.chart_data_model = args.chartDataModel;
        blueprintDirty = true;
      }
    });

    $scope.blueprintUnchanged = function() {
      return !blueprintDirty;
    };

    function newBlueprint() {
      var blueprint = BlueprintsState.getNewBlueprintObj();
      blueprintDirty = true;

      return blueprint;
    }

    $scope.saveBlueprint = function() {
      BlueprintsState.saveBlueprint($scope.blueprint).then(saveSuccess, saveFailure);

      function saveSuccess(id) {
        EventNotifications.success(sprintf(__("'%s' was succesfully saved."), $scope.blueprint.name));
        if (id) {
          $state.go($state.current, {blueprintId: id}, {reload: true});
        }

        /*
         Saving in case we decide to not always reload; for performance

         get another copy to work, different obj from what was saved
         BlueprintsState.saveOriginalBlueprint(angular.copy($scope.blueprint));
         blueprintDirty = false;
         $( "#saveBtm" ).blur();
         $log.debug("Saved blueprint from designer"); */
      }

      function saveFailure() {
        EventNotifications.error(sprintf(__("Failed to save '%s'."), $scope.blueprint.name));
      }
    };

    $scope.editDetails = function() {
      $scope.loading = true;
      BlueprintDetailsModal.showModal('edit', $scope.blueprint).then(
        function() {
          $scope.loading = false;
        });
    };

    $scope.itemsSelected = function() {
      if ($scope.chartViewModel && $scope.chartViewModel.getSelectedNodes) {
        return $scope.chartViewModel.getSelectedNodes().length > 0;
      } else {
        return false;
      }
    };

    $scope.onlyOneTtemSelected = function() {
      if ($scope.chartViewModel && $scope.chartViewModel.getSelectedNodes) {
        return $scope.chartViewModel.getSelectedNodes().length === 1;
      } else {
        return false;
      }
    };

    $scope.duplicateSelectedItem = function() {
      $scope.$broadcast('duplicateSelectedItem');
      angular.element("#duplicateItem").blur();
    };

    $scope.removeSelectedItemsFromCanvas = function() {
      $scope.$broadcast('removeSelectedItems');
      angular.element("#removeItems").blur();
    };

    /*  Catalog Editor Toolbox Methods */

    $scope.toolboxVisible = false;

    $scope.showToolbox = function() {
      $scope.toolboxVisible = true;
      // add class to subtabs to apply PF style and
      // focus to filter input box

      $timeout(function() {
        angular.element(".subtabs>ul").addClass('nav-tabs-pf');
        angular.element("#filterFld").focus();
      });
    };

    $scope.hideToolbox = function() {
      $scope.toolboxVisible = false;
    };

    $scope.$on('clickOnChart', function(evt) {
      $scope.hideToolbox();
    });

    $scope.tabClicked = function() {
      angular.element("#filterFld").focus();
    };

    $scope.inConnectingMode = false;
    $scope.hideConnectors = false;

    // broadcast hideConnectors change down to canvas
    $scope.toggleshowHideConnectors = function() {
      $scope.$broadcast('hideConnectors', {hideConnectors: $scope.hideConnectors});
    };

    // listen for in connecting mode from canvas
    $scope.$on('inConnectingMode', function(evt, args) {
      $scope.inConnectingMode = args.inConnectingMode;
      $scope.hideConnectors = false;
    });

    $scope.tabs = DesignerState.getDesignerToolboxTabs($scope.$parent.vm.serviceTemplates);

    $scope.getNewItem = function() {
      var activeTab = $scope.activeTab();
      var activeSubTab = $scope.activeSubTab();
      var activeSubSubTab = $scope.activeSubSubTab();

      if (activeSubSubTab && activeSubSubTab.newItem) {
        return activeSubSubTab.newItem;
      }

      if (activeSubTab && activeSubTab.newItem) {
        return activeSubTab.newItem;
      }

      if (activeTab && activeTab.newItem) {
        return activeTab.newItem;
      }

      return null;
    };

    $scope.activeTab = function() {
      return $scope.tabs.filter(function(tab) {
        return tab.active;
      })[0];
    };

    $scope.activeSubTab = function() {
      var activeTab = $scope.activeTab();
      if (activeTab && activeTab.subtabs) {
        return activeTab.subtabs.filter(function(subtab) {
          return subtab.active;
        })[0];
      }
    };

    $scope.activeSubSubTab = function() {
      var activeSubTab = $scope.activeSubTab();
      if (activeSubTab && activeSubTab.subtabs) {
        return activeSubTab.subtabs.filter(function(subsubtab) {
          return subsubtab.active;
        })[0];
      }
    };
  }
})();
<|endoftext|>


<commit_before>var _ = require('lodash');

var Injector = function (valueDelimiter) {
    if (!valueDelimiter) {
        throw new Error('Invalid value delimiter');
    }

    this.beans = {};
    this.instances = {};
    this.values = {};
    this.valueDelimiter = valueDelimiter;
};

Injector.prototype._value = function (path, val) {
    if (!_.isString(path) || !path) {
        return this.values;
    }

    var parent = null;
    var obj = this.values;
    var parts = path.split('.');
    var key;
    while (parts.length > 0) {
        key = parts.shift();
        if (_.isNull(obj[key]) || _.isUndefined(obj[key])) {
            obj[key] = {};
        }
        parent = obj;
        obj = obj[key];
    }

    if (parent && arguments.length > 1) {
        parent[key] = val;
        return val;
    }

    return obj;
};

Injector.prototype.setValue = function (path, val) {
    if (_.isString(path)) {
        this._value(path, val);
    } else {
        this.values = _.extend({}, val);
    }
};

Injector.prototype.getValue = function (path) {
    return this._value(path);
};

Injector.prototype._isValue = function (name) {
    return name.indexOf(this.valueDelimiter) === 0;
};

Injector.prototype._parseName = function (name) {
    var trimmed = name.trim();

    if (!trimmed) {
        throw new Error('Invalid bean name "' + name + '". Cannot be empty');
    }

    if (this._isValue(trimmed)) {
        throw new Error('Invalid bean name "' + name + '". Cannot start with ' + this.valueDelimiter);
    }

    return trimmed;
};

Injector.prototype.get = function (beanName) {
    var name = this._parseName(beanName);
    var bean = this.beans[name];
    if (!bean) {
        throw new Error('No such bean "' + beanName + '" (parsed as "' + name + '")');
    }

    return bean;
};

Injector.prototype.bean = function (bean) {
    var name = this._parseName(bean.name);
    if (this.beans[name]) {
        throw new Error('Bean "' + bean.name + '" (parsed as "' + name + '") is already defined');
    }

    bean.name = name;
    this.beans[name] = bean;
};

Injector.prototype.inject = function (bean) {

    var args = _.map(bean.inject, function (dep) {
        if (this._isValue(dep)) {
            var path = dep.substr(this.valueDelimiter.length);
            return this.getValue(path);
        }

        var depBean = this.get(dep);
        return this.init(depBean);
    }, this);

    return bean.factory
        ? bind(bean.fn, null, args)
        : function () {
            var obj = Object.create(bean.fn.prototype);
            bean.fn.apply(obj, args);
            return obj;
        };
};

Injector.prototype.init = function (bean) {
    var name = this._parseName(bean.name);
    if (!this.instances.hasOwnProperty(name)) {
        this.instances[name] = this.inject(bean)();
    }

    return this.instances[name];
};

module.exports = Injector;

function bind(fn, thisArg, args) {
    return Function.prototype.bind.apply(fn, [thisArg].concat(args));
}<commit_msg>feat(lib/Injector): change #getValue and #setValue behaviour<commit_after>var _ = require('lodash');

var Injector = function (valueDelimiter) {
    if (!valueDelimiter) {
        throw new Error('Invalid value delimiter');
    }

    this.beans = {};
    this.instances = {};
    this.values = {};
    this.valueDelimiter = valueDelimiter;
};

Injector.prototype.setValue = function (path, val) {
    if (!path || !_.isString(path)) {
        this.values = val;
        return;
    }

    var parts = path.split('.');
    var lastKey = parts.pop();
    var obj = _.reduce(parts, function (obj, key) {
        if (!obj.hasOwnProperty(key)) {
            obj[key] = {};
        }
        return obj[key];
    }, this.values);

    obj[lastKey] = val;
    return obj;
};

Injector.prototype.getValue = function (path) {
    if (!path || !_.isString(path)) {
        return this.values;
    }

    var parts = path.split('.');
    return _.reduce(parts, function (obj, key) {
        if (!obj.hasOwnProperty(key)) {
            throw new Error('Could not find value "' + path + '"');
        }
        return obj[key];
    }, this.values);
};

Injector.prototype._isValue = function (name) {
    return name.indexOf(this.valueDelimiter) === 0;
};

Injector.prototype._parseName = function (name) {
    var trimmed = name.trim();

    if (!trimmed) {
        throw new Error('Invalid bean name "' + name + '". Cannot be empty');
    }

    if (this._isValue(trimmed)) {
        throw new Error('Invalid bean name "' + name + '". Cannot start with ' + this.valueDelimiter);
    }

    return trimmed;
};

Injector.prototype.get = function (beanName) {
    var name = this._parseName(beanName);
    var bean = this.beans[name];
    if (!bean) {
        throw new Error('No such bean "' + beanName + '" (parsed as "' + name + '")');
    }

    return bean;
};

Injector.prototype.bean = function (bean) {
    var name = this._parseName(bean.name);
    if (this.beans[name]) {
        throw new Error('Bean "' + bean.name + '" (parsed as "' + name + '") is already defined');
    }

    bean.name = name;
    this.beans[name] = bean;
};

Injector.prototype.inject = function (bean) {

    var args = _.map(bean.inject, function (dep) {
        if (this._isValue(dep)) {
            var path = dep.substr(this.valueDelimiter.length);
            return this.getValue(path);
        }

        var depBean = this.get(dep);
        return this.init(depBean);
    }, this);

    return bean.factory
        ? bind(bean.fn, null, args)
        : function () {
            var obj = Object.create(bean.fn.prototype);
            bean.fn.apply(obj, args);
            return obj;
        };
};

Injector.prototype.init = function (bean) {
    var name = this._parseName(bean.name);
    if (!this.instances.hasOwnProperty(name)) {
        this.instances[name] = this.inject(bean)();
    }

    return this.instances[name];
};

module.exports = Injector;

function bind(fn, thisArg, args) {
    return Function.prototype.bind.apply(fn, [thisArg].concat(args));
}<|endoftext|>


<commit_before>var url = require('url'),
	http = require('http'),
	https = require('https'),
	zlib = require('zlib');

var server_string = require('../index').server_string;

var PERMANENT = 'Permanent',
	TEMPORARY = 'Temporary';

function Location(uri) {
	if(!uri) throw new Error('URI for location is not specified');
	this._uri = uri;
	this._uri_regexp = new RegExp(uri);
	this._zlib_options = null;
	this._addproxyheaders = [];
	this._rewrite = null;
	this._forward_raw = null;
}

module.exports = Location;

Location.prototype.forwardToUpstream = function (raw) {
	this._forward_raw = raw;
	return this;
};

Location.prototype.tryResolveUpstream = function (upstream) {
	var _forward_raw_decomposed = url.parse(this._forward_raw);
	if(_forward_raw_decomposed.host == upstream.getName().toLowerCase()) {
		this._forward_to = {
			transport_name: (_forward_raw_decomposed.protocol == 'http:' ? 'http' : (_forward_raw_decomposed.protocol == 'https:' ? 'https' : 'http' )),
			transport: (_forward_raw_decomposed.protocol == 'http:' ? http : (_forward_raw_decomposed.protocol == 'https:' ? https : http )),
			upstream: upstream,
			pathname: _forward_raw_decomposed.pathname
		};
	}

	return this;
};

Location.prototype.addProxyHeader = function (name, value) {
	this._addproxyheaders.push({
		name: name,
		value: value
	});
	return this;
};

Location.prototype.rewrite = function (from, to, range) {
	if(from == '^') from = '^.+$';
	if(range != TEMPORARY && range != PERMANENT) throw new Error('Unknown range "' + range + '": expected either "' + PERMANENT + '" or "' + TEMPORARY + '"');
	this._rewrite = {
		from: new RegExp(from),
		to: to,
		range: range
	};
	return this;
};

Location.prototype.getMatchScore = function (path) {
	if(this._uri_regexp.test(path))
		return this._uri.length;
	return -1;
};

Location.prototype.setZlib = function (zlib_options) {
	this._zlib_options = zlib_options;
	return this;
};

Location.prototype.getZlibType = function (acceptencoding) {
	if(!this._zlib_options || !acceptencoding) return { algorithm: 'none' };

	if(acceptencoding.match(/deflate/)) {
		return {
			algorithm: 'deflate',
			types: this._zlib_options.types,
			minlength: this._zlib_options.minlength
		};
	} else if(acceptencoding.match(/gzip/)) {
		return {
			algorithm: 'gzip',
			types: this._zlib_options.types,
			minlength: this._zlib_options.minlength
		};
	}

	return { algorithm: 'none' };
};

Location.prototype.tryRewrite = function (src_req, src_res) {
	if(this._rewrite) {
		var incoming_url = url.parse(src_req.url);
		var to = src_req.url.replace(this._rewrite.from, this._rewrite.to);
		to = to.replace('$pathname', incoming_url.pathname);
		to = to.replace('$query', incoming_url.query || '');

		if(this._rewrite.range == PERMANENT) {
			src_res.writeHead(301, {
				'server': server_string,
				'location': to
			});
			src_res.end();
			return true;
		} else {
			src_res.writeHead(307, {
				'server': server_string,
				'location': to
			});
			src_res.end();
			return true;
		}
	}
	return false;
};

Location.prototype.tryForward = function (src_req, src_res, logger) {
	if(this._forward_to) {
		var log_primitives = {
			remote_addr: src_req.connection.remoteAddress,
			method: src_req.method,
			url: src_req.url,
			httpversion: src_req.httpVersionMajor + '.' + src_req.httpVersionMinor,
			bytes_sent: 0,
			bytes_received: 0,
			http_referer: src_req.headers['referer'],
			http_user_agent: src_req.headers['user-agent']
		};

		var options = {
			method: src_req.method,
			path: this._forward_to.pathname + src_req.url.substring(1, src_req.url.length),
			headers: src_req.headers
		};

		options.headers['connection'] = 'keep-alive';

		for(var i=0; i<this._addproxyheaders.length; i++) {
			var header = this._addproxyheaders[i],
				name = header.name,
				value = header.value;
			value = value.replace('$x_forwarded_for', src_req.connection.remoteAddress);
			options.headers[name] = value;
		}

		var zlibtype = this.getZlibType(src_req.headers['accept-encoding']);

		var dst_req = this._forward_to.upstream.openTransport(this._forward_to.transport, options, function (dst_res) {
			log_primitives.status = dst_res.statusCode;

			src_req.on('error', function (err) { console.error('Source request error: ' + err); });
			src_res.on('error', function (err) { console.error('Source response error: ' + err); });
			dst_req.on('error', function (err) { console.error('Destination request error: ' + err); });
			dst_res.on('error', function (err) { console.error('Destination response error: ' + err); });

			switch(zlibtype.algorithm) {
			case 'deflate':
			case 'gzip':
				if(!dst_res.headers['content-encoding']
						&& dst_res.headers['content-type']
						&& dst_res.headers['content-length']
						&& parseInt(dst_res.headers['content-length']) > zlibtype.minlength
						&& (zlibtype.types.indexOf(dst_res.headers['content-type'].split(';')[0].toLowerCase()) >= 0)) {
					var _zl = ((zlibtype.algorithm == 'deflate') ? zlib.createDeflate() : zlib.createGzip());
					delete dst_res.headers['content-length'];
					dst_res.headers['content-encoding'] = zlibtype.algorithm;

					dst_res.on('data', function (chunk) { log_primitives.bytes_received += chunk.length; });
					_zl.on('data', function (chunk) { log_primitives.bytes_sent += chunk.length; });
					_zl.on('end', function () { logger && logger.log(log_primitives); });

					src_res.writeHead(dst_res.statusCode, dst_res.headers);
					dst_res.pipe(_zl).pipe(src_res);
					break;
				}
			default:
				src_res.writeHead(dst_res.statusCode, dst_res.headers);

				dst_res.on('data', function (chunk) { log_primitives.bytes_sent += chunk.length; });
				dst_res.on('end', function () { logger && logger.log(log_primitives); });

				dst_res.pipe(src_res);
				break;
			}

		});

		src_req.on('data', function (chunk) { dst_req.write(chunk); })
		src_req.on('end', function () { dst_req.end(); });
	} else {
		src_res.writeHead(404, {
			'server': server_string,
			'connection': 'close'
		});
		src_res.end();
		return true;
	}

};

Location.prototype.toString = function () {
	var retStr = ['LOCATION'];
	retStr.push(this._uri);

	for(var i=0; i< this._addproxyheaders.length; i++) {
		retStr.push('HEADER');
		retStr.push(this._addproxyheaders[i].name + '(' + this._addproxyheaders[i].value + ')');
	}
	if(this._rewrite) {
		retStr.push(this._rewrite.range);
		retStr.push(this._rewrite.from.toString() + ' -> ' + this._rewrite.to);
	}
	if(this._forward_raw) {
		retStr.push('FORWARD');
		retStr.push(this._forward_to.transport_name + ' ' + this._forward_to.upstream.toString());
	}
	return retStr.join(': ');
};<commit_msg>result always includes server string<commit_after>var url = require('url'),
	http = require('http'),
	https = require('https'),
	zlib = require('zlib');

var server_string = require('../index').server_string;

var PERMANENT = 'Permanent',
	TEMPORARY = 'Temporary';

function Location(uri) {
	if(!uri) throw new Error('URI for location is not specified');
	this._uri = uri;
	this._uri_regexp = new RegExp(uri);
	this._zlib_options = null;
	this._addproxyheaders = [];
	this._rewrite = null;
	this._forward_raw = null;
}

module.exports = Location;

Location.prototype.forwardToUpstream = function (raw) {
	this._forward_raw = raw;
	return this;
};

Location.prototype.tryResolveUpstream = function (upstream) {
	var _forward_raw_decomposed = url.parse(this._forward_raw);
	if(_forward_raw_decomposed.host == upstream.getName().toLowerCase()) {
		this._forward_to = {
			transport_name: (_forward_raw_decomposed.protocol == 'http:' ? 'http' : (_forward_raw_decomposed.protocol == 'https:' ? 'https' : 'http' )),
			transport: (_forward_raw_decomposed.protocol == 'http:' ? http : (_forward_raw_decomposed.protocol == 'https:' ? https : http )),
			upstream: upstream,
			pathname: _forward_raw_decomposed.pathname
		};
	}

	return this;
};

Location.prototype.addProxyHeader = function (name, value) {
	this._addproxyheaders.push({
		name: name,
		value: value
	});
	return this;
};

Location.prototype.rewrite = function (from, to, range) {
	if(from == '^') from = '^.+$';
	if(range != TEMPORARY && range != PERMANENT) throw new Error('Unknown range "' + range + '": expected either "' + PERMANENT + '" or "' + TEMPORARY + '"');
	this._rewrite = {
		from: new RegExp(from),
		to: to,
		range: range
	};
	return this;
};

Location.prototype.getMatchScore = function (path) {
	if(this._uri_regexp.test(path))
		return this._uri.length;
	return -1;
};

Location.prototype.setZlib = function (zlib_options) {
	this._zlib_options = zlib_options;
	return this;
};

Location.prototype.getZlibType = function (acceptencoding) {
	if(!this._zlib_options || !acceptencoding) return { algorithm: 'none' };

	if(acceptencoding.match(/deflate/)) {
		return {
			algorithm: 'deflate',
			types: this._zlib_options.types,
			minlength: this._zlib_options.minlength
		};
	} else if(acceptencoding.match(/gzip/)) {
		return {
			algorithm: 'gzip',
			types: this._zlib_options.types,
			minlength: this._zlib_options.minlength
		};
	}

	return { algorithm: 'none' };
};

Location.prototype.tryRewrite = function (src_req, src_res) {
	if(this._rewrite) {
		var incoming_url = url.parse(src_req.url);
		var to = src_req.url.replace(this._rewrite.from, this._rewrite.to);
		to = to.replace('$pathname', incoming_url.pathname);
		to = to.replace('$query', incoming_url.query || '');

		if(this._rewrite.range == PERMANENT) {
			src_res.writeHead(301, {
				'server': server_string,
				'location': to
			});
			src_res.end();
			return true;
		} else {
			src_res.writeHead(307, {
				'server': server_string,
				'location': to
			});
			src_res.end();
			return true;
		}
	}
	return false;
};

Location.prototype.tryForward = function (src_req, src_res, logger) {
	if(this._forward_to) {
		var log_primitives = {
			remote_addr: src_req.connection.remoteAddress,
			method: src_req.method,
			url: src_req.url,
			httpversion: src_req.httpVersionMajor + '.' + src_req.httpVersionMinor,
			bytes_sent: 0,
			bytes_received: 0,
			http_referer: src_req.headers['referer'],
			http_user_agent: src_req.headers['user-agent']
		};

		var options = {
			method: src_req.method,
			path: this._forward_to.pathname + src_req.url.substring(1, src_req.url.length),
			headers: src_req.headers
		};

		options.headers['connection'] = 'keep-alive';

		for(var i=0; i<this._addproxyheaders.length; i++) {
			var header = this._addproxyheaders[i],
				name = header.name,
				value = header.value;
			value = value.replace('$x_forwarded_for', src_req.connection.remoteAddress);
			options.headers[name] = value;
		}

		var zlibtype = this.getZlibType(src_req.headers['accept-encoding']);

		var dst_req = this._forward_to.upstream.openTransport(this._forward_to.transport, options, function (dst_res) {
			log_primitives.status = dst_res.statusCode;

			src_req.on('error', function (err) { console.error('Source request error: ' + err); });
			src_res.on('error', function (err) { console.error('Source response error: ' + err); });
			dst_req.on('error', function (err) { console.error('Destination request error: ' + err); });
			dst_res.on('error', function (err) { console.error('Destination response error: ' + err); });

			dst_res.headers['server'] = server_string;

			switch(zlibtype.algorithm) {
			case 'deflate':
			case 'gzip':
				if(!dst_res.headers['content-encoding']
						&& dst_res.headers['content-type']
						&& dst_res.headers['content-length']
						&& parseInt(dst_res.headers['content-length']) > zlibtype.minlength
						&& (zlibtype.types.indexOf(dst_res.headers['content-type'].split(';')[0].toLowerCase()) >= 0)) {
					var _zl = ((zlibtype.algorithm == 'deflate') ? zlib.createDeflate() : zlib.createGzip());
					delete dst_res.headers['content-length'];
					dst_res.headers['content-encoding'] = zlibtype.algorithm;

					dst_res.on('data', function (chunk) { log_primitives.bytes_received += chunk.length; });
					_zl.on('data', function (chunk) { log_primitives.bytes_sent += chunk.length; });
					_zl.on('end', function () { logger && logger.log(log_primitives); });

					src_res.writeHead(dst_res.statusCode, dst_res.headers);
					dst_res.pipe(_zl).pipe(src_res);
					break;
				}
			default:
				src_res.writeHead(dst_res.statusCode, dst_res.headers);

				dst_res.on('data', function (chunk) { log_primitives.bytes_sent += chunk.length; });
				dst_res.on('end', function () { logger && logger.log(log_primitives); });

				dst_res.pipe(src_res);
				break;
			}

		});

		src_req.on('data', function (chunk) { dst_req.write(chunk); })
		src_req.on('end', function () { dst_req.end(); });
	} else {
		src_res.writeHead(404, {
			'server': server_string,
			'connection': 'close'
		});
		src_res.end();
		return true;
	}

};

Location.prototype.toString = function () {
	var retStr = ['LOCATION'];
	retStr.push(this._uri);

	for(var i=0; i< this._addproxyheaders.length; i++) {
		retStr.push('HEADER');
		retStr.push(this._addproxyheaders[i].name + '(' + this._addproxyheaders[i].value + ')');
	}
	if(this._rewrite) {
		retStr.push(this._rewrite.range);
		retStr.push(this._rewrite.from.toString() + ' -> ' + this._rewrite.to);
	}
	if(this._forward_raw) {
		retStr.push('FORWARD');
		retStr.push(this._forward_to.transport_name + ' ' + this._forward_to.upstream.toString());
	}
	return retStr.join(': ');
};<|endoftext|>


<commit_before>                       from.package('poopy.js')         .wait();
var             yarn = from.package('Yarn')             .wait(),
    particularizable = from.package('particularizable') .wait();

return (function(){ var percival;
  percival = new(Object);

  percival.quilt = {
    key: {weight: 'bold'},
    string: {underline: 'single'},
    number: {foreground: 'magenta'},
    special: {foreground: 'yellow'}, 'function': {foreground: 'yellow'},
    escape: {inverse: 'negative'},
    'true': {foreground: 'green'},
    'false': {foreground: 'red'}
  };

  // The first two elements of this array are treated specially; do not change
  // them. Beyond that, you’re free to append anything you want escaped to it.
  // Be aware that these have to be escaped such as to be legal in regular
  // expression syntax; so you will likely have to double-escape inside a
  // string literal.
  percival.escapes = ["\\u0001-\\u001F", "\\n", "\\\\", "\\\""];

  percival.peer = function (target, quilt) {
    process.stdio.write(percival.percieve(target)
                          .toString(quilt || percival.quilt) + '\n') };

  percival.percieve = function (target, lens) { var stack;
    var stack = new(Array);

    return (function (target, lens) { var me, sub;
      me = arguments.callee;

      if ((index = stack.indexOf(target)) !== -1) {
        return new(Array)( stack.length - index + 1 ).join('.') };

      sub = function (sub, lens) { var result;
        stack.push(target);
        result = me.apply(percival, arguments);
        stack.pop();
        return result;
      };

      return (lens || lensFor(target, percival.lenses)).apply(target, [sub]);
    })(target, lens);
  };

  var hardEscape = function (str) { var out;
    out = yarn.beget();

    str.match(new(RegExp)("[^"+percival.escapes.join('')+"]+|(?:.|\n)", 'g'))
      .forEach(function (subStr) { var matchings;
        if (matchings = subStr.match(
                new(RegExp)('(['+percival.escapes.join('])|([')+'])') )) {
          switch (matchings[0]) {
            case matchings[2]:
              out.push(yarn.beget({ elements : ['\\0',
                matchings[0].charCodeAt(0).toString(8)] }).label('escape') );
              break;
            case matchings[1]: subStr = 'n';
            default:
              out.push(yarn.beget({ elements : ['\\', subStr] }).label('escape') );
          }
        } else { out.push(subStr) }
      });

    return out;
  };

  // ==================
  // = Bundled lenses =
  // ==================

  percival.lenses = particularizable.ass.beget();

  // The default lens. Applied to all basic JavaScript objects.
  //
  // (Note: Lenses are `apply()`ed, so `this` in this function refers to the
  // object being `probe()`d, not the `percival` object.)
  percival.lenses.set(Object.prototype, function (sub) { var out;
    out = yarn.beget();

    for (key in this) { if (this.hasOwnProperty(key)) {
      out.push(sub( key, percival.lenses.get('key') ), ': ',
               sub( this[key]                       ), ', ') }};

    out.pop(); // To get rid of the final comma… I wish I could use `join()`…
    out.unshift('{');
    out.push   ('}');
    return out;
  });

  // Keys in object literals
  //--
  // TODO: Ensure this won’t fuckup for the *actual `String`* `'key'`
  // TODO: Use hex `\u` escapes instead of octal
  percival.lenses.set('key', function (sub) { var out;
    out = yarn.beget();
    out.label('key');
    out.push(hardEscape(this));
    if (!(/^\w+$/).exec(this)) { out.unshift("'"); out.push("'"); };
    return out;
  });

  // typeof → 'undefined'
  percival.lenses.set('undefined', function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'undefined');
    out.push('undefined');
    return out;
  });

  // === null
  percival.lenses.set(null, function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'null');
    out.push('null');
    return out;
  });

  // === Number.NaN
  percival.lenses.set('NaN', function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'nan');
    out.push('NaN');
    return out;
  });

  // typeof → 'boolean'
  percival.lenses.set('boolean', function (sub) {var out;
    out = yarn.beget();
    out.label('native', 'boolean', 'boolean-native',
                this.toString());
    out.push(this.valueOf());
    return out;
  });

  // Boolean.prototype.isPrototypeOf
  percival.lenses.set(Boolean.prototype, function (sub) {var out, classYarn;
    classYarn = yarn.beget({ elements : ['Boolean'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'boolean', 'boolean-wrapper',
                this.toString());
    out.push(this.valueOf());
    out.unshift('new(', classYarn, ')('); out.push(')');
    return out;
  });

  // typeof → 'string'
  percival.lenses.set('string', function (sub) { var out;
    out = yarn.beget();
    out.label('native', 'string', 'string-native');
    out.push(hardEscape(this));
    out.unshift('"'); out.push('"');
    return out;
  });

  // String.prototype.isPrototypeOf
  percival.lenses.set(String.prototype, function (sub) { var out, classYarn;
    classYarn = yarn.beget({ elements : ['String'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'string', 'string-wrapper');
    out.push(hardEscape(this));
    out.unshift('new(', classYarn, ')("'); out.push('")');
    return out;
  });

  // typeof → 'number'
  percival.lenses.set('number', function (sub) {var out;
    out = yarn.beget();
    out.label('native', 'number', 'number-native');
    out.push(this.valueOf());
    return out;
  });

  // Number.prototype.isPrototypeOf
  percival.lenses.set(Number.prototype, function (sub) {var out, classYarn;
    classYarn = yarn.beget({ elements : ['Number'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'number', 'number-wrapper');
    out.push(this.valueOf());
    out.unshift('new(', classYarn, ')('); out.push(')');
    return out;
  });

  // typeof → 'function'
  percival.lenses.set('function', function (sub) {var out;
    out = yarn.beget();
    out.label('class', 'constructor', 'function');
    out.push('Function');
    return out;
  });

  // Climbs the prototypal inheritance chain, and returns the first lens
  // associated with one of the objects. Will return the `lens` property, if
  // it’s defined, or the relevant element from `lenses`, if not.
  var lensFor = function (thing, lenses) { var me;
    me = arguments.callee;

         if (       thing === null)       { return lenses.get(null) }
    else if (typeof thing === 'number' && isNaN(thing)) {
             return lenses.get('NaN') }

    else if (typeof thing !== 'object')   {
             return lenses.get(typeof thing) }

    else if (typeof thing.lens        !== 'undefined') {
             return thing.lens }

    else if (typeof lenses.get(thing) !== 'undefined') {
             return lenses.get(thing) }

      else { return me.apply(null, [ thing['__proto__'], lenses ]) };
  };

  return percival;
})();
<commit_msg>Slightly re-styling the new hardEscape()<commit_after>                       from.package('poopy.js')         .wait();
var             yarn = from.package('Yarn')             .wait(),
    particularizable = from.package('particularizable') .wait();

return (function(){ var percival;
  percival = new(Object);

  percival.quilt = {
    key: {weight: 'bold'},
    string: {underline: 'single'},
    number: {foreground: 'magenta'},
    special: {foreground: 'yellow'}, 'function': {foreground: 'yellow'},
    escape: {inverse: 'negative'},
    'true': {foreground: 'green'},
    'false': {foreground: 'red'}
  };

  // The first two elements of this array are treated specially; do not change
  // them. Beyond that, you’re free to append anything you want escaped to it.
  // Be aware that these have to be escaped such as to be legal in regular
  // expression syntax; so you will likely have to double-escape inside a
  // string literal.
  percival.escapes = ["\\u0001-\\u001F", "\\n", "\\\\", "\\\""];

  percival.peer = function (target, quilt) {
    process.stdio.write(percival.percieve(target)
                          .toString(quilt || percival.quilt) + '\n') };

  percival.percieve = function (target, lens) { var stack;
    var stack = new(Array);

    return (function (target, lens) { var me, sub;
      me = arguments.callee;

      if ((index = stack.indexOf(target)) !== -1) {
        return new(Array)( stack.length - index + 1 ).join('.') };

      sub = function (sub, lens) { var result;
        stack.push(target);
        result = me.apply(percival, arguments);
        stack.pop();
        return result;
      };

      return (lens || lensFor(target, percival.lenses)).apply(target, [sub]);
    })(target, lens);
  };

  var hardEscape = function (str) { var out;
    out = yarn.beget();

    str.match(new(RegExp)("[^"+percival.escapes.join('')+"]+|(?:.|\n)", 'g'))
      .forEach(function (sub) { var matchings; if (matchings = sub.match(
              new(RegExp)('(['+percival.escapes.join('])|([')+'])') )) {
        switch (matchings[0]) {
          case  matchings[2]:
            out.push(yarn.beget({ elements : ['\\0',
                matchings[0].charCodeAt(0).toString(8)] }).label('escape') );
            break;
          case  matchings[1]: sub = 'n';
          default:
            out.push(yarn.beget({ elements : ['\\', sub] }).label('escape') );
        }} else { out.push(sub) }
      });

    return out;
  };

  // ==================
  // = Bundled lenses =
  // ==================

  percival.lenses = particularizable.ass.beget();

  // The default lens. Applied to all basic JavaScript objects.
  //
  // (Note: Lenses are `apply()`ed, so `this` in this function refers to the
  // object being `probe()`d, not the `percival` object.)
  percival.lenses.set(Object.prototype, function (sub) { var out;
    out = yarn.beget();

    for (key in this) { if (this.hasOwnProperty(key)) {
      out.push(sub( key, percival.lenses.get('key') ), ': ',
               sub( this[key]                       ), ', ') }};

    out.pop(); // To get rid of the final comma… I wish I could use `join()`…
    out.unshift('{');
    out.push   ('}');
    return out;
  });

  // Keys in object literals
  //--
  // TODO: Ensure this won’t fuckup for the *actual `String`* `'key'`
  // TODO: Use hex `\u` escapes instead of octal
  percival.lenses.set('key', function (sub) { var out;
    out = yarn.beget();
    out.label('key');
    out.push(hardEscape(this));
    if (!(/^\w+$/).exec(this)) { out.unshift("'"); out.push("'"); };
    return out;
  });

  // typeof → 'undefined'
  percival.lenses.set('undefined', function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'undefined');
    out.push('undefined');
    return out;
  });

  // === null
  percival.lenses.set(null, function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'null');
    out.push('null');
    return out;
  });

  // === Number.NaN
  percival.lenses.set('NaN', function (sub) {var out;
    out = yarn.beget();
    out.label('special', 'nothingness', 'nan');
    out.push('NaN');
    return out;
  });

  // typeof → 'boolean'
  percival.lenses.set('boolean', function (sub) {var out;
    out = yarn.beget();
    out.label('native', 'boolean', 'boolean-native',
                this.toString());
    out.push(this.valueOf());
    return out;
  });

  // Boolean.prototype.isPrototypeOf
  percival.lenses.set(Boolean.prototype, function (sub) {var out, classYarn;
    classYarn = yarn.beget({ elements : ['Boolean'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'boolean', 'boolean-wrapper',
                this.toString());
    out.push(this.valueOf());
    out.unshift('new(', classYarn, ')('); out.push(')');
    return out;
  });

  // typeof → 'string'
  percival.lenses.set('string', function (sub) { var out;
    out = yarn.beget();
    out.label('native', 'string', 'string-native');
    out.push(hardEscape(this));
    out.unshift('"'); out.push('"');
    return out;
  });

  // String.prototype.isPrototypeOf
  percival.lenses.set(String.prototype, function (sub) { var out, classYarn;
    classYarn = yarn.beget({ elements : ['String'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'string', 'string-wrapper');
    out.push(hardEscape(this));
    out.unshift('new(', classYarn, ')("'); out.push('")');
    return out;
  });

  // typeof → 'number'
  percival.lenses.set('number', function (sub) {var out;
    out = yarn.beget();
    out.label('native', 'number', 'number-native');
    out.push(this.valueOf());
    return out;
  });

  // Number.prototype.isPrototypeOf
  percival.lenses.set(Number.prototype, function (sub) {var out, classYarn;
    classYarn = yarn.beget({ elements : ['Number'],
                               labels : ['class', 'constructor'] });

    out = yarn.beget();
    out.label('native-wrapper', 'number', 'number-wrapper');
    out.push(this.valueOf());
    out.unshift('new(', classYarn, ')('); out.push(')');
    return out;
  });

  // typeof → 'function'
  percival.lenses.set('function', function (sub) {var out;
    out = yarn.beget();
    out.label('class', 'constructor', 'function');
    out.push('Function');
    return out;
  });

  // Climbs the prototypal inheritance chain, and returns the first lens
  // associated with one of the objects. Will return the `lens` property, if
  // it’s defined, or the relevant element from `lenses`, if not.
  var lensFor = function (thing, lenses) { var me;
    me = arguments.callee;

         if (       thing === null)       { return lenses.get(null) }
    else if (typeof thing === 'number' && isNaN(thing)) {
             return lenses.get('NaN') }

    else if (typeof thing !== 'object')   {
             return lenses.get(typeof thing) }

    else if (typeof thing.lens        !== 'undefined') {
             return thing.lens }

    else if (typeof lenses.get(thing) !== 'undefined') {
             return lenses.get(thing) }

      else { return me.apply(null, [ thing['__proto__'], lenses ]) };
  };

  return percival;
})();
<|endoftext|>


<commit_before>"use strict"

const Loader = require("./Loader");
const vocab = "<http://schema.jillix.net/vocab/";

module.exports = (scope, sequence_id, event) => {
    return Loader(scope, sequence_id, (sequence) => {
        if (sequence.roles[event.role]) {
            return Promise.resolve([event, sequence]);
        } else {
           return Promise.reject(new Error('Flow: Sorry, no access. Roles:' + Object.keys(sequence.roles) + ' Role:' + event.role));
        }

    }, (resolve, sequence) => {
        resolve([event, sequence]);

    }, (loader) => {

        const sequence = {
            id: sequence_id,
            roles: {}
        };

        setImmediate(() => {
            const triples = scope.seq(scope, sequence_id, event.role);
            triples.on('end', () => {loader.resolve(sequence)});
            triples.on('error', (err) => {loader.reject(err)});
            triples.on("data", (triple) => {

                let subject = triple[0] || triple.subject;
                let predicate = triple[1] || triple.predicate;
                let object = triple[2] || triple.object;

                switch (predicate) {
                    case vocab + 'onError>':
                        sequence.err = object;
                        break;
                    case vocab + 'role>':
                        sequence.roles[object] = true;
                        break;
                    case vocab + 'next>':
                        if (subject === sequence.id) {
                            sequence.first = object;
                        } else {
                            setHandler(sequence, subject, 'next', object);
                        }
                        break;
                    case vocab + 'args>':
                        try {
                            setHandler(sequence, subject, 'args', Object.freeze(JSON.parse(object)));
                        } catch (err) {
                            return loader.reject(err);
                        }
                        break;
                    case vocab + 'state>':
                        setHandler(sequence, subject ,'state', getState(scope, object));
                        break;
                    case vocab + 'fn>':
                        loader.wait.push(Fn(scope, sequence, subject, object, event.role));
                        break;
                    default:
                        loader.reject(new Error('[Parser] Unknown triple: ' + predicate));
                }
            });
        });
    });
};

function Fn (scope, sequence, handler_id, fn_iri, role) {
    return Loader(scope, fn_iri, (fn) => {
        setHandler(sequence, handler_id, "fn", fn);
        return Promise.resolve(fn);

    }, (resolve, fn) => {
        setHandler(sequence, handler_id, "fn", fn);
        resolve(fn);

    }, (loader) => {
        scope.fn(fn_iri, role, (err, fn) => {
            if (err) {
                return loader.reject(err);
            }
            loader.resolve(fn);
        });
    });
};

function getState (scope, state_id) {
    let state = scope.cache.get(state_id);
    if (state) {
        return state;
    }

    state = {};
    scope.cache.set(state_id, state);
    return state;
}

function setHandler (seq, handler, key, value) {
    seq[handler] = seq[handler] || {};
    seq[handler][key] = value;
}
<commit_msg>format<commit_after>"use strict"

const Loader = require("./Loader");
const vocab = "<http://schema.jillix.net/vocab/";

module.exports = (scope, sequence_id, event) => {
    return Loader(scope, sequence_id, (sequence) => {
        if (sequence.roles[event.role]) {
            return Promise.resolve([event, sequence]);
        } else {
            return Promise.reject(new Error('Flow: Sorry, no access. Roles:' + Object.keys(sequence.roles) + ' Role:' + event.role));
        }

    }, (resolve, sequence) => {
        resolve([event, sequence]);

    }, (loader) => {

        const sequence = {
            id: sequence_id,
            roles: {}
        };

        setImmediate(() => {
            const triples = scope.seq(scope, sequence_id, event.role);
            triples.on('end', () => {loader.resolve(sequence)});
            triples.on('error', (err) => {loader.reject(err)});
            triples.on("data", (triple) => {

                let subject = triple[0] || triple.subject;
                let predicate = triple[1] || triple.predicate;
                let object = triple[2] || triple.object;

                switch (predicate) {
                    case vocab + 'onError>':
                        sequence.err = object;
                        break;
                    case vocab + 'role>':
                        sequence.roles[object] = true;
                        break;
                    case vocab + 'next>':
                        if (subject === sequence.id) {
                            sequence.first = object;
                        } else {
                            setHandler(sequence, subject, 'next', object);
                        }
                        break;
                    case vocab + 'args>':
                        try {
                            setHandler(sequence, subject, 'args', Object.freeze(JSON.parse(object)));
                        } catch (err) {
                            return loader.reject(err);
                        }
                        break;
                    case vocab + 'state>':
                        setHandler(sequence, subject ,'state', getState(scope, object));
                        break;
                    case vocab + 'fn>':
                        loader.wait.push(Fn(scope, sequence, subject, object, event.role));
                        break;
                    default:
                        loader.reject(new Error('[Parser] Unknown triple: ' + predicate));
                }
            });
        });
    });
};

function Fn (scope, sequence, handler_id, fn_iri, role) {
    return Loader(scope, fn_iri, (fn) => {
        setHandler(sequence, handler_id, "fn", fn);
        return Promise.resolve(fn);

    }, (resolve, fn) => {
        setHandler(sequence, handler_id, "fn", fn);
        resolve(fn);

    }, (loader) => {
        scope.fn(fn_iri, role, (err, fn) => {
            if (err) {
                return loader.reject(err);
            }
            loader.resolve(fn);
        });
    });
};

function getState (scope, state_id) {
    let state = scope.cache.get(state_id);
    if (state) {
        return state;
    }

    state = {};
    scope.cache.set(state_id, state);
    return state;
}

function setHandler (seq, handler, key, value) {
    seq[handler] = seq[handler] || {};
    seq[handler][key] = value;
}
<|endoftext|>


<commit_before>'use strict';

var babelHelpers = require('./util/babelHelpers.js');

var React = require('react'),
    dates = require('./util/dates'),
    List = require('./List'),
    localizers = require('./util/configuration').locale,
    CustomPropTypes = require('./util/propTypes');

var format = function format(props) {
  return props.format || localizers.date.formats.time;
};

module.exports = React.createClass({

  displayName: 'TimeList',

  propTypes: {
    value: React.PropTypes.instanceOf(Date),
    min: React.PropTypes.instanceOf(Date),
    max: React.PropTypes.instanceOf(Date),
    step: React.PropTypes.number,
    itemComponent: CustomPropTypes.elementType,
    format: CustomPropTypes.dateFormat,
    onSelect: React.PropTypes.func,
    preserveDate: React.PropTypes.bool,
    culture: React.PropTypes.string
  },

  mixins: [require('./mixins/TimeoutMixin')],

  getDefaultProps: function getDefaultProps() {
    return {
      step: 30,
      onSelect: function onSelect() {},
      min: new Date(1900, 0, 1),
      max: new Date(2099, 11, 31),
      preserveDate: true,
      delay: 300
    };
  },

  getInitialState: function getInitialState() {
    var data = this._dates(this.props),
        focusedItem = this._closestDate(data, this.props.value);

    return {
      focusedItem: focusedItem || data[0],
      dates: data
    };
  },

  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
    var data = this._dates(nextProps),
        focusedItem = this._closestDate(data, nextProps.value),
        valChanged = !dates.eq(nextProps.value, this.props.value, 'minutes'),
        minChanged = !dates.eq(nextProps.min, this.props.min, 'minutes'),
        maxChanged = !dates.eq(nextProps.max, this.props.max, 'minutes');

    if (valChanged || minChanged || maxChanged) {
      this.setState({
        focusedItem: focusedItem || data[0],
        dates: data
      });
    }
  },

  render: function render() {
    var _props = this.props;
    var min = _props.min;
    var max = _props.max;
    var value = _props.value;
    var step = _props.step;
    var props = babelHelpers.objectWithoutProperties(_props, ['min', 'max', 'value', 'step']);

    var times = this.state.dates,
        date = this._closestDate(times, value);

    var adjustHours = 3;
    var adjustPlaces = 60 / step * adjustHours;
    var moveTimes = times.splice(adjustPlaces, 0);
    times = times.concat(moveTimes);

    return React.createElement(List, babelHelpers._extends({}, props, {
      ref: 'list',
      data: times,
      textField: 'label',
      valueField: 'date',
      selected: date,
      focused: this.state.focusedItem
    }));
  },

  _closestDate: function _closestDate(times, date) {
    var roundTo = 1000 * 60 * this.props.step,
        inst = null,
        label;

    if (!date) return null;

    date = new Date(Math.floor(date.getTime() / roundTo) * roundTo);
    label = dates.format(date, this.props.format, this.props.culture);

    times.some(function (time) {
      if (time.label === label) return inst = time;
    });

    return inst;
  },

  _data: function _data() {
    return this.state.dates;
  },

  _dates: function _dates(props) {
    var times = [],
        i = 0,
        values = this._dateValues(props),
        start = values.min,
        startDay = dates.date(start);

    while (dates.date(start) === startDay && dates.lte(start, values.max)) {
      i++;
      times.push({ date: start, label: localizers.date.format(start, format(props), props.culture) });
      start = dates.add(start, props.step || 30, 'minutes');
    }
    return times;
  },

  _dateValues: function _dateValues(props) {
    var value = props.value || dates.today(),
        useDate = props.preserveDate,
        min = props.min,
        max = props.max,
        start,
        end;

    //compare just the time regradless of whether they fall on the same day
    if (!useDate) {
      start = dates.startOf(dates.merge(new Date(), min), 'minutes');
      end = dates.startOf(dates.merge(new Date(), max), 'minutes');

      if (dates.lte(end, start) && dates.gt(max, min, 'day')) end = dates.tomorrow();

      return {
        min: start,
        max: end
      };
    }

    start = dates.today();
    end = dates.tomorrow();
    //date parts are equal
    return {
      min: dates.eq(value, min, 'day') ? dates.merge(start, min) : start,
      max: dates.eq(value, max, 'day') ? dates.merge(start, max) : end
    };
  },

  _keyDown: function _keyDown(e) {
    var _this = this;

    var key = e.key,
        character = String.fromCharCode(e.keyCode),
        focusedItem = this.state.focusedItem,
        list = this.refs.list;

    if (key === 'End') this.setState({ focusedItem: list.last() });else if (key === 'Home') this.setState({ focusedItem: list.first() });else if (key === 'Enter') this.props.onSelect(focusedItem);else if (key === 'ArrowDown') {
      e.preventDefault();
      this.setState({ focusedItem: list.next(focusedItem) });
    } else if (key === 'ArrowUp') {
      e.preventDefault();
      this.setState({ focusedItem: list.prev(focusedItem) });
    } else {
      e.preventDefault();

      this.search(character, function (item) {
        _this.setState({ focusedItem: item });
      });
    }
  },

  scrollTo: function scrollTo() {
    this.refs.list.move && this.refs.list.move();
  },

  search: function search(character, cb) {
    var _this2 = this;

    var word = ((this._searchTerm || '') + character).toLowerCase();

    this._searchTerm = word;

    this.setTimeout('search', function () {
      var list = _this2.refs.list,
          item = list.next(_this2.state.focusedItem, word);

      _this2._searchTerm = '';
      if (item) cb(item);
    }, this.props.delay);
  }

});<commit_msg>start times at 9am<commit_after>'use strict';

var babelHelpers = require('./util/babelHelpers.js');

var React = require('react'),
    dates = require('./util/dates'),
    List = require('./List'),
    localizers = require('./util/configuration').locale,
    CustomPropTypes = require('./util/propTypes');

var format = function format(props) {
  return props.format || localizers.date.formats.time;
};

module.exports = React.createClass({

  displayName: 'TimeList',

  propTypes: {
    value: React.PropTypes.instanceOf(Date),
    min: React.PropTypes.instanceOf(Date),
    max: React.PropTypes.instanceOf(Date),
    step: React.PropTypes.number,
    itemComponent: CustomPropTypes.elementType,
    format: CustomPropTypes.dateFormat,
    onSelect: React.PropTypes.func,
    preserveDate: React.PropTypes.bool,
    culture: React.PropTypes.string
  },

  mixins: [require('./mixins/TimeoutMixin')],

  getDefaultProps: function getDefaultProps() {
    return {
      step: 30,
      onSelect: function onSelect() {},
      min: new Date(1900, 0, 1),
      max: new Date(2099, 11, 31),
      preserveDate: true,
      delay: 300
    };
  },

  getInitialState: function getInitialState() {
    var data = this._dates(this.props),
        focusedItem = this._closestDate(data, this.props.value);

    return {
      focusedItem: focusedItem || data[0],
      dates: data
    };
  },

  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
    var data = this._dates(nextProps),
        focusedItem = this._closestDate(data, nextProps.value),
        valChanged = !dates.eq(nextProps.value, this.props.value, 'minutes'),
        minChanged = !dates.eq(nextProps.min, this.props.min, 'minutes'),
        maxChanged = !dates.eq(nextProps.max, this.props.max, 'minutes');

    if (valChanged || minChanged || maxChanged) {
      this.setState({
        focusedItem: focusedItem || data[0],
        dates: data
      });
    }
  },

  render: function render() {
    var _props = this.props;
    var min = _props.min;
    var max = _props.max;
    var value = _props.value;
    var step = _props.step;
    var props = babelHelpers.objectWithoutProperties(_props, ['min', 'max', 'value', 'step']);

    var times = this.state.dates,
        date = this._closestDate(times, value);

    var adjustHours = 3;
    var adjustPlaces = 60 / step * adjustHours;
    var moveTimes = times.splice(adjustPlaces, 0);
    times = times.concat(moveTimes);

    console.log('TIMES', times);

    return React.createElement(List, babelHelpers._extends({}, props, {
      ref: 'list',
      data: times,
      textField: 'label',
      valueField: 'date',
      selected: date,
      focused: this.state.focusedItem
    }));
  },

  _closestDate: function _closestDate(times, date) {
    var roundTo = 1000 * 60 * this.props.step,
        inst = null,
        label;

    if (!date) return null;

    date = new Date(Math.floor(date.getTime() / roundTo) * roundTo);
    label = dates.format(date, this.props.format, this.props.culture);

    times.some(function (time) {
      if (time.label === label) return inst = time;
    });

    return inst;
  },

  _data: function _data() {
    return this.state.dates;
  },

  _dates: function _dates(props) {
    var times = [],
        i = 0,
        values = this._dateValues(props),
        start = values.min,
        startDay = dates.date(start);

    while (dates.date(start) === startDay && dates.lte(start, values.max)) {
      i++;
      times.push({ date: start, label: localizers.date.format(start, format(props), props.culture) });
      start = dates.add(start, props.step || 30, 'minutes');
    }
    return times;
  },

  _dateValues: function _dateValues(props) {
    var value = props.value || dates.today(),
        useDate = props.preserveDate,
        min = props.min,
        max = props.max,
        start,
        end;

    //compare just the time regradless of whether they fall on the same day
    if (!useDate) {
      start = dates.startOf(dates.merge(new Date(), min), 'minutes');
      end = dates.startOf(dates.merge(new Date(), max), 'minutes');

      if (dates.lte(end, start) && dates.gt(max, min, 'day')) end = dates.tomorrow();

      return {
        min: start,
        max: end
      };
    }

    start = dates.today();
    end = dates.tomorrow();
    //date parts are equal
    return {
      min: dates.eq(value, min, 'day') ? dates.merge(start, min) : start,
      max: dates.eq(value, max, 'day') ? dates.merge(start, max) : end
    };
  },

  _keyDown: function _keyDown(e) {
    var _this = this;

    var key = e.key,
        character = String.fromCharCode(e.keyCode),
        focusedItem = this.state.focusedItem,
        list = this.refs.list;

    if (key === 'End') this.setState({ focusedItem: list.last() });else if (key === 'Home') this.setState({ focusedItem: list.first() });else if (key === 'Enter') this.props.onSelect(focusedItem);else if (key === 'ArrowDown') {
      e.preventDefault();
      this.setState({ focusedItem: list.next(focusedItem) });
    } else if (key === 'ArrowUp') {
      e.preventDefault();
      this.setState({ focusedItem: list.prev(focusedItem) });
    } else {
      e.preventDefault();

      this.search(character, function (item) {
        _this.setState({ focusedItem: item });
      });
    }
  },

  scrollTo: function scrollTo() {
    this.refs.list.move && this.refs.list.move();
  },

  search: function search(character, cb) {
    var _this2 = this;

    var word = ((this._searchTerm || '') + character).toLowerCase();

    this._searchTerm = word;

    this.setTimeout('search', function () {
      var list = _this2.refs.list,
          item = list.next(_this2.state.focusedItem, word);

      _this2._searchTerm = '';
      if (item) cb(item);
    }, this.props.delay);
  }

});<|endoftext|>


<commit_before>/*
 *  IOTDBTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-04-01
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;
var bunyan = iotdb.bunyan;

var path = require('path');

var util = require('util');
var url = require('url');

var logger = bunyan.createLogger({
    name: 'iotdb-transport-iotdb',
    module: 'IOTDBTransport',
});

/* --- constructor --- */
/**
 *  Create a Transporter for IOTDB Things.
 *

 *  Bands for IOTDB are inherenly "istate", "ostate", "model", "meta".
 *

 *  See {iotdb.transporter.Transport#Transport} for documentation.
 *
 *  @constructor
 */
var IOTDBTransport = function (initd, things) {
    var self = this;

    if (arguments.length === 1) {
        initd = {};
        things = arguments[0];
    }

    self.initd = _.defaults(
        initd,
        iotdb.keystore().get("/transports/IOTDBTransport/initd"),
        {
        }
    );

    if (!_.is.ThingArray(things)) {
        throw new Error("things is required and must be a ThingArray");
    }

    self.native = things;
};

IOTDBTransport.prototype = new iotdb.transporter.Transport;

/* --- methods --- */
/**
 *  See {iotdb.transporter.Transport#list} for documentation.
 */
IOTDBTransport.prototype.list = function(paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_list(paramd, callback);

    for (var i = 0; i < self.native.length; i++) {
        var thing = self.native[i];
        callback({
            id: thing.thing_id(),
        });
    }

    callback(null);
};

/**
 *  See {iotdb.transporter.Transport#added} for documentation.
 */
IOTDBTransport.prototype.added = function(paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_added(paramd, callback);

    self.native.on("thing", function(thing) {
        callback({
            id: thing.thing_id(),
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#get} for documentation.
 */
IOTDBTransport.prototype.get = function(id, band, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var thing = self._thing_by_id(paramd.id);
    if (!thing) {
        return callback({
            id: paramd.id,
            band: paramd.band,
            value: null,
        });
    }

    return callback({
        id: id,
        band: band,
        value: self._get_thing_band(thing, band),
    });
};

/**
 *  See {iotdb.transporter.Transport#update} for documentation.
 *

 *  NOT FINISHED
 */
IOTDBTransport.prototype.update = function(paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    /* XXX: at some point in the future we should be able to add new things */
    var thing = self._thing_by_id(paramd.id);
    if (!thing) {
        /* XXX: maybe raise an exception? */
        return;
    }

    if (paramd.band === "ostate") {
        thing.update(paramd.value, { notify: true });
    } else if (paramd.band === "ostate") {
    } else if (paramd.band === "meta") {
    } else {
    }
};

/**
 *  See {iotdb.transporter.Transport#updated} for documentation.
 */
IOTDBTransport.prototype.updated = function(paramd, callback) {
    var self = this;

    self._validate_updated(paramd, callback);

    var _monitor_band = function(_band) {
        if ((_band === "istate") || (_band === "ostate") || (_band === "meta")) {
            self.native.on(_band, function(thing) {
                if (paramd.id && (thing.thing_id() !== paramd.id)) {
                    return;
                }

                callback(thing.thing_id(), _band, self._get_thing_band(thing, _band));
            });
        } else if (_band === "model") {
        } else {
            return null;
        }
    };

    if (paramd.band) {
        _monitor_band(paramd.band);
    } else {
        var bands = [ "istate", "ostate", "meta", "model" ];
        for (var bi in bands) {
            _monitor_band(bands[bi]);
        };
    }
};

/* -- internals -- */
IOTDBTransport.prototype._thing_by_id = function(id) {
    var self = this;

    for (var i = 0; i < self.native.length; i++) {
        var thing = self.native[i];
        if (thing.thing_id() === id) {
            return thing;
        }
    }

    return null;
};

IOTDBTransport.prototype._get_thing_band = function(thing, band) {
    if (!band) {
        return {
            bands: [ "istate", "ostate", "model", "meta" ],
        }
    } else if (band === "istate") {
        return thing.state({ istate: true, ostate: false });
    } else if (band === "ostate") {
        return thing.state({ istate: false, ostate: true });
    } else if (band === "model") {
        return _.ld.compact(thing.jsonld());
    } else if (band === "meta") {
        return _.ld.compact(thing.meta().state());
    } else {
        return null;
    }
};

/**
 *  API
 */
exports.IOTDBTransport = IOTDBTransport;
<commit_msg>modernize API<commit_after>/*
 *  IOTDBTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-04-01
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;
var bunyan = iotdb.bunyan;

var path = require('path');

var util = require('util');
var url = require('url');

var logger = bunyan.createLogger({
    name: 'iotdb-transport-iotdb',
    module: 'IOTDBTransport',
});

/* --- constructor --- */
/**
 *  Create a Transporter for IOTDB Things.
 *

 *  Bands for IOTDB are inherenly "istate", "ostate", "model", "meta".
 *

 *  See {iotdb.transporter.Transport#Transport} for documentation.
 *
 *  @constructor
 */
var IOTDBTransport = function (initd, things) {
    var self = this;

    if (arguments.length === 1) {
        initd = {};
        things = arguments[0];
    }

    self.initd = _.defaults(
        initd,
        iotdb.keystore().get("/transports/IOTDBTransport/initd"),
        {
        }
    );

    if (!_.is.ThingArray(things)) {
        throw new Error("things is required and must be a ThingArray");
    }

    self.native = things;
};

IOTDBTransport.prototype = new iotdb.transporter.Transport;

/* --- methods --- */
/**
 *  See {iotdb.transporter.Transport#list} for documentation.
 */
IOTDBTransport.prototype.list = function(paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_list(paramd, callback);

    for (var i = 0; i < self.native.length; i++) {
        var thing = self.native[i];
        callback({
            id: thing.thing_id(),
        });
    }

    callback(null);
};

/**
 *  See {iotdb.transporter.Transport#added} for documentation.
 */
IOTDBTransport.prototype.added = function(paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_added(paramd, callback);

    self.native.on("thing", function(thing) {
        callback({
            id: thing.thing_id(),
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#get} for documentation.
 */
IOTDBTransport.prototype.get = function(paramd, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var thing = self._thing_by_id(paramd.id);
    if (!thing) {
        return callback({
            id: paramd.id,
            band: paramd.band,
            value: null,
        });
    }

    return callback({
        id: paramd.id,
        band: paramd.band,
        value: self._get_thing_band(thing, paramd.band),
    });
};

/**
 *  See {iotdb.transporter.Transport#update} for documentation.
 *

 *  NOT FINISHED
 */
IOTDBTransport.prototype.update = function(paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    /* XXX: at some point in the future we should be able to add new things */
    var thing = self._thing_by_id(paramd.id);
    if (!thing) {
        /* XXX: maybe raise an exception? */
        return;
    }

    if (paramd.band === "ostate") {
        thing.update(paramd.value, { notify: true });
    } else if (paramd.band === "ostate") {
    } else if (paramd.band === "meta") {
    } else {
    }
};

/**
 *  See {iotdb.transporter.Transport#updated} for documentation.
 */
IOTDBTransport.prototype.updated = function(paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_updated(paramd, callback);

    var _monitor_band = function(_band) {
        if ((_band === "istate") || (_band === "ostate") || (_band === "meta")) {
            self.native.on(_band, function(thing) {
                if (paramd.id && (thing.thing_id() !== paramd.id)) {
                    return;
                }

                callback({
                    id: thing.thing_id(),
                    band: _band,
                    value: self._get_thing_band(thing, _band),
                });
            });
        } else if (_band === "model") {
        } else {
            return null;
        }
    };

    if (paramd.band) {
        _monitor_band(paramd.band);
    } else {
        var bands = [ "istate", "ostate", "meta", "model" ];
        for (var bi in bands) {
            _monitor_band(bands[bi]);
        };
    }
};

/* -- internals -- */
IOTDBTransport.prototype._thing_by_id = function(id) {
    var self = this;

    for (var i = 0; i < self.native.length; i++) {
        var thing = self.native[i];
        if (thing.thing_id() === id) {
            return thing;
        }
    }

    return null;
};

IOTDBTransport.prototype._get_thing_band = function(thing, band) {
    if (band === ".") {
        return {
            bands: [ "istate", "ostate", "model", "meta" ],
        }
    } else if (band === "istate") {
        return thing.state({ istate: true, ostate: false });
    } else if (band === "ostate") {
        return thing.state({ istate: false, ostate: true });
    } else if (band === "model") {
        return _.ld.compact(thing.jsonld());
    } else if (band === "meta") {
        return _.ld.compact(thing.meta().state());
    } else {
        return null;
    }
};

/**
 *  API
 */
exports.IOTDBTransport = IOTDBTransport;
<|endoftext|>


<commit_before>var _ = require('lodash'),
    Promise = require('bluebird'),
    util = require('../util'),
    log = util.logger();

var LEADS = util.createPath('leads.json');

function Lead(marketo, connection) {
  this._marketo = marketo;
  this._connection = connection;
}

Lead.prototype = {
  byId: function(id, options) {
    var path = util.createPath('lead', id + '.json');
    options = util.formatOptions(options, 'fields');

    return this._connection.get(path, {query: options});
  },

  find: function(filterType, filterValues, options) {
    if (!_.isArray(filterValues)) {
      var msg = 'filterValues needs to be an Array';
      log.error(msg);
      return Promise.reject(msg);
    }

    options = _.extend({}, options, {
      filterType: filterType,
      filterValues: filterValues,
      _method: 'GET'
    });
    options = util.formatOptions(options);

    return this._connection.post(LEADS, {data: options});
  },

  createOrUpdate: function(input, options) {
    if (!_.isArray(input) && !_.isEmpty(input)) {
      var msg = 'input must be an array of leads';
      log.error(msg);
      return Promise.reject(msg);
    }

    var data = _.extend({}, options, {
      input: input
    });

    return this._connection.postJson(LEADS, data)
      .then(function(data) {
        if (data.success) {
          return data;
        } else {
          log.warn('Cannot create/update lead: ', data);
          return Promise.reject('Cannot get lead(s) from input: ' + JSON.stringify(input));
        }
      });
  },

  describe: function() {
    var path = util.createPath('leads', 'describe.json');
    return this._connection.get(path);
  },

  partitions: function() {
    var path = util.createPath('leads', 'partitions.json');
    return this._connection.get(path);
  }
};

module.exports = Lead;
<commit_msg>Add mergeLead method<commit_after>var _ = require('lodash'),
    Promise = require('bluebird'),
    util = require('../util'),
    log = util.logger();

var LEADS = util.createPath('leads.json');

function Lead(marketo, connection) {
  this._marketo = marketo;
  this._connection = connection;
}

Lead.prototype = {
  byId: function(id, options) {
    var path = util.createPath('lead', id + '.json');
    options = util.formatOptions(options, 'fields');

    return this._connection.get(path, {query: options});
  },

  find: function(filterType, filterValues, options) {
    if (!_.isArray(filterValues)) {
      var msg = 'filterValues needs to be an Array';
      log.error(msg);
      return Promise.reject(msg);
    }

    options = _.extend({}, options, {
      filterType: filterType,
      filterValues: filterValues,
      _method: 'GET'
    });
    options = util.formatOptions(options);

    return this._connection.post(LEADS, {data: options});
  },

  createOrUpdate: function(input, options) {
    if (!_.isArray(input) && !_.isEmpty(input)) {
      var msg = 'input must be an array of leads';
      log.error(msg);
      return Promise.reject(msg);
    }

    var data = _.extend({}, options, {
      input: input
    });

    return this._connection.postJson(LEADS, data)
      .then(function(data) {
        if (data.success) {
          return data;
        } else {
          log.warn('Cannot create/update lead: ', data);
          return Promise.reject('Cannot get lead(s) from input: ' + JSON.stringify(input));
        }
      });
  },

  describe: function() {
    var path = util.createPath('leads', 'describe.json');
    return this._connection.get(path);
  },

  partitions: function() {
    var path = util.createPath('leads', 'partitions.json');
    return this._connection.get(path);
  },

  mergeLead: function(winningLead, losingLeads, options) {
    if (!_.isArray(losingLeads) && !_.isEmpty(losingLeads)) {
      var msg = 'input must be an array of lead ids';
      log.error(msg);
      return Promise.reject(msg);
    }

    var path = util.createPath('leads', winningLead, 'merge.json');
    return this._connection.postJson(path, {data: options}, {query: {leadIds: losingLeads.join()}});
  }
};

module.exports = Lead;
<|endoftext|>